Sub topic 15
Beyond GRANT: a first look at row-level security
This chapter assumes you know GRANT and REVOKE on tables and columns, role membership, and the owner, read-only and read-write role layout from the earlier chapters. It also assumes you can run SQL as a superuser and switch roles with SET ROLE.
GRANT decides whether a role may touch a table. It cannot say which rows the role may touch. Row-level security (RLS) adds that second layer. You attach policies to a table, and PostgreSQL adds each policy's condition to every query on that table.
Why table privileges are not enough
Suppose every sales representative should read only their own rows in shop.orders. With GRANT alone you have two bad choices. You can give all representatives SELECT on the whole table. Or you can build one view or one table per representative. RLS keeps one table and filters rows by the current role.
RLS does not replace GRANT. A role still needs the table privilege first. The policy then narrows which rows the privilege applies to.
Enabling RLS and writing a first policy
Two statements turn RLS on and define a rule. Run this setup as a superuser or as app_owner. It reuses the shop.orders table and the app_readonly and app_writer roles from earlier chapters.
CREATE ROLE bob LOGIN PASSWORD 'change-me';
GRANT app_readonly TO bob;
INSERT INTO shop.orders (customer, sales_rep, total) VALUES
('Acme', 'alice', 100.00),
('Globex', 'bob', 250.00),
('Initech','alice', 75.50);
ALTER TABLE shop.orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_orders ON shop.orders
FOR SELECT
TO app_readonly
USING (sales_rep = current_user);The sales_rep column has type name, the same type current_user returns, so the comparison needs no cast. Now test it by switching to alice:
SET ROLE alice;
SELECT id, customer, sales_rep FROM shop.orders;
RESET ROLE;Alice sees her two rows. Bob would see only the Globex row. Neither of them gets an error for the rows they cannot see. Those rows are silently absent, as if they did not exist.
Default deny
Once RLS is enabled, a role that is subject to RLS and has no applicable policy sees no rows and can change none. This is a default-deny rule.
In the example, app_writer has SELECT, INSERT and UPDATE privileges, but the only policy applies to app_readonly. A member of app_writer who is not also a member of app_readonly gets empty results and cannot insert. That surprises many people, because the GRANT statements still look correct. If a table "suddenly returns nothing" after you enable RLS, check for a missing policy first.
USING versus WITH CHECK
A policy has up to two expressions, and each applies at a different moment.
USINGfilters rows that already exist. It decides which rows a query can see, update or delete.WITH CHECKvalidates rows that are being written. It decides whether a new or modified row is allowed to exist.
| Command | Expression used |
|---|---|
| SELECT | `USING` |
| INSERT | `WITH CHECK` |
| UPDATE | `USING` on the old row, `WITH CHECK` on the new row |
| DELETE | `USING` |
For UPDATE, if you omit WITH CHECK, PostgreSQL uses the USING expression for both checks. Here is a policy for writers that lets each person insert and change only their own orders:
CREATE POLICY writer_own_orders ON shop.orders
FOR ALL
TO app_writer
USING (sales_rep = current_user)
WITH CHECK (sales_rep = current_user);If a writer named alice tries to insert a row with sales_rep = 'bob', PostgreSQL rejects it:
SET ROLE alice;
GRANT app_writer TO alice; -- run beforehand as a superuser
INSERT INTO shop.orders (customer, sales_rep, total)
VALUES ('Umbrella', 'bob', 10.00);
-- ERROR: new row violates row-level security policy for table "orders"Without WITH CHECK, a writer could "give away" a row by updating sales_rep to someone else. The old row passes USING, and nothing would stop the new row from leaving the writer's view.
How PostgreSQL evaluates policies
When several policies apply to the same command, PostgreSQL combines them. By default policies are permissive, and a row is visible if any permissive policy allows it (OR). You can create a restrictive policy with AS RESTRICTIVE. Every restrictive policy must also pass (AND).
A restrictive policy is useful for a rule that must always hold, whatever other policies exist. This one hides cancelled orders from everyone, assuming the table has a status column:
CREATE POLICY hide_cancelled ON shop.orders
AS RESTRICTIVE
FOR SELECT
USING (status <> 'cancelled');A table that has only restrictive policies still shows no rows. At least one permissive policy must allow a row before the restrictive ones are checked.
Who is exempt
Three kinds of role skip RLS:
- Superusers.
- Roles with the
BYPASSRLSattribute. - The table owner, unless you run
ALTER TABLE shop.orders FORCE ROW LEVEL SECURITY.
The owner exemption matters in the least-privilege layout. app_owner owns the tables and sees all rows when it runs migrations. That is usually what you want. If the application itself connects as the owner, though, RLS does nothing for it. Applications should connect as a non-owner role, which is the reason for the owner, read-only and read-write split.
FORCE ROW LEVEL SECURITY applies policies to the owner as well. Superusers and BYPASSRLS roles are still exempt.
Choosing what the policy compares to
The first example uses current_user. That is simple, but it ties row ownership to database logins. That works when each person has a role. Many applications use one shared login role and many application users. In that case, a policy usually reads a session setting that the application sets for each transaction:
CREATE POLICY tenant_rows ON shop.orders
FOR ALL
TO app_writer
USING (sales_rep = current_setting('app.current_rep', true))
WITH CHECK (sales_rep = current_setting('app.current_rep', true));The application then runs SELECT set_config('app.current_rep', 'alice', true); at the start of each transaction. The true in set_config limits the value to the current transaction. The true in current_setting returns NULL instead of an error when the setting is unset, which makes the policy deny every row. Treat any setting a user can change as untrusted. Any client that can run SQL can run set_config itself, so this pattern protects only against application mistakes, not against a user with direct SQL access.
Gotchas and limits
- Policies are not shown by
\dp. Use\d shop.ordersin psql to see the policies on a table, or query thepg_policiesview. - Views run with the view owner's rights by default. A view over an RLS table is checked as its owner, so RLS may not filter as you expect. From PostgreSQL 15, create the view
WITH (security_invoker = true)so that the caller's rights apply. - Constraints bypass RLS. Foreign key checks and unique-constraint checks look at all rows. An error message can reveal that a hidden row exists.
- Cost. The policy expression becomes part of every query. Index the columns it uses, such as
sales_rep. Keep the expression simple. Avoid subqueries that read other RLS-protected tables. - Dump and restore.
pg_dumpcan fail or produce partial output if the dumping role is subject to RLS. Dump as a role that bypasses RLS.
Checking your policies
Test each policy as each role, using SET ROLE, and check both reads and writes. This query lists the policies on a table:
SELECT policyname, permissive, roles, cmd, qual, with_check
FROM pg_policies
WHERE schemaname = 'shop' AND tablename = 'orders'
ORDER BY policyname;To confirm the owner exemption and the flags:
SELECT relname, relrowsecurity, relforcerowsecurity
FROM pg_class
WHERE oid = 'shop.orders'::regclass;relrowsecurity is true when RLS is enabled. relforcerowsecurity is true when the owner is also subject to policies.
Exercise
You enable RLS on shop.orders and create one policy, FOR SELECT TO appreadonly USING (salesrep = currentuser). A user who is a member only of appwriter, which has SELECT, INSERT and UPDATE privileges, runs SELECT * FROM shop.orders. What do they get, and why? What single statement would let them insert only rows where sales_rep is their own login name?
Show answer
They get zero rows and no error. RLS is enabled, no policy applies to appwriter, and the default is to deny. The statement CREATE POLICY writerownorders ON shop.orders FOR ALL TO appwriter USING (salesrep = currentuser) WITH CHECK (salesrep = currentuser) lets them see and change only their own rows. WITH CHECK is what stops them inserting rows for another sales_rep.
Exercise
Why does enabling RLS not protect rows from the role app_owner, and what do you change if you want the policies to apply to it too?
Show answer
The table owner is exempt from RLS by default. Run ALTER TABLE shop.orders FORCE ROW LEVEL SECURITY so that policies also apply to the owner. Superusers and roles with BYPASSRLS stay exempt even then.