Sub topic 6
Targeting policies at roles
This chapter assumes you know CREATE POLICY, USING, and WITH CHECK from the earlier chapters, and that you are comfortable with CREATE ROLE, GRANT, and group roles. Here you decide which roles a policy applies to. You also learn how that choice interacts with privileges, role membership, and default deny.
The TO clause
CREATE POLICY accepts an optional TO clause with a list of roles:
CREATE POLICY name ON table
[ AS { PERMISSIVE | RESTRICTIVE } ]
[ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]
[ TO role_name [, ...] ]
[ USING ( ... ) ]
[ WITH CHECK ( ... ) ];If you leave TO out, the policy applies to PUBLIC, which means every role. If you name roles, the policy applies only to those roles. For any other role the policy does not exist. It does not filter rows and it does not grant access.
The list can contain role names, PUBLIC, CURRENT_USER, and SESSION_USER. The last two are resolved when you create the policy, so they are rarely what you want in a long-lived policy.
How a role is matched
PostgreSQL compares the policy's role list with the role in effect for the query, which is current_user. This has three consequences.
SET ROLEchanges which policies apply, because it changescurrent_user. This is whySET ROLEis a good testing tool.- A policy that names a group role applies to its members when they inherit the group's privileges. The default
INHERITbehavior gives you that. A member created withNOINHERITdoes not get the group's policies until it runsSET ROLEto the group. - Inside a
SECURITY DEFINERfunction,current_useris the function's owner. Policies for that owner apply, not policies for the caller.
Targeting group roles is usually better than listing individual users. A new hire joins a group and immediately gets the right policies, and you do not touch the policy definitions.
Privileges and policies are separate layers
A role needs both a table privilege and an applicable policy. PostgreSQL checks the privilege first. Without it, the query fails with permission denied. Policies then decide which rows are visible or writable.
The outcome depends on the combination:
| Table privilege | Applicable policy | Result |
|---|---|---|
| No | Yes | `permission denied for table` |
| Yes | No | Zero rows returned, writes rejected |
| Yes | Yes | Rows are limited by the policy expressions |
| Yes | Yes, but the role is exempt from RLS | All rows, policies ignored |
The second row catches many people. When RLS is enabled and no policy applies to a role, default deny gives that role an empty table. It does not raise an error.
A worked example: three audiences, one table
A help desk table has three audiences. Customers manage their own tickets. Support staff read all tickets and update them, but never delete. Auditors read only tickets that are not marked internal.
First create the roles. customer, support, and auditor are group roles. The other roles are members, and hank is a role with a grant but no group.
CREATE ROLE customer NOLOGIN;
CREATE ROLE support NOLOGIN;
CREATE ROLE auditor NOLOGIN;
CREATE ROLE erin LOGIN IN ROLE customer;
CREATE ROLE dana LOGIN IN ROLE support;
CREATE ROLE gus LOGIN IN ROLE auditor;
CREATE ROLE hank LOGIN;Then create the table, grant privileges to the groups, and enable RLS:
CREATE TABLE tickets (
id bigserial PRIMARY KEY,
owner_name text NOT NULL DEFAULT current_user,
subject text NOT NULL,
internal boolean NOT NULL DEFAULT false
);
ALTER TABLE tickets ENABLE ROW LEVEL SECURITY;
GRANT SELECT, INSERT, UPDATE, DELETE ON tickets TO customer;
GRANT USAGE ON SEQUENCE tickets_id_seq TO customer;
GRANT SELECT, UPDATE ON tickets TO support;
GRANT SELECT ON tickets TO auditor;
GRANT SELECT ON tickets TO hank;Now create one policy for each audience:
CREATE POLICY customer_own ON tickets
FOR ALL
TO customer
USING (owner_name = current_user)
WITH CHECK (owner_name = current_user);
CREATE POLICY support_read ON tickets
FOR SELECT
TO support
USING (true);
CREATE POLICY support_update ON tickets
FOR UPDATE
TO support
USING (true)
WITH CHECK (true);
CREATE POLICY auditor_read ON tickets
FOR SELECT
TO auditor
USING (NOT internal);Load three rows as the table owner. The owner is exempt from RLS because you have not used FORCE, so these inserts work:
INSERT INTO tickets (owner_name, subject, internal) VALUES
('erin', 'Login fails', false),
('zoe', 'Refund', false),
('zoe', 'Fraud review', true);Now act as each role:
SET ROLE erin;
SELECT subject FROM tickets; -- Login fails
RESET ROLE;
SET ROLE dana;
SELECT count(*) FROM tickets; -- 3
UPDATE tickets SET internal = true WHERE subject = 'Refund'; -- UPDATE 1
DELETE FROM tickets WHERE id = 1; -- ERROR: permission denied for table tickets
RESET ROLE;
SET ROLE gus;
SELECT subject FROM tickets; -- Login fails (the Refund ticket is now internal)
RESET ROLE;
SET ROLE hank;
SELECT count(*) FROM tickets; -- 0
RESET ROLE;Each result shows a different part of the model:
erininheritscustomer, socustomer_ownapplies and filters to her rows.danamatches two policies, one per command, and sees everything. HerDELETEfails at the privilege layer, before any policy runs.gusis limited byauditor_read. Afterdana's update, the Refund ticket is internal and disappears from his view.hankhasSELECTbut no applicable policy, so default deny returns zero rows.
Users in several groups
When a role matches several permissive policies for the same command, PostgreSQL combines them with OR. If dana were also a member of customer, she would see the rows allowed by support_read or by customer_own. For this reason, role-targeted permissive policies are additive: each new group adds access and never removes any.
Restrictive policies are combined with AND, and they also respect TO. A restrictive policy applies to a role only if it names that role or PUBLIC. Remember that a restrictive policy only narrows access. If no permissive policy applies to a role, adding restrictive ones will not let any rows through.
Changing and inspecting role targets
ALTER POLICY can change the role list, USING, and WITH CHECK. It cannot change the command or the permissive/restrictive type, so for those you drop and recreate the policy.
ALTER POLICY auditor_read ON tickets
TO auditor, support;
SELECT policyname, cmd, permissive, roles, qual, with_check
FROM pg_policies
WHERE tablename = 'tickets'
ORDER BY policyname;In pg_policies, the roles column lists the targets. A policy without a TO clause shows {public}. Review this column whenever you audit access, because a policy meant for one group can end up on PUBLIC if someone forgets the clause.
Common mistakes
- Forgetting
TO. The policy then applies to every role that has table privileges, including ones you did not plan for. - Testing only as a superuser. Superusers and roles with
BYPASSRLSignore policies, so every test passes. Always test withSET ROLEto an ordinary role. - Assuming a policy grants privileges. A policy only filters rows. It never replaces
GRANT. - Using
NOINHERITmembers without noticing. Such a role matches no group policies until it switches to the group role. - Dropping roles still named in policies.
DROP ROLEfails while a policy depends on the role. Remove or alter those policies first, or useDROP OWNED BY role, which drops the policies that depend on that role (and any objects it owns).
Exercise
A role ivy has SELECT on tickets and belongs to no group role. The only policy on the table is CREATE POLICY p ON tickets FOR SELECT USING (NOT internal); with no TO clause. What does ivy see, and why? Then say what changes if you add TO support to the policy.
Show answer
ivy sees every ticket where internal is false. A policy without TO applies to PUBLIC, so it matches ivy. After adding TO support, the policy no longer applies to ivy. No policy remains for her, so default deny applies and she sees zero rows, with no error.
Exercise
dana is a member of support (policy support_read with USING (true)) and of customer (policy customer_own with USING (owner_name = current_user)). Both are permissive SELECT policies and both roles inherit. Which rows can dana read? Would a restrictive policy TO customer change that for her?
Show answer
She can read all rows. The two permissive policies are combined with OR, and support_read is always true. A restrictive policy TO customer would apply to her, because she inherits customer. It would be ANDed with the permissive result and so would narrow what she can see.
Exercise
A new role kim is added to auditor. She runs SELECT * FROM tickets and gets permission denied for table tickets. Name the layer that failed and how to confirm it.
Show answer
The privilege layer failed, not the policy layer. auditor has SELECT in this chapter's setup, so check whether kim actually inherits it (for example, a NOINHERIT membership) and run \dp tickets in psql to see the grants. A missing policy would give zero rows, not an error.