Sub topic 13
SECURITY DEFINER done safely
This chapter assumes you can write a basic SQL function, and that you know how roles, schemas, GRANT and REVOKE work. By the end you will know how to create a SECURITY DEFINER function that does not hand its owner's privileges to anyone who calls it.
What SECURITY DEFINER changes
A function runs with one of two security contexts:
SECURITY INVOKER(the default) runs the body with the privileges of the role that calls the function.SECURITY DEFINERruns the body with the privileges of the role that owns the function.
Definer functions let you expose a narrow, controlled operation on a table that the caller cannot touch directly. A role can read one account balance without having SELECT on the whole accounts table. The cost is that the function body is now a privilege boundary. Anything the caller can influence (arguments, search_path, who may call it) becomes part of your attack surface.
The four hazards
- Default execute rights.
CREATE FUNCTIONgrantsEXECUTEtoPUBLIC, which means every role. A new definer function is therefore callable by everyone until you revoke that. - search_path hijacking. Unqualified names in the body are resolved through the caller's
search_path. A caller can put a schema they control first and plant a table, view, function, or operator with the same name as one your function uses. The function then runs the attacker's object with the owner's privileges. - An over-privileged owner. If a superuser owns the function, a bug in it can act as a superuser.
- Trusting caller-supplied values. The function sees the owner's access, so it must enforce any row-level rules itself.
A safe definer function
This example puts the function in a schema, gives it a dedicated owner, pins search_path, and controls who can call it.
CREATE ROLE bank_owner NOLOGIN;
CREATE ROLE app_reader NOLOGIN;
CREATE SCHEMA bank AUTHORIZATION bank_owner;
CREATE TABLE bank.accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
ALTER TABLE bank.accounts OWNER TO bank_owner;
INSERT INTO bank.accounts VALUES (1, 250.00);
BEGIN;
CREATE FUNCTION bank.get_balance(p_account int)
RETURNS numeric
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
SELECT balance FROM bank.accounts WHERE id = p_account;
$$;
ALTER FUNCTION bank.get_balance(int) OWNER TO bank_owner;
REVOKE EXECUTE ON FUNCTION bank.get_balance(int) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION bank.get_balance(int) TO app_reader;
COMMIT;
GRANT USAGE ON SCHEMA bank TO app_reader;Now test it as the unprivileged role:
SET ROLE app_reader;
SELECT bank.get_balance(1); -- returns 250.00
SELECT * FROM bank.accounts; -- ERROR: permission denied for table accounts
RESET ROLE;The sections below explain each choice.
Pin search_path with SET
SET search_path = ... in the CREATE FUNCTION statement replaces the caller's value for the duration of the call and restores it afterward. Follow these rules:
- Prefer a list that contains only trusted schemas.
pg_catalogis always searched first unless you list it elsewhere, so naming it is mostly for clarity. - Schema-qualify every table in the body (
bank.accounts, notaccounts). Then even a wrongsearch_pathcannot redirect the lookup. - List
pg_templast. Without that, the session's temporary schema is searched first for tables and views, so a caller can shadow your table with a temporary one. The PostgreSQL documentation recommends placingpg_tempat the end. - Avoid
publicin the list. Before PostgreSQL 15, every role could create objects inpublicby default. Even on 15 and later, a database upgraded from an older version may keep the old privileges.
A BEGIN ATOMIC body is parsed when the function is created, so its object references are bound at that moment rather than at each call. This removes most of the lookup risk from the body. Pinning search_path is still a sensible habit, and it costs nothing.
Close the PUBLIC door in the same transaction
The function exists with EXECUTE for PUBLIC from the instant CREATE FUNCTION finishes. Putting CREATE, REVOKE and GRANT in one transaction means no other session can call it in the gap.
To stop the problem for future functions, change the default privileges for the schema owner:
ALTER DEFAULT PRIVILEGES FOR ROLE bank_owner IN SCHEMA bank
REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;This affects only functions created after the statement runs. Existing functions keep their current privileges.
Choose the owner deliberately
Create a role that owns only the objects the function touches and has only the privileges it needs. Make it NOLOGIN so nobody can connect as it. Avoid superusers and avoid roles with BYPASSRLS unless the function needs that. If a definer function is injectable or mis-written, the damage is limited to what its owner can do.
Table owners also bypass row-level security unless the table has FORCE ROW LEVEL SECURITY. A definer function owned by the table owner therefore sees all rows. Either filter explicitly in the body or force RLS on the table.
Who is the caller inside the function?
Inside a definer function, current_user is the function owner. session_user is still the role that logged in. Use session_user when you need to know who called, for example to restrict results to the caller's own rows or to write an audit record:
CREATE FUNCTION bank.log_access(p_account int)
RETURNS void
LANGUAGE sql
VOLATILE
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
INSERT INTO bank.access_log (account_id, who, at)
VALUES (p_account, session_user, now());
$$;This assumes a table bank.access_log(account_id int, who name, at timestamptz). Note that SET ROLE changes current_user but not session_user, so use a real login when you test this kind of check.
Interaction with inlining and performance
The planner can inline a simple SQL function into the calling query only if it is not SECURITY DEFINER and has no SET clause. A safe definer function is both, so it is never inlined. The planner treats it as a black box: it cannot push WHERE conditions into it or use its statistics. For a single-row lookup this does not matter. If you call the function for millions of rows in a query, consider whether a view, an RLS policy, or a plain invoker function with narrower grants fits the problem better.
Auditing existing functions
You can find definer functions that lack a pinned search_path or still allow PUBLIC execution by querying the catalog:
SELECT n.nspname AS schema,
p.proname AS function,
p.proowner::regrole AS owner,
(p.proconfig IS NULL OR NOT EXISTS (
SELECT 1 FROM unnest(p.proconfig) AS c
WHERE c LIKE 'search_path=%')) AS missing_search_path,
(p.proacl IS NULL) AS default_public_execute
FROM pg_proc AS p
JOIN pg_namespace AS n ON n.oid = p.pronamespace
WHERE p.prosecdef
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY 1, 2;proacl IS NULL means the function still has its default privileges, which include EXECUTE for PUBLIC. A function whose ACL was edited may have an explicit =X/owner entry, which also grants PUBLIC. Use \df+ in psql to read the full ACL.
To fix an existing function without recreating it:
ALTER FUNCTION bank.get_balance(int)
SET search_path = pg_catalog, pg_temp;Checklist
| Check | How |
|---|---|
| Pinned `search_path` | `SET search_path = pg_catalog, pg_temp` plus any trusted schemas |
| Qualified names | `bank.accounts`, never bare `accounts` |
| No default access | `REVOKE EXECUTE ... FROM PUBLIC`, then `GRANT` to named roles |
| Atomic setup | Create, revoke and grant in one transaction |
| Minimal owner | Dedicated `NOLOGIN` role with only needed privileges |
| Caller identity | `session_user`, not `current_user` |
| Input handling | Treat arguments as untrusted; no dynamic SQL built by concatenation |
Exercise
A colleague creates CREATE FUNCTION app.close_ticket(p_id int) RETURNS void LANGUAGE sql SECURITY DEFINER AS $$ UPDATE tickets SET status = 'closed' WHERE id = p_id; $$; as a superuser and runs no other statements. Name three problems and give a fix for each.
Show answer
(1) EXECUTE is still granted to PUBLIC, so every role can call it. Fix: REVOKE EXECUTE ON FUNCTION app.close_ticket(int) FROM PUBLIC; and GRANT it only to the intended roles, in the same transaction as CREATE FUNCTION. (2) tickets is unqualified and search_path is not pinned, so a caller can redirect the lookup to an object in a schema they control. Fix: write app.tickets and add SET search_path = pg_catalog, pg_temp. (3) The owner is a superuser, so any flaw runs with full privileges. Fix: ALTER FUNCTION app.close_ticket(int) OWNER TO a dedicated NOLOGIN role that has only UPDATE on app.tickets.