← Back to SQL, page 20

sql-0387 · Hard senior

Why can a SECURITY DEFINER function in PostgreSQL be dangerous, and how is it made safe?

A SECURITY DEFINER function runs with its owner's privileges, not the caller's. If it resolves unqualified names through search_path, a caller can create an object with the same name in a schema they control and have the function call it with elevated rights. Set a fixed search_path on the function, qualify names, and grant EXECUTE narrowly.

Full answer

Safe definition pattern (illustrative, not run here):

text
CREATE FUNCTION app.reset_password(uid int) RETURNS void
LANGUAGE sql SECURITY DEFINER
SET search_path = pg_catalog, app
AS $$ UPDATE app.users SET password_hash = NULL WHERE id = uid $$;
REVOKE ALL ON FUNCTION app.reset_password(int) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION app.reset_password(int) TO support_role;

Points:

  • The SET search_path clause pins name resolution, putting pg_temp last implicitly when not listed, so temporary objects cannot shadow real ones.
  • Functions are executable by PUBLIC by default; revoke that and grant to specific roles.
  • Keep the function small and validate inputs, since it bypasses normal permission checks.
  • The owner should be a dedicated role with only the rights the function needs, not a superuser.

SECURITY INVOKER (the default) runs with the caller's rights and avoids the issue when elevation is not needed.

Key points

  • SECURITY DEFINER runs with the owner's rights
  • Unpinned search_path allows object shadowing
  • Set search_path on the function
  • Revoke EXECUTE from PUBLIC
  • Owner should be a minimal role

Common mistakes

  • Owning definer functions by a superuser
  • Relying on the caller's search_path

Follow-ups

  • How does row-level security interact with definer functions?
  • Which privileges does a new function get by default?

Tips

  • Name the search_path attack