SECURITY DEFINER Functions Guard Privileges

Grant a function owner privileges with SECURITY DEFINER, pin search_path against hijacking, and restrict execution to one role.

SqlSecurity Boundaries

Code

snippet
-- 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

FAQ

Which tables appear in this script?
`payroll`, `public`, `pg_proc` — referenced directly, no join needed.