Sub topic 11
Testing policies with SET ROLE and pg_policies
This chapter assumes you can write policies with CREATE POLICY and know USING from WITH CHECK. It also assumes you know how roles and GRANT work, and that you can use psql. The goal is to check that a policy does what you meant, from the role's point of view, before real users find out.
Why you must test as the restricted role
Policies are invisible to the roles that bypass them. If you build a table as a superuser or as the table owner and run a quick SELECT, you see every row and conclude nothing is wrong. The policy is never evaluated for you.
A useful test therefore runs as each role the application uses. It checks four things:
- Which rows the role can read.
- Which rows it can change.
- Which writes it is rejected for.
- What a role with no matching policy sees.
PostgreSQL gives you two tools for this. SET ROLE lets you act as another role inside one session. The pg_policies view shows what policies actually exist.
Acting as another role
SET ROLE name switches the current user to name. You must be allowed to do that. A superuser can switch to any role, and other users can switch only to roles they are members of. After the switch, privilege checks and RLS use the new role, so a superuser who switches to alice stops bypassing RLS until RESET ROLE.
| Command | Effect | Lasts until |
|---|---|---|
| `SET ROLE alice` | Changes `current_user` to `alice`. `session_user` is unchanged. | `RESET ROLE` or session end |
| `SET LOCAL ROLE alice` | Same, but only for the current transaction. | `COMMIT` or `ROLLBACK` |
| `SET SESSION AUTHORIZATION alice` | Changes `session_user` too. Superusers only. | `RESET SESSION AUTHORIZATION` |
Prefer SET LOCAL ROLE inside a transaction that ends with ROLLBACK. A test can then insert and delete freely, and a failed test cannot leave you running as the wrong role.
A scripted test with assertions
Manual checking works while you design a policy. Once the policy is settled, put the same checks in a script that fails loudly. The script below is self-contained. Run it as a superuser in a scratch database.
CREATE ROLE alice;
CREATE ROLE bob;
CREATE TABLE documents (
id bigserial PRIMARY KEY,
owner_name text NOT NULL DEFAULT current_user,
title text NOT NULL,
body text
);
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
CREATE POLICY documents_owner ON documents
FOR ALL
USING (owner_name = current_user)
WITH CHECK (owner_name = current_user);
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO alice, bob;
GRANT USAGE ON SEQUENCE documents_id_seq TO alice, bob;
BEGIN;
DO $$
DECLARE
n bigint;
BEGIN
SET LOCAL ROLE alice;
INSERT INTO documents (title) VALUES ('Alice notes');
SELECT count(*) INTO n FROM documents;
ASSERT n = 1, format('alice should see 1 row, saw %s', n);
RESET ROLE;
SET LOCAL ROLE bob;
SELECT count(*) INTO n FROM documents;
ASSERT n = 0, format('bob should see 0 rows, saw %s', n);
UPDATE documents SET title = 'hijacked';
GET DIAGNOSTICS n = ROW_COUNT;
ASSERT n = 0, format('bob should update 0 rows, updated %s', n);
BEGIN
INSERT INTO documents (title, owner_name) VALUES ('Forged', 'alice');
RAISE EXCEPTION 'forged insert was allowed';
EXCEPTION WHEN insufficient_privilege THEN
NULL; -- expected: WITH CHECK rejected the row
END;
RESET ROLE;
RAISE NOTICE 'all RLS checks passed';
END
$$;
ROLLBACK;Each check shows one behavior from earlier chapters:
- Reads: a row hidden by
USINGis silently absent. There is no error, so the test counts rows. - Updates and deletes: an
UPDATEthat matches no visible rows succeeds and reports zero rows. The test checksROW_COUNT, because an error never arrives. - Inserts: a row that fails
WITH CHECKraises an error with SQLSTATE42501, which PL/pgSQL namesinsufficient_privilege.
The inner block deliberately raises a different exception (P0001) if the forged insert succeeds. That exception is not caught by the handler, so it ends the script and the test fails.
Reading pg_policies
The pg_policies view shows what PostgreSQL stored. Use it to confirm the policy you deployed is the policy you wrote.
SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check
FROM pg_policies
WHERE tablename = 'documents';| Column | Meaning |
|---|---|
| `permissive` | The text `PERMISSIVE` or `RESTRICTIVE`. |
| `roles` | An array of role names. `{public}` means the policy has no `TO` clause. |
| `cmd` | `ALL`, `SELECT`, `INSERT`, `UPDATE`, or `DELETE`. |
| `qual` | The `USING` expression, or `NULL` if there is none. |
| `with_check` | The `WITH CHECK` expression, or `NULL` if there is none. |
Two details cause confusion:
- A policy created with only
USINGshowsNULLinwith_check. ForFOR ALLandFOR UPDATEpolicies, PostgreSQL then applies theUSINGexpression to new rows as well. ANULLinwith_checktherefore does not mean new rows are unchecked. - An
INSERTpolicy has noUSINGclause, soqualisNULLfor it. Likewise aSELECTorDELETEpolicy has noWITH CHECK.
The expressions are shown in PostgreSQL's normalized form, not the text you typed. Expect extra parentheses and explicit casts.
Checking the RLS state of the table
Policies do nothing on a table where RLS is not enabled, and pg_policies lists them anyway. Always check the table flags too.
SELECT relname,
relowner::regrole AS owner,
relrowsecurity,
relforcerowsecurity
FROM pg_class
WHERE oid = 'documents'::regclass;
SELECT rolname, rolsuper, rolbypassrls
FROM pg_roles
WHERE rolname IN ('alice', 'bob', current_user);The first query shows whether RLS is on (relrowsecurity), whether FORCE is set (relforcerowsecurity), and who the owner is. The second shows which roles bypass RLS. Any role with rolsuper or rolbypassrls set to true will not be filtered, and the owner is not filtered either unless FORCE is set.
The function row_security_active answers the question directly for the current user:
SET ROLE alice;
SELECT row_security_active('documents'); -- true: policies apply to alice
RESET ROLE;
SELECT row_security_active('documents'); -- false if you are a superuserIn psql, \d documents also lists the table's policies, and \dp documents shows them next to the privileges.
Debugging a role that sees the wrong rows
When a test fails, work through the causes in order. Privilege errors look different from RLS effects, so check them first.
Use the roles and cmd columns when you reach the last step. A policy applies to role R and command C only when R is in roles (or roles is {public}) and cmd is ALL or equals C. Permissive policies that apply are combined with OR. Restrictive policies are combined with AND on top of that result.
Common testing mistakes
- Testing as the owner. The owner sees everything unless
FORCE ROW LEVEL SECURITYis set. If the application connects as the owner, either addFORCEor use a separate application role. - No empty-result check. A hidden row produces no error, so a test that only looks for errors passes while the policy leaks data. Count rows.
- Missing sequence or column privileges. An
INSERTcan fail withpermission denied for sequencebefore any policy is checked. That is aGRANTproblem. - Updates that need
SELECTvisibility. AnUPDATEorDELETEwith aWHEREclause reads the existing rows, so aSELECTpolicy (or anALLpolicy) must also let the role see them. With separate per-command policies, anUPDATEpolicy alone is not enough. - Session settings left behind. If your policies read
current_setting('app.tenant_id', true), set it withset_config(..., true)inside the test transaction so it does not carry over to the next test. - Trusting
pg_policiesalone. It shows the text of the policy, not its effect. A policy can be correct on paper and still be neutralized by a bypassing role.
Checking the plan
EXPLAIN run as the restricted role shows the policy predicate added to the query. It appears in the Filter line of the scan node. Run it under SET ROLE, because as a bypassing role you will not see the predicate at all. Performance of those predicates is a topic for a later chapter. For testing, the plan confirms that the policy was applied to your query.
Exercise
You run SELECT count(*) FROM documents; as the table owner and get 500 rows, though the table has an owner policy. Your application role app_user then reports 0 rows. List the steps you would take to find out whether the policy is wrong or the test was misleading.
Show answer
First run SELECT row_security_active('documents'); as the owner. It returns false because the owner bypasses RLS unless FORCE ROW LEVEL SECURITY is set, so the 500 rows say nothing about the policy. Next check relrowsecurity and relforcerowsecurity in pg_class. Then run SET ROLE app_user; and repeat the query, and query pg_policies for rows where roles contains app_user or {public} and cmd is ALL or SELECT. If no policy matches, default deny explains the 0 rows. If one matches, read its qual expression and compare it with the values stored in the rows, for example the owner_name column against current_user.
Exercise
As role bob, UPDATE documents SET title = 'x' WHERE id = 1; returns UPDATE 0 with no error, although row 1 exists and belongs to alice. Is that a bug in the policy? How would you assert this behavior in a test?
Show answer
No. The USING expression hides alice's row from bob, so the update finds no rows to change and reports zero rows instead of raising an error. Only a write that creates or modifies a row so that it fails WITH CHECK raises an error. In a test, switch to bob with SET LOCAL ROLE bob, run the update, read the count with GET DIAGNOSTICS n = ROW_COUNT, and ASSERT n = 0.