Sub topic 10
Sequences and functions
Tables get most of the attention in a permissions design, but two other object types commonly cause "permission denied" errors in production: sequences and functions. This chapter covers the privileges each one uses, the defaults that surprise people, and how to check the result. It assumes you know GRANT, REVOKE, group roles, and ALTER DEFAULT PRIVILEGES from earlier chapters, and it reuses the shop schema and the roles app_owner, app_readonly, and app_writer.
Sequence privileges
A sequence is a separate database object that hands out numbers. It has its own owner and its own access list, so INSERT on a table does not imply any right on the sequence behind it. Three privileges apply to sequences:
| Privilege | Allows |
|---|---|
| `USAGE` | `currval` and `nextval` |
| `SELECT` | `currval`, and reading the sequence as a table (`SELECT last_value FROM seq`) |
| `UPDATE` | `nextval` and `setval` |
Each sequence function accepts more than one privilege:
| Function | Privilege required |
|---|---|
| `nextval` | `USAGE` or `UPDATE` |
| `currval` | `USAGE` or `SELECT` |
| `setval` | `UPDATE` |
USAGE is what a writer role normally needs. UPDATE also allows setval, which can move the counter backwards and cause duplicate keys. Grant it only to a role that administers the data.
Identity columns versus serial columns
The sequence behind a column matters. A column declared GENERATED ... AS IDENTITY, like shop.orders.id, uses an internal sequence. When a role inserts a row and lets the identity default fill the value, PostgreSQL checks only the table privilege. INSERT on the table is enough.
A column declared serial, or one with DEFAULT nextval('...'), calls the nextval function as an ordinary default expression. The inserting role then needs USAGE on the sequence. Without it, the insert fails with permission denied for sequence, even though the table grant is correct. The same applies if a role with an identity column calls nextval('shop.orders_id_seq') directly.
Granting on sequences
Create a standalone sequence and grant access:
SET ROLE app_owner;
CREATE SEQUENCE shop.invoice_no_seq;
RESET ROLE;
GRANT USAGE ON SEQUENCE shop.invoice_no_seq TO app_writer;
GRANT SELECT ON SEQUENCE shop.invoice_no_seq TO app_readonly;
-- Existing sequences only, like ALL TABLES
GRANT USAGE ON ALL SEQUENCES IN SCHEMA shop TO app_writer;ALL SEQUENCES IN SCHEMA has the same limitation as ALL TABLES. It covers only the sequences that exist when the command runs. For future ones, use default privileges:
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA shop
GRANT USAGE ON SEQUENCES TO app_writer;Default privileges apply only to objects created by app_owner, so this matters most when you run migrations as that role. Sequences created by another role are not affected.
Function privileges
Functions and procedures have one privilege: EXECUTE. It allows calling the function, using it in an expression, and using it as an operator implementation or index support function. Procedures called with CALL need EXECUTE too.
The default is permissive
When a function is created, PUBLIC receives EXECUTE automatically. Every role that can connect and reach the function's schema can call it. This is the one object type where the default grants access without any GRANT, which is why a schema-level lockdown is incomplete if you never look at functions.
To restrict a function, revoke from PUBLIC and grant to specific roles. Identify the function with its argument types, because functions can be overloaded:
SET ROLE app_owner;
CREATE FUNCTION shop.order_total(p_customer text)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT coalesce(sum(total), 0) FROM shop.orders WHERE customer = p_customer
$$;
RESET ROLE;
REVOKE EXECUTE ON FUNCTION shop.order_total(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION shop.order_total(text) TO app_readonly, app_writer;Two details:
ON FUNCTION name(argtypes)names exactly one overload.ON ALL FUNCTIONS IN SCHEMA shopcovers every function that exists now.- Since PostgreSQL 11,
ROUTINEandALL ROUTINES IN SCHEMAcover functions and procedures together. Aggregates are also functions for this purpose.
Invoker rights: EXECUTE is not enough
By default a function is SECURITY INVOKER. The body runs with the caller's privileges. A role with EXECUTE on shop.order_total still needs SELECT on shop.orders, or the call fails inside the body. EXECUTE controls only the right to call the function.
SECURITY DEFINER
A SECURITY DEFINER function runs with the privileges of its owner. This lets you expose a narrow operation without granting table access. The caller needs EXECUTE, and the owner needs whatever the body requires:
SET ROLE app_owner;
CREATE FUNCTION shop.add_order(p_customer text, p_total numeric)
RETURNS bigint
LANGUAGE sql
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
INSERT INTO shop.orders (customer, sales_rep, total)
VALUES (p_customer, session_user, p_total)
RETURNING id
$$;
RESET ROLE;
REVOKE EXECUTE ON FUNCTION shop.add_order(text, numeric) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION shop.add_order(text, numeric) TO app_writer;The function uses session_user, the login role, instead of current_user, which inside a SECURITY DEFINER function is the owner. Always follow the safety rules for definer functions:
- Set
search_pathon the function, as above, so a caller cannot shadow an object name with their own schema. - Schema-qualify every object in the body.
- Revoke
EXECUTEfromPUBLICin the same script that creates the function, so no window exists in which any role can call it. - Keep the owner's privileges minimal. A definer function owned by a superuser hands superuser power to every caller of that function.
Default privileges for functions
Closing the PUBLIC default for future functions has a catch. Per-schema default privileges are added to the global defaults, so they cannot subtract anything. Revoking from PUBLIC with IN SCHEMA has no effect. Alter the global default instead, then grant to the roles you want:
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner
REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA shop
GRANT EXECUTE ON FUNCTIONS TO app_readonly, app_writer;The first command affects every function app_owner creates in any schema of the current database. That is usually what you want for an application owner role.
Inspecting sequence and function access
The has_*_privilege family has matching functions, and \dp lists sequences along with tables. For functions, \df+ shows an access column.
SELECT has_sequence_privilege('alice', 'shop.invoice_no_seq', 'USAGE') AS can_nextval;
SELECT has_function_privilege('alice', 'shop.order_total(text)', 'EXECUTE') AS can_call;
SELECT p.oid::regprocedure AS function, p.prosecdef AS security_definer, p.proacl
FROM pg_proc AS p
WHERE p.pronamespace = 'shop'::regnamespace
ORDER BY 1;A NULL in proacl means the object still has the built-in defaults: the owner has all rights and PUBLIC has EXECUTE. After you run REVOKE ... FROM PUBLIC, the column is filled in with an explicit list and PUBLIC no longer appears in it. Auditing for proacl IS NULL, or for entries that begin with =X/, finds functions that anyone can call.
Common errors
| Error | Likely cause | Fix |
|---|---|---|
| `permission denied for sequence orders_id_seq` on `INSERT` | `serial` or `DEFAULT nextval` column, no `USAGE` on the sequence | `GRANT USAGE ON SEQUENCE` to the writer role |
| `permission denied for function f` | No `EXECUTE`, usually after revoking from `PUBLIC` | Grant `EXECUTE` to the group role |
| `permission denied for table` inside a function | Invoker function, caller lacks table rights | Grant the table privilege, or use a carefully written `SECURITY DEFINER` function |
| New sequences are unusable | Default privileges were set for a different creating role | Re-run `ALTER DEFAULT PRIVILEGES FOR ROLE <creator>` |
Exercise
A role in app_writer has INSERT on a table whose id column was declared as id serial. Inserts fail with "permission denied for sequence". The same role inserts fine into shop.orders, which uses an identity column. Why do the two tables behave differently, and what is the narrowest fix?
Show answer
A serial column uses DEFAULT nextval('...'), which is an ordinary function call that checks sequence privileges, so the role needs USAGE (or UPDATE) on the sequence. An identity column's internal sequence is checked only through the table's INSERT privilege. The narrowest fix is GRANT USAGE ON SEQUENCE <the sequence> TO app_writer. Granting USAGE rather than ALL avoids giving the role UPDATE, which would allow setval.
Exercise
You run ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA shop REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; and then app_owner creates a new function in shop. Can an unrelated role that has USAGE on the schema still call it? How do you correctly stop that?
Show answer
Yes, it can. Per-schema default privileges are added to the global defaults and cannot remove them, so PUBLIC still receives EXECUTE. Run the command without IN SCHEMA: ALTER DEFAULT PRIVILEGES FOR ROLE app_owner REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;, then grant EXECUTE to the intended roles with a per-schema default or explicit GRANT statements.