Role Membership Inheritance

Grant one role to another so privileges flow through membership, and control whether members inherit automatically or must SET ROLE first.

SqlSecurity Boundaries

Code

snippet
-- 权限容器:NOLOGIN 角色只装权限,不让人直接登录
CREATE ROLE app_read NOLOGIN;
GRANT SELECT ON orders TO app_read;

-- 用户成员继承容器权限:INHERIT(默认)下登录即有 SELECT
CREATE ROLE analyst LOGIN INHERIT;
GRANT app_read TO analyst;

-- NOINHERIT 成员:授权不会自动生效,必须显式 SET ROLE
CREATE ROLE auditor LOGIN NOINHERIT;
GRANT app_read TO auditor;

-- auditor 直接查询会失败(未继承):
-- SELECT * FROM orders;  -- ERROR: permission denied for table orders

-- 显式切换到容器角色后权限可用,SET ROLE NONE 切回自身
SET ROLE app_read;
SELECT count(*) FROM orders;
RESET ROLE;

-- 复核成员关系
SELECT r.rolname AS member, g.rolname AS granted_role
FROM pg_auth_members m
JOIN pg_roles r ON r.oid = m.member
JOIN pg_roles g ON g.oid = m.roleid;

What the code does

What runs here is SELECT / CREATE — orders, pg_auth_members and pg_roles are the objects involved.

Breaking the statements into their working parts: 2 JOINs combining rows across tables; COUNT aggregation.

What to watch for

  • 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.

Applying it

Run the statement against the orders table.

Statements that matter

SELECT r.rolname AS member, g.rolname AS granted_role
FROM pg_auth_members m
JOIN pg_roles r ON r.oid = m.member
JOIN pg_roles g ON g.oid = m.roleid;
CREATE ROLE auditor LOGIN NOINHERIT;
GRANT SELECT ON orders TO app_read;

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`orders`, `pg_auth_members`, `pg_roles` — joined via 2 JOIN clauses.