SECURITY DEFINER Functions Guard Privileges
Grant a function owner privileges with SECURITY DEFINER, pin search_path against hijacking, and restrict execution to one role.
Code
-- SECURITY DEFINER:函数以拥有者权限执行,调用者无需直接访问底表
CREATE TABLE IF NOT EXISTS payroll (
employee_id bigint PRIMARY KEY,
salary numeric(12, 2) NOT NULL
);
CREATE OR REPLACE FUNCTION employee_salary(target bigint)
RETURNS numeric
LANGUAGE sql
SECURITY DEFINER
SET search_path = public, pg_temp
AS $$
SELECT salary FROM payroll WHERE employee_id = target;
$$;
-- 撤销 PUBLIC 的执行权,只授权给指定角色
REVOKE ALL ON FUNCTION employee_salary(bigint) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION employee_salary(bigint) TO payroll_reader;
-- 检查函数的安全属性
SELECT proname, prosecdef, proconfig
FROM pg_proc
WHERE proname = 'employee_salary';
-- 注意:SECURITY DEFINER 必须固定 search_path,防止对象劫持How it works
Several statements share this file — SELECT / CREATE, with payroll, public and pg_proc among the objects involved.
Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
Point it at the payroll table.
Key statements
CREATE OR REPLACE FUNCTION employee_salary(target bigint)
RETURNS numeric
LANGUAGE sql
SECURITY DEFINER
SET search_path = public, pg_temp
AS $$
SELECT salary FROM payroll WHERE employee_id = target;
SELECT proname, prosecdef, proconfig
FROM pg_proc
WHERE proname = 'employee_salary';
CREATE TABLE IF NOT EXISTS payroll (
employee_id bigint PRIMARY KEY,
salary numeric(12, 2) NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- Which tables appear in this script?
- `payroll`, `public`, `pg_proc` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.