Sub topic 15
Beyond GRANT: a first look at row-level security
Prerequisites and the working model
This chapter assumes that you can connect to PostgreSQL, create tables, and use roles and GRANT. It also assumes that shop.orders exists and that alice belongs to app_readonly.
A table privilege answers, “Can this role use this table?” Row-level security answers a narrower question: “Which rows may this role use?” PostgreSQL checks both controls. A user needs the required table privilege, and the row must pass the applicable security policy.
Enable row-level security
Enable row-level security on the table, then create a policy. This example permits members of app_readonly to see orders whose sales_rep value matches the login role's name.
ALTER TABLE shop.orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_orders
ON shop.orders
FOR SELECT
TO app_readonly
USING (sales_rep = current_user);USING is a Boolean expression. PostgreSQL evaluates it for each row. A row is visible only when the expression is true. current_user is the role currently being used for permission checks. When Alice connects as alice, the policy compares sales_rep with alice.
The policy does not grant SELECT. Alice still needs table access:
GRANT USAGE ON SCHEMA shop TO app_readonly;
GRANT SELECT ON shop.orders TO app_readonly;If Alice queries the table, she sees only her own orders:
SELECT id, customer, sales_rep, total
FROM shop.orders
ORDER BY id;Policies for writes
A SELECT policy controls visibility. For INSERT and UPDATE, use WITH CHECK to control the rows a user may create or produce. For example, this policy lets a sales representative update only rows assigned to that representative:
CREATE POLICY update_own_orders
ON shop.orders
FOR UPDATE
TO app_writer
USING (sales_rep = current_user)
WITH CHECK (sales_rep = current_user);USING chooses which existing rows may be updated. WITH CHECK validates the new version of each row. Without the second condition, a user might update an allowed row and change its sales_rep value to another user.
Important exceptions
Table owners normally bypass row-level security. In this example, app_owner can see every row even when a policy would hide it. A superuser or a role with the BYPASSRLS attribute also bypasses policies.
To make the owner subject to policies, use:
ALTER TABLE shop.orders FORCE ROW LEVEL SECURITY;Use this carefully. Administrative jobs and migrations often need owner access.
Exercise
Why might Alice receive no rows even when the row-level policy expression is true?
Show answer
She may not have SELECT on the table, or she may lack USAGE on the shop schema. Row-level security cannot grant missing object privileges.