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_pathclause pins name resolution, puttingpg_templast 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