Sub topic 2
Turning RLS On: Default Deny
Assume you know basic SQL, PostgreSQL roles, and table privileges such as GRANT SELECT. Row-level security, or RLS, adds a second access check after those privileges. A role must have permission to use a table, and an RLS policy must allow the specific rows.
Enable RLS on a table
Use ALTER TABLE ... ENABLE ROW LEVEL SECURITY to turn RLS on:
CREATE TABLE documents (
id bigserial PRIMARY KEY,
owner_name text NOT NULL,
title text NOT NULL,
body text
);
GRANT SELECT, INSERT, UPDATE, DELETE
ON documents
TO app_user;
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;After RLS is enabled, PostgreSQL checks policies for commands issued by ordinary roles. At this point, the table has no policies. PostgreSQL therefore uses its default-deny behavior.
The app_user role has table privileges, but it cannot read or modify rows because no policy permits those actions.
What default deny means
With RLS enabled and no applicable policy:
SELECTreturns no rows.INSERTis rejected.UPDATEchanges no rows.DELETEdeletes no rows.
The exact result depends on the command and the query, but the security result is the same: an ordinary role cannot use the table through RLS until a policy allows it.
Table owners and bypass roles
Default deny applies to roles that are subject to RLS. By default, the table owner bypasses RLS. A superuser and a role with the BYPASSRLS attribute also bypass it.
This can make an owner appear to have access even when an application role does not:
CREATE ROLE app_user LOGIN;
GRANT SELECT ON documents TO app_user;
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
-- Run as the table owner:
SELECT * FROM documents;
-- Run as app_user:
SET ROLE app_user;
SELECT * FROM documents; -- no rows
RESET ROLE;If the table owner must also obey policies, use FORCE ROW LEVEL SECURITY:
ALTER TABLE documents FORCE ROW LEVEL SECURITY;This setting does not affect superusers or roles with BYPASSRLS.
Exercise
Exercise
A role has SELECT permission on a table, but RLS is enabled and the table has no policies. What should a normal SELECT return?
Show answer
It should return no rows. The role has the table privilege, but no RLS policy allows access to any row.