Sub topic 2
Turning RLS on: default deny
This chapter covers what happens to a table when you enable row-level security (RLS), and how to predict the result before you run a query. It assumes you can write basic SQL, create tables, and manage PostgreSQL roles with GRANT and REVOKE. You should also be comfortable using psql or another SQL client.
Table privileges and RLS are separate checks
PostgreSQL checks access in layers. Table privileges (GRANT SELECT ON ...) decide whether a role may run a kind of statement against a table at all. Column privileges narrow that to specific columns. RLS adds a third check that decides which rows within the table the role may see or change.
The order matters. PostgreSQL checks table privileges first. If the role lacks SELECT on the table, the query fails with a permission error and RLS never runs. If the role has the privilege, RLS then filters or validates rows.
RLS never grants access the privileges don't already give. It only narrows what the privileges allow.
Enabling RLS
RLS is off by default on every table. You turn it on per table:
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;Until you create a policy, the table is in a locked state. PostgreSQL calls this a default-deny policy. With RLS enabled and no policies defined, roles that are subject to RLS see no rows and can't add, change, or delete any rows.
The behavior differs by statement:
| Statement | Result with RLS enabled and no policy |
|---|---|
| `SELECT` | Returns zero rows, with no error |
| `INSERT` | Fails with a row-level security policy error |
| `UPDATE` | Affects zero rows, with no error |
| `DELETE` | Affects zero rows, with no error |
SELECT, UPDATE, and DELETE don't raise errors because an existing row that fails the policy is simply treated as invisible. INSERT raises an error because the new row is checked against a rule and fails it.
Seeing default deny in action
The following script creates two roles, grants them ordinary table privileges, and then tries to use the table. It assumes the documents table from above exists and that you run it as the table owner or a superuser.
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;
SELECT count(*) FROM documents;
-- count: 0
INSERT INTO documents (title) VALUES ('Alice notes');
-- ERROR: new row violates row-level security policy for table "documents"
RESET ROLE;The GRANT statements give both roles full table privileges, yet the role still can't do anything useful. Two separate mechanisms are involved. The privilege check passes. The RLS check then finds no policy that allows the operation, so it denies it.
SET ROLE alice makes the session act as alice for permission checks. RESET ROLE returns to the original login role. You will use this pattern throughout the tutorial to test policies. The next chapter adds the policy that makes the table usable.
How the deny decision works
Think of RLS as a filter built from policies. For each command, PostgreSQL gathers the policies that apply to the current role and combines their expressions. A row is allowed only if the combined expression is true. When there are no applicable policies, there is nothing to make an expression true, so every row is denied.
This is why the default is safe. Adding a table with RLS enabled can never expose rows by accident. Rows become reachable only when someone writes a policy that says so.
The bypass step in this diagram is covered in detail in a later chapter. For now, note that some roles skip the policy check entirely.
The roles that RLS does not restrict
Default deny applies to roles that are subject to RLS. Three kinds of roles are exempt:
- Superusers always bypass RLS.
- Roles with the
BYPASSRLSattribute bypass RLS. - The table owner bypasses RLS, unless the table has
FORCE ROW LEVEL SECURITYset.
The owner exemption surprises many people. The role that ran CREATE TABLE owns the table. If you test your new RLS table while logged in as that role, you will see every row and conclude the policies do nothing. Test with a separate role, using SET ROLE, or force RLS on the table. Forcing is covered later in this tutorial.
You can check whether your current role bypasses RLS:
SELECT rolname, rolsuper, rolbypassrls
FROM pg_roles
WHERE rolname = current_user;If either rolsuper or rolbypassrls is true, RLS does not apply to that role.
Checking whether RLS is enabled
The pg_class catalog records the setting for each table:
SELECT relname, relrowsecurity, relforcerowsecurity
FROM pg_class
WHERE relname = 'documents';relrowsecurity is true after ENABLE ROW LEVEL SECURITY. relforcerowsecurity is true only if you also ran FORCE ROW LEVEL SECURITY. In psql, the \d documents command shows the same information, listing policies and noting "Row security: enabled".
Disabling RLS, and what that does to policies
You can turn RLS off again:
ALTER TABLE documents DISABLE ROW LEVEL SECURITY;This removes enforcement and gives every role with ordinary privileges full access to all rows. Policies you already created are not deleted. They remain defined on the table and take effect again if you re-enable RLS. This is a risk during maintenance: if someone disables RLS to debug a problem and forgets to re-enable it, data is exposed with no visible sign.
The reverse case is also worth knowing. If you create policies on a table but never run ENABLE ROW LEVEL SECURITY, the policies exist but are not applied. PostgreSQL accepts the CREATE POLICY command without complaint, and the table stays fully open. Always confirm relrowsecurity is true after setting up a table.
Common errors
- Testing as the owner. You see all rows and think RLS is broken. Switch to a non-owner role without
BYPASSRLS. - Forgetting table privileges. A role with a correct policy but no
GRANTgetspermission denied for table, not an RLS error. Fix it withGRANT. - Missing sequence privileges. Inserts into a
bigserialtable fail on the sequence before the row check runs. GrantUSAGEon the sequence, as the earlier script does. - Mistaking empty results for errors, or the reverse. Reads and updates hide rows silently. Only inserts, and updates that produce a row failing a check, raise the row-level security error.
- Assuming a default policy exists. There is no implicit "allow owner" rule for non-owner roles. Without a policy, they get nothing.
Summary of the default-deny model
- RLS is per table and off until you run
ENABLE ROW LEVEL SECURITY. - Once enabled, a table with no policies denies every row to roles that are subject to RLS.
- Table privileges are checked first and RLS does not add privileges.
- Superusers,
BYPASSRLSroles, and (withoutFORCE) the table owner are not restricted.
Exercise
You run ALTER TABLE documents ENABLE ROW LEVEL SECURITY as the table owner, create no policies, and GRANT SELECT and INSERT on the table to a role named carol. Describe what each of these gives: (1) carol runs SELECT FROM documents, (2) carol runs INSERT INTO documents (title) VALUES ('x'), (3) the owner runs SELECT FROM documents.
Show answer
(1) Carol gets zero rows and no error, because she has the SELECT privilege but no policy allows any row. (2) The insert fails with "new row violates row-level security policy for table documents". If the sequence privilege is missing, it fails earlier with a permission error on the sequence. (3) The owner sees all rows, because the table owner bypasses RLS unless FORCE ROW LEVEL SECURITY is set.
Exercise
A colleague creates a policy on the table invoices but the table still returns every row to a normal role. Which catalog column do you check first, and what is the likely cause?
Show answer
Check pg_class.relrowsecurity for invoices. It is probably false because ALTER TABLE ... ENABLE ROW LEVEL SECURITY was never run. Creating a policy alone does not turn RLS on.