Sub topic 11
Testing PostgreSQL Row-Level Security with `SET ROLE` and `pg_policies`
Assume you know basic SQL, PostgreSQL roles, GRANT, and CREATE POLICY. This chapter focuses on testing an existing row-level security (RLS) setup. Testing must check both successful access and rejected access.
Test the policy as different roles
SET ROLE changes the role used for permission checks in the current database session. The connected role must be allowed to become the target role, usually through role membership.
Suppose documents has this policy:
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);
CREATE ROLE alice;
CREATE ROLE bob;
GRANT SELECT, INSERT, UPDATE, DELETE
ON documents TO alice, bob;
GRANT USAGE, SELECT
ON SEQUENCE documents_id_seq TO alice, bob;The administrator or role owner must also permit the test session to switch roles:
GRANT alice, bob TO test_runner;Now connect as test_runner and test each role:
SET ROLE alice;
INSERT INTO documents (title, body)
VALUES ('Alice notes', 'Private content');
SELECT id, owner_name, title
FROM documents;
RESET ROLE;
SET ROLE bob;
SELECT id, owner_name, title
FROM documents;
RESET ROLE;Alice can see her row. Bob receives no rows because the policy adds owner_name = current_user to the query. RESET ROLE returns the session to its original connected role.
The main checks are:
| Test action | Expected result |
|---|---|
| Alice selects Alice's row | The row is visible |
| Bob selects Alice's row | The row is hidden |
| Alice inserts without `owner_name` | The default creates an Alice-owned row |
| Bob inserts an Alice-owned row | RLS rejects the row |
| Alice updates Bob's row | The row is not found for the update |
Test rejected writes safely
A failed statement can abort the current transaction. Use a savepoint when testing an expected failure:
SET ROLE bob;
SAVEPOINT before_forged_insert;
INSERT INTO documents (title, owner_name)
VALUES ('Forged row', 'alice');
-- Expected error:
-- new row violates row-level security policy
ROLLBACK TO SAVEPOINT before_forged_insert;
RESET ROLE;WITH CHECK validates rows created or changed by a command. In this example, Bob cannot claim that a new row belongs to Alice.
For a repeatable test, run each role's checks in a clean transaction. Avoid relying only on the number of rows returned. Also verify that a user cannot infer another user's data through updates, deletes, error messages, or application behavior.
Inspect policies with `pg_policies`
PostgreSQL exposes policy definitions through the pg_policies system view:
SELECT schemaname,
tablename,
policyname,
permissive,
roles,
cmd,
qual,
with_check
FROM pg_policies
WHERE schemaname = 'public'
AND tablename = 'documents';The qual column contains the USING expression. The with_check column contains the WITH CHECK expression. roles shows the roles targeted by the policy. A policy using FOR ALL appears with cmd set to * on supported PostgreSQL versions.
This inspection helps find mistakes such as a policy assigned to the wrong role, a missing command-specific policy, or a WITH CHECK expression that is weaker than the read filter.
Use `EXPLAIN` to confirm filtering
EXPLAIN can show the policy predicate added to a query:
SET ROLE alice;
EXPLAIN SELECT id, title
FROM documents
WHERE title LIKE 'Alice%';
RESET ROLE;Look for a filter involving owner_name = current_user. To test actual visibility, use EXPLAIN (ANALYZE, BUFFERS) only with safe test data, because it executes the statement.
Exercise
Why can Bob's SELECT return no rows even though Bob has the SELECT privilege on documents?
Show answer
The privilege allows Bob to query the table, but the RLS policy filters the rows to those whose ownername equals currentuser. Bob therefore sees only rows owned by bob.