Sub topic 3
Writing your first policy
This chapter shows how to write a first row-level security policy with CREATE POLICY, and how to read each part of the command. It assumes you can write basic SQL, create tables, use GRANT, and run psql. It also assumes you have seen that ALTER TABLE ... ENABLE ROW LEVEL SECURITY makes a table deny all rows to roles that do not bypass RLS. The next chapter covers USING and WITH CHECK in detail. Here you only need to write them and see them work.
What a policy is
A policy is a named rule attached to one table. It holds a boolean expression that PostgreSQL evaluates for each row. When RLS is enabled on the table, a role that does not bypass RLS can only see or write the rows that some policy allows.
The syntax has several optional parts:
CREATE POLICY name ON table_name
[ AS { PERMISSIVE | RESTRICTIVE } ]
[ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]
[ TO { role_name | PUBLIC | CURRENT_USER | SESSION_USER } [, ...] ]
[ USING ( using_expression ) ]
[ WITH CHECK ( check_expression ) ];Only the name and the table are required. Every other clause has a default:
| Clause | Default | Meaning |
|---|---|---|
| `AS` | `PERMISSIVE` | Permissive policies are combined with OR. A later chapter covers restrictive ones. |
| `FOR` | `ALL` | The policy applies to every command. |
| `TO` | `PUBLIC` | The policy applies to every role. |
| `USING` | none | Decides which existing rows a command can see or target. |
| `WITH CHECK` | the `USING` expression, for `ALL` and `UPDATE` policies | Decides which new or changed rows are allowed. |
Policy names are unique per table, not per database. Two tables can each have a policy called owner_only.
A table whose rows have an owner
The simplest useful policy ties each row to the role that created it. The owner_name column defaults to current_user, which is the role running the statement.
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);Reading the policy part by part:
documents_owner ON documentsnames the policy and the table it protects.FOR ALLapplies it toSELECT,INSERT,UPDATE, andDELETE. This is the default, and it is written out here for clarity.USING (owner_name = current_user)is evaluated against existing rows. A row for which it is not true is invisible to the command.SELECTskips it, andUPDATEandDELETEnever touch it.WITH CHECK (owner_name = current_user)is evaluated against rows being created or changed. If it is not true, PostgreSQL raises an error.
Because WITH CHECK is omitted for ALL and UPDATE policies, PostgreSQL reuses the USING expression. Writing both here is therefore redundant. It is still worth doing at first, because it shows which expression does which job.
How a query meets a policy
PostgreSQL does not run your query and then filter the result. It adds the policy expression to the query itself, so the planner treats it like part of your WHERE clause.
Since fences cannot nest and the diagram needs the exact format, here it is in the required form:
The distinction between the two outcomes matters in practice:
- A failed
USINGtest is silent. The row is simply absent, so aSELECTreturns fewer rows and anUPDATEreportsUPDATE 0. - A failed
WITH CHECKtest is loud. You get an error, and the statement is rolled back.
Running it end to end
Run the following as a superuser or as the table owner. Superusers and table owners bypass RLS, so you must switch to another role to see the policy work.
CREATE ROLE alice;
CREATE ROLE bob;
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO alice, bob;
GRANT USAGE ON SEQUENCE documents_id_seq TO alice, bob;
SET ROLE alice;
INSERT INTO documents (title) VALUES ('Alice notes');
SET ROLE bob;
SELECT title FROM documents; -- returns no rows
INSERT INTO documents (title, owner_name) VALUES ('Forged', 'alice');
-- ERROR: new row violates row-level security policy for table "documents"
RESET ROLE;Each step has a reason:
- The
GRANTstatements are required. RLS adds a second layer on top of ordinary privileges and does not replace them. If a role lacksSELECTon the table, it gets a permission error before any policy is considered. - Alice's insert works.
owner_namedefaults toalicethroughcurrent_user, so theWITH CHECKexpression is true. - Bob's
SELECTreturns nothing. Alice's row failsUSINGfor Bob, but no error is raised. - Bob's forged insert fails. The new row would have
owner_name = 'alice', which fails Bob'sWITH CHECK. RESET ROLEreturns you to your original session role.
After RESET ROLE, SELECT * FROM documents; as the superuser shows Alice's row, because the superuser bypasses RLS.
Using separate policies
A single FOR ALL policy is compact, but you can also write one policy per command. Each policy then carries only the expression that command needs, and TO limits it to named roles.
CREATE POLICY documents_select ON documents
FOR SELECT
TO alice, bob
USING (owner_name = current_user);
CREATE POLICY documents_insert ON documents
FOR INSERT
TO alice, bob
WITH CHECK (owner_name = current_user);Which expressions each command accepts is fixed:
| Command | `USING` | `WITH CHECK` |
|---|---|---|
| `SELECT` | allowed | not allowed |
| `INSERT` | not allowed | allowed |
| `UPDATE` | allowed | allowed |
| `DELETE` | allowed | not allowed |
| `ALL` | allowed | allowed |
Supplying an expression a command cannot use is an error at CREATE POLICY time. For example, FOR INSERT USING (...) is rejected.
If you apply these two policies on top of documents_owner from earlier, they add to it. Permissive policies combine with OR, so a row is visible if any applicable policy allows it. Drop documents_owner first if you want to test the separate policies on their own.
Managing policies
These commands cover the rest of a policy's life:
-- Change roles or expressions without dropping the policy
ALTER POLICY documents_owner ON documents
USING (owner_name = current_user OR owner_name = 'shared');
-- Rename a policy
ALTER POLICY documents_owner ON documents RENAME TO documents_owner_or_shared;
-- Remove a policy
DROP POLICY documents_owner_or_shared ON documents;ALTER POLICY cannot change the command (FOR) or whether the policy is permissive or restrictive. To change those, drop the policy and create it again.
Dropping the last policy does not turn RLS off. The table goes back to default deny for non-bypassing roles. That is usually what you want, but it can surprise you if you expected the table to open up. Only ALTER TABLE ... DISABLE ROW LEVEL SECURITY turns RLS off.
Common errors
- Policy created but nothing is filtered. Either RLS is not enabled on the table, or you are testing as a role that bypasses it, such as a superuser or the table owner. Check
relrowsecurityinpg_class, and test withSET ROLE. permission denied for table documents. The role has no table privilege. Policies only narrow what a privilege already allows, so add theGRANT.permission denied for sequence documents_id_seq. The role can insert into the table but cannot use thebigserialsequence. GrantUSAGEon the sequence.UPDATE 0with no error. TheUSINGexpression hid the rows. This is expected behavior and not a bug.new row violates row-level security policy. TheWITH CHECKexpression failed for the row you tried to write. Compare the row's values with the expression.policy "x" for table "y" already exists. Policy names must be unique per table. UseALTER POLICYor drop the old one first.
Exercise
You run CREATE POLICY p ON documents USING (owner_name = current_user); without FOR or TO. As bob, you run UPDATE documents SET title = 'x' WHERE owner_name = 'alice'; and see UPDATE 0. Which clause caused this, and why is there no error?
Show answer
The default FOR ALL applies the policy to UPDATE, and its USING expression is evaluated against existing rows. Alice's rows fail owner_name = current_user for bob, so they are filtered out before the update. A failed USING test is silent, so zero rows match and PostgreSQL reports UPDATE 0 instead of raising an error.
Exercise
Write a policy named own_rows_read that lets only the role carol read rows from documents whose owner_name equals her role name, and lets her do nothing else through this policy.
Show answer
CREATE POLICY ownrowsread ON documents FOR SELECT TO carol USING (ownername = currentuser); Carol also needs GRANT SELECT ON documents TO carol. The policy covers only SELECT, so it grants no write access.