Sub topic 14
Policies that query other tables
This chapter covers policies whose USING or WITH CHECK expression reads another table. It assumes you can write a basic policy, you know the difference between USING and WITH CHECK, and you know which roles bypass RLS. It also assumes the roles alice and bob exist from the earlier examples.
Why a policy needs another table
A single-table rule such as owner_name = current_user stops working once access depends on a relationship. Examples include "you can see a task if you belong to its project" and "you can see an invoice line if you can see its invoice". The ownership information lives in a second table, so the policy has to look there.
The usual shape is a membership table:
CREATE TABLE projects (
id bigserial PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE project_members (
project_id bigint NOT NULL REFERENCES projects (id),
member_name text NOT NULL,
PRIMARY KEY (project_id, member_name)
);
CREATE TABLE tasks (
id bigserial PRIMARY KEY,
project_id bigint NOT NULL REFERENCES projects (id),
title text NOT NULL
);A subquery policy on a table without RLS
The simplest case is a policy on tasks that checks project_members, where project_members has no RLS of its own:
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
CREATE POLICY tasks_by_membership ON tasks
USING (EXISTS (
SELECT 1
FROM project_members m
WHERE m.project_id = tasks.project_id
AND m.member_name = current_user
))
WITH CHECK (EXISTS (
SELECT 1
FROM project_members m
WHERE m.project_id = tasks.project_id
AND m.member_name = current_user
));
GRANT SELECT, INSERT, UPDATE, DELETE ON tasks TO alice, bob;
GRANT USAGE ON SEQUENCE tasks_id_seq TO alice, bob;
GRANT SELECT ON projects, project_members TO alice, bob;Two points matter here.
- The subquery runs with the caller's privileges.
aliceneedsSELECTonproject_members, or the query ontasksfails with a permission error. The policy does not borrow the table owner's rights. - The subquery is subject to the other table's RLS. If
project_membershas RLS enabled, its policies filter the rows the subquery sees. This is where recursion problems begin.
Infinite recursion
Suppose you also want members to see who else is on their projects. The obvious policy on project_members queries project_members:
ALTER TABLE project_members ENABLE ROW LEVEL SECURITY;
CREATE POLICY members_see_peers ON project_members
USING (project_id IN (
SELECT project_id
FROM project_members
WHERE member_name = current_user
));The policy is accepted when you create it. The first query that touches the table fails:
ERROR: infinite recursion detected in policy for relation "project_members"To read project_members, PostgreSQL applies the policy. The policy reads project_members, which applies the policy again, and so on. PostgreSQL detects this while it rewrites the query, so the error appears at query time and not at CREATE POLICY time.
Indirect cycles fail the same way. If a policy on projects reads tasks, and the tasks policy reads projects, the loop spans two tables. It is easy to create this by accident when you add a policy to a table that other policies already reference.
Breaking the loop with a SECURITY DEFINER function
The standard fix moves the lookup into a function that runs with its owner's privileges. If the owner is exempt from RLS on the table, the lookup does not trigger the policy. The owner of a table is exempt unless you used FORCE ROW LEVEL SECURITY. A role with BYPASSRLS is also exempt.
CREATE FUNCTION is_member(p_project_id bigint, p_user text)
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = public, pg_temp
AS $$
SELECT EXISTS (
SELECT 1
FROM project_members
WHERE project_id = p_project_id
AND member_name = p_user
);
$$;
DROP POLICY members_see_peers ON project_members;
CREATE POLICY members_see_peers ON project_members
USING (is_member(project_id, current_user));
DROP POLICY tasks_by_membership ON tasks;
CREATE POLICY tasks_by_membership ON tasks
USING (is_member(project_id, current_user))
WITH CHECK (is_member(project_id, current_user));Run the CREATE FUNCTION as the owner of project_members, so the function runs as a role that bypasses RLS.
Several details in this function are deliberate.
- The user name is a parameter. Inside a
SECURITY DEFINERfunction,current_userreturns the function's owner and not the caller. Writingmember_name = current_userinside the function would compare against the owner and silently give wrong answers. The policy evaluatescurrent_userin the caller's context and passes it in. search_pathis pinned. A definer function with a mutable search path can be tricked into calling objects an attacker created in a schema earlier on the path.pg_tempgoes last so temporary objects cannot shadow real ones.- The function is
STABLE. It reads the database but does not modify it, which lets the planner call it once per row at most and use it in index conditions. - It is callable by everyone. New functions grant
EXECUTEtoPUBLICby default. Any role that can callis_membercan probe whether any user belongs to any project. If that matters, revokeEXECUTEfromPUBLICand grant it only to the roles that need it.
Choosing an approach
| Approach | Strength | Weakness |
|---|---|---|
| Inline `EXISTS` subquery | Visible in `pg_policies`, and the planner can see the whole query | Fails with recursion if the other table's policies refer back; the caller needs `SELECT` on the other table |
| `SECURITY DEFINER` function | Avoids recursion and hides the lookup table from callers | Opaque to the planner; easy to write the `current_user` mistake; needs careful ownership and `search_path` |
| Denormalized column (for example `tenant_id` copied onto each table) | Fast, with no lookup | The copy must be kept consistent and the duplicated column adds write cost |
For multi-tenant systems, the denormalized column usually wins. Copying tenant_id onto child tables lets every policy use the same cheap predicate from the previous chapter. Use a lookup function when access depends on a many-to-many relationship that you cannot flatten.
Testing it
Insert data as the table owner, then check what each role sees:
INSERT INTO projects (name) VALUES ('Apollo'), ('Gemini');
INSERT INTO project_members VALUES (1, 'alice'), (2, 'bob');
INSERT INTO tasks (project_id, title)
VALUES (1, 'Plan launch'), (2, 'Review budget');
SET ROLE alice;
SELECT title FROM tasks; -- Plan launch
INSERT INTO tasks (project_id, title)
VALUES (2, 'Sneaky'); -- ERROR: new row violates row-level security policy
RESET ROLE;Alice sees only the task for project 1. The insert fails because WITH CHECK calls is_member(2, 'alice'), which returns false.
Performance and visibility
A policy that reads another table adds work to every query on the protected table.
- Index the lookup. The primary key
(project_id, member_name)above serves theEXISTSlookup. Without it, each row check becomes a scan. - Function calls run per row. PostgreSQL does not inline
SECURITY DEFINERfunctions, so the planner treats them as black boxes. ASTABLEfunction is evaluated at most once per candidate row. CheckEXPLAINon a realistic data volume, and compare it with the inlineEXISTSform, which the planner can sometimes turn into a join. - Policy conditions run before your conditions. PostgreSQL evaluates policy expressions first, unless your own function is marked
LEAKPROOF. This prevents a user function from observing rows the policy would hide, but it can stop the planner from using yourWHEREclause for an index scan. - Nothing is cached across statements. Each query evaluates the policy against the current snapshot, so a membership change takes effect on the next statement.
Common mistakes
- Recursive lookups. A policy that reads its own table, directly or through a cycle of tables, fails with the recursion error. Break the cycle with a definer function or a denormalized column.
- Forgetting
SELECTon the lookup table. The error shows up aspermission denied for table project_memberswhen a user queriestasks, which can be confusing because the user never named that table. - Using
current_userinside the definer function. It returns the owner, so every check compares against the wrong name. - Using
FORCEon the lookup table and also relying on owner bypass.FORCE ROW LEVEL SECURITYmakes the owner subject to policies, so the definer function loops again. Either use a separateBYPASSRLSowner for the function or avoidFORCEon that table.
Exercise
A policy on comments uses USING (EXISTS (SELECT 1 FROM posts WHERE posts.id = comments.post_id)), and posts has a policy that lets each user see only their own posts. A user reports that they can see comments only on their own posts, even though comments should be visible whenever the post is public. What is the cause, and how would you fix it without exposing the posts table's private rows?
Show answer
The subquery runs with the caller's privileges and is filtered by the posts policy, so it can only find posts the user owns. Move the lookup into a STABLE SECURITY DEFINER function owned by a role that bypasses RLS on posts, with SET search_path pinned. The function should take the post id and return whether the post is public. Call it from the comments policy, for example USING (is_public_post(post_id)). Because the function returns only a boolean, the private post rows stay hidden.