From e4bc498c2827dbda6df1d178dcda471639fe9bf4 Mon Sep 17 00:00:00 2001 From: Lorenzo Corallo Date: Sun, 15 Nov 2026 02:43:39 +0100 Subject: [PATCH] fix(rbac): only Master Admin can confer a built-in role through inheritance A role reports every role it inherits, so a delegated role administrator could create a role inheriting Presidente (or Socio, Direttivo, Segretario, Student) and assign it to anyone. Unless Master Admin, a change may no longer alter which built-in roles any role inherits, and nobody else may give or take back a role that inherits one, from the dashboard, the MCP server or People. The editor stops offering those parents and assignments. Co-Authored-By: Claude --- README.md | 6 +- docs/rbac-security-review.md | 8 +- src/auth/mcp-server.ts | 2 +- src/auth/people-binding.test.ts | 23 ++++ src/auth/people-binding.ts | 7 ++ src/auth/rbac-delegation.ts | 32 +++++ src/auth/rbac-security.integration.test.mjs | 39 +++++++ src/auth/rbac-store.ts | 26 ++++- src/auth/rbac.test.ts | 123 ++++++++++++++++++++ src/auth/rbac.ts | 18 +++ src/components/rbac/delegation.test.ts | 40 ++++++- src/components/rbac/delegation.ts | 22 +++- src/components/rbac/role-form.tsx | 13 ++- src/components/users/user-roles.tsx | 8 +- 14 files changed, 346 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 4d438d6..ce42299 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,10 @@ inherit from `Socio`, everyone holding your role also reports the `socio` role a permissions, whether or not Entra says they are a member. Inherit from a built-in role only when that is what you mean. +So only a Master Admin can make a role inherit from a built-in role, directly or through +another role, and only a Master Admin can give or take back a role that does, here or from +People. Holding `idp:roles:write` and `idp:roles:assign` is not enough. + ### Permissions the identity provider defines itself Administering this service is expressed as permissions like any other capability, so it can @@ -373,7 +377,7 @@ The backend only names the actor; this IdP resolves the actor's own access and r | `team::member` | `admin:access` + `people:write`, or the Lead of that team | | `team::lead` | `admin:access` + `people:appoint` | -- unless Master Admin, the actor holds every permission the role grants. +- unless Master Admin, the actor holds every permission the role grants, and the role does not inherit a built-in role. The backend applies the same rules to assignments it keeps for records that aren't linked yet, which this IdP only sees when the record is linked: that is what each bound role's `permissions` and `bindings` are for. diff --git a/docs/rbac-security-review.md b/docs/rbac-security-review.md index 42afd54..9966712 100644 --- a/docs/rbac-security-review.md +++ b/docs/rbac-security-review.md @@ -44,7 +44,7 @@ No known code-remediable blocker in the audited RBAC paths is deliberately defer - Microsoft Graph propagation and real upstream provider availability are outside this repository. No live tenant, Google, Telegram or mail-delivery integration was exercised. Membership tests simulate positive, negative, expired, failed and superseded checks. A Graph outage loses group-derived access after the short cache expires; the explicit break-glass allowlist remains available. - The 60 seconds is the application cache bound for new authorization decisions, not a promise to cancel requests already in progress. Already-issued five-minute OIDC tokens remain valid until expiry. A token minted near the cache deadline can therefore retain group-derived rights for approximately six minutes, plus upstream propagation and consumer clock tolerance. Consumers requiring immediate revocation must use fresh authorization rather than offline token claims. - PostgreSQL owners and deployment operators are trusted. They can disable triggers/change configuration. Audit events resist application UPDATE/DELETE/TRUNCATE, but protection from database owners requires external, separately administered audit retention. Console denial logs likewise require an operational log sink. -- A custom role may still inherit Socio/Direttivo/Student permissions without conferring the corresponding raw identity state. This is documented product behavior; downstream applications should authorize by permissions and use `states` when they need evidence of actual membership. +- A custom role may still inherit Socio/Direttivo/Student permissions without conferring the corresponding raw identity state. This is documented product behavior, and only Master Admin can set it up (see §6); downstream applications should authorize by permissions and use `states` when they need evidence of actual membership. - Bounded delegation protects the stored graph, not arbitrary downstream interpretations of new permission names or future edits made by Master Admin. Master Admin remains intentionally omnipotent. - Built-in OAuth client SDK actions check current authorization at their provider hook; an action already authorized before revocation may finish. Local RBAC mutations additionally reauthorize inside their serialized mutation transaction. There is no claim of distributed cancellation across the upstream identity provider and the database. @@ -76,6 +76,12 @@ No additional environment variables or migrations are needed for these follow-up Validation: formatting, lint, TypeScript, production build, Docker image build/startup, and the full suite against disposable PostgreSQL and the compiled HTTP server: **152 passed, zero skipped**. Upgrade rehearsals from `main` and the original RBAC branch preserve existing states and record/remove unsafe legacy links. Missing bootstrap configuration stops the container before migrations. Browser checks cover delegated read-only controls, Master Admin editing and page navigation. The integration tests include a blocked Graph lookup concurrent with an unrelated write and account unlink, proving both progress and denial of stale authority. The limits in section 3 still apply. +## 6. Built-in roles given through inheritance + +A later review found that the built-in roles could be handed out without a Master Admin. + +- **A delegated role administrator could confer any built-in role through a parent.** Holding a role reports every role it inherits, in the `groups` and `polinetwork_roles` claims and in the backend access snapshot, and the backend authorizes on those keys. `validateRoleDraft` only refused Master Admin as a parent, and bounded delegation only compared permissions. So someone with `idp:roles:write` and `idp:roles:assign`, holding what Presidente grants, could create a role inheriting `presidente` (or `socio`, `direttivo`, `segretario`, `student`) and assign it to anyone, who then held `presidente` and `direttivo` everywhere. Adding the parent to an existing role worked too. Fixed: unless Master Admin, a change may not alter which built-in roles any role inherits, directly or through another role (`inheritedBuiltInRoleChanges` in `src/auth/rbac-delegation.ts`), and nobody else may give or take back a role that inherits one, from the dashboard, the MCP server or People (`inheritedBuiltInRoles` in `src/auth/rbac.ts`). The editor no longer offers such parents or assignments. Master Admin keeps full control. No production role inherited a built-in role, so nothing existing changes. Unit and PostgreSQL regressions cover creation, assignment, the indirect case and the People path. + ## Authorization model and coverage notes - Resolution order: persisted user → owned accounts and trusted evidence → current group checks/student evidence → configured Master Admin + manual custom roles → role inheritance → transitive permission implications. There are no explicit deny rules or client-selected tenants. Roles/permissions use normalized lowercase keys; reads/checks use exact matching. Only Master Admin has wildcard behavior. diff --git a/src/auth/mcp-server.ts b/src/auth/mcp-server.ts index 4346e76..a067946 100644 --- a/src/auth/mcp-server.ts +++ b/src/auth/mcp-server.ts @@ -842,7 +842,7 @@ export function createMcpServer(principal: McpPrincipal) { { title: "Manage a role from People", description: - "Binds a hand-made role to the admin dashboard's People register, or unbinds it with null. Holders of a bound role appear in People, and whoever may change that part of People can give or take it back, never to themselves and never beyond the permissions they hold. Roles carrying idp:* permissions can't be bound, and only Master Admin can bind or unbind a role granting permissions you don't hold.", + "Binds a hand-made role to the admin dashboard's People register, or unbinds it with null. Holders of a bound role appear in People, and whoever may change that part of People can give or take it back, never to themselves and never beyond the permissions they hold. Roles carrying idp:* permissions can't be bound, and only Master Admin can bind or unbind a role granting permissions you don't hold. A role inheriting a built-in role is given and taken back only by Master Admin.", inputSchema: z.object({ role: roleRef, binding: z diff --git a/src/auth/people-binding.test.ts b/src/auth/people-binding.test.ts index 42bebcd..26d1933 100644 --- a/src/auth/people-binding.test.ts +++ b/src/auth/people-binding.test.ts @@ -330,3 +330,26 @@ it("describes each bound role with its effective permissions and inherited bindi // Roles People can't manage are left out, as everywhere else. expect(described.map((entry) => entry.key)).not.toContain("sneaky"); }); + +it("leaves bound roles that inherit a built-in role to Master Admin", () => { + const socio = { ...role("socio", ["people:self"]), managed: true }; + const member = role("socio-member", ["people:self"], "team:events:member", ["socio"]); + const extended = { ...catalog, roles: [...catalog.roles, socio, member] }; + const problem = (actorRoles: string[], overrides: Partial = {}) => + peopleRoleChangeProblem({ + catalog: extended, + actorId: "actor", + actor: resolveAccess(extended, actorRoles), + targetId: "target", + role: member, + action: "assign", + ...overrides, + }); + // Direttivo holds every permission the role grants, and may give ordinary team roles. + expect(problem(["direttivo"])).toMatch(/Only a Master Admin.*socio/); + expect(problem(["direttivo"], { action: "unassign" })).toMatch(/Only a Master Admin/); + expect(problem([MASTER_ADMIN_ROLE_KEY])).toBeNull(); + expect(problem([MASTER_ADMIN_ROLE_KEY], { action: "unassign" })).toBeNull(); + // Giving up one's own role stays allowed. + expect(problem([], { targetId: "actor", action: "unassign" })).toBeNull(); +}); diff --git a/src/auth/people-binding.ts b/src/auth/people-binding.ts index 24b268a..3a1997c 100644 --- a/src/auth/people-binding.ts +++ b/src/auth/people-binding.ts @@ -6,7 +6,9 @@ import { MASTER_ADMIN_ROLE_KEY, effectiveRolePermissions, expandRoleKeys, + inheritedBuiltInRoles, isManagedPermissionKey, + roleNames, } from "./rbac"; /** @@ -116,6 +118,8 @@ function ruleProblem(context: PeopleRuleContext): string | null { * * - Only bound roles, and only while they carry no `idp:*` permission. * - Nobody gives themselves a role. Giving one up is always allowed: it only removes access. + * - Unless Master Admin, nobody gives or takes back a role that inherits a built-in role: + * holding it means holding the built-in role, which only a Master Admin confers. * - The rule of the role's binding kind, and of every binding it inherits: a member role * wrapping a Lead role needs what the Lead role needs. See `PEOPLE_RULES`. * - Bounded delegation, as in the dashboard: unless Master Admin, the actor must already hold @@ -128,6 +132,9 @@ export function peopleRoleChangeProblem(change: PeopleRoleChange): string | null if (problem) return problem; if (actorId === targetId) return action === "unassign" ? null : "Nobody can give themselves a role."; + const builtIn = inheritedBuiltInRoles(catalog, role.key); + if (builtIn.length && !actor.roles.includes(MASTER_ADMIN_ROLE_KEY)) + return `Only a Master Admin can give or take back ${role.name}, because it also gives ${roleNames(catalog, builtIn)}.`; const holds = (key: string) => actor.permissions.includes(key); const general = (key: string) => holds(ADMIN_ACCESS_PERMISSION) && holds(key); diff --git a/src/auth/rbac-delegation.ts b/src/auth/rbac-delegation.ts index dc470dd..1d7a3a6 100644 --- a/src/auth/rbac-delegation.ts +++ b/src/auth/rbac-delegation.ts @@ -4,9 +4,30 @@ import { MASTER_ADMIN_ROLE_KEY, effectiveRolePermissions, expandPermissionKeys, + inheritedBuiltInRoles, resolveAccess, } from "./rbac"; +/** + * The built-in roles that some role, matched by id, gives through inheritance in one graph + * but not in the other, sorted. A role missing from a graph gives none there, so a new role + * that inherits a built-in role counts, and so does deleting one. + */ +export function inheritedBuiltInRoleChanges(before: RbacCatalog, after: RbacCatalog): string[] { + const reached = (catalog: RbacCatalog, id: string) => { + const found = catalog.roles.find((entry) => entry.id === id); + return new Set(found ? inheritedBuiltInRoles(catalog, found.key) : []); + }; + const changed = new Set(); + for (const id of new Set([...before.roles, ...after.roles].map((entry) => entry.id))) { + const was = reached(before, id); + const is = reached(after, id); + for (const key of was) if (!is.has(key)) changed.add(key); + for (const key of is) if (!was.has(key)) changed.add(key); + } + return [...changed].sort(); +} + /** Compare both committed and proposed graphs. Called under the mutation lock; a false * result rolls back the entire transaction, including edge replacements and assignments. */ export function mayDelegateMutation( @@ -39,8 +60,19 @@ export function mayDelegateMutation( if (old?.managed || next?.managed) return false; if (old && !subset(effectiveRolePermissions(before, old.key))) return false; if (next && !subset(effectiveRolePermissions(after, next.key))) return false; + // Giving or taking back a role that inherits a built-in role gives or takes back the + // built-in role too, which only a Master Admin does. + if ( + (operation === "role.assign" || operation === "role.unassign") && + old && + inheritedBuiltInRoles(before, old.key).length + ) + return false; } if (!subset(resolveAccess(after, access.roles).permissions)) return false; + // Only a Master Admin confers a built-in role, so nobody else may change which built-in + // roles any role inherits, directly or through another role. + if (inheritedBuiltInRoleChanges(before, after).length) return false; // Custom ancestors/implications cannot act as a backdoor for editing managed or // more privileged roles, including roles the writer does not themselves hold. for (const old of before.roles) { diff --git a/src/auth/rbac-security.integration.test.mjs b/src/auth/rbac-security.integration.test.mjs index ed7f70d..985fb46 100644 --- a/src/auth/rbac-security.integration.test.mjs +++ b/src/auth/rbac-security.integration.test.mjs @@ -82,6 +82,7 @@ import { } from "./rbac.functions"; import { updateOidcClientFn } from "./oidc.functions"; import { callServerFn } from "./server-fn-harness"; +import { effectiveRolePermissions } from "./rbac"; const root = "security-root"; const ordinary = "security-ordinary"; @@ -322,6 +323,44 @@ describe.skipIf(!process.env.RBAC_TEST_DATABASE_URL)("RBAC security with Postgre await expect(assignRole(root, direttivo.id, ordinary)).rejects.toThrow(/Managed roles/); }); + it("leaves giving a built-in role through inheritance to Master Admin", async () => { + const catalog = await loadCatalog(root); + // The actor holds everything Presidente and Socio grant, so only the rule refuses them. + const granted = ["presidente", "socio"].flatMap((key) => + effectiveRolePermissions(catalog, key), + ); + const actor = await delegate([...new Set(["idp:roles:write", "idp:roles:assign", ...granted])]); + const refused = unique("helper"); + expect( + (await call(saveRoleFn, actor.id, { draft: draftRole(refused, [], ["presidente"]) })).status, + ).toBe(403); + expect((await pool.query("SELECT id FROM role WHERE key = $1", [refused])).rows).toEqual([]); + + const helper = await saveRole(root, draftRole(unique("helper"), [], ["presidente"])); + const change = (action) => + call(changeRoleMemberFn, actor.id, { action, roleId: helper.id, userId: ordinary }); + expect((await change("assign")).status).toBe(403); + await expect(assignRole(actor.id, helper.id, ordinary)).rejects.toThrow(/Presidente/); + await assignRole(root, helper.id, ordinary); + try { + expect((await getIdentity(ordinary)).roles).toEqual( + expect.arrayContaining(["presidente", "direttivo"]), + ); + expect((await change("unassign")).status).toBe(403); + } finally { + await unassignRole(root, helper.id, ordinary); + } + + // An existing role can't gain a built-in parent either, directly or through `helper`. + const plain = await saveRole(actor.id, draftRole(unique("plain"))); + for (const parent of ["socio", helper.key]) + await expect( + saveRole(actor.id, draftRole(plain.key, [], [parent]), plain.id), + ).rejects.toThrow(/Only a Master Admin/); + await assignRole(actor.id, plain.id, ordinary); + await unassignRole(actor.id, plain.id, ordinary); + }); + it("preserves bounded delegation while refusing direct and indirect managed-role edits", async () => { const own = await savePermission(root, draftPermission(unique("own"))); const actor = await delegate(["idp:roles:write", "idp:roles:assign", own.key]); diff --git a/src/auth/rbac-store.ts b/src/auth/rbac-store.ts index 79280ce..b3290f2 100644 --- a/src/auth/rbac-store.ts +++ b/src/auth/rbac-store.ts @@ -1,7 +1,7 @@ import { groupListings, traitConditions, searchCondition } from "./people-search"; import type { FieldErrors } from "@/lib/action-error"; import { contactEmails } from "./contact-email"; -import { mayDelegateMutation } from "./rbac-delegation"; +import { inheritedBuiltInRoleChanges, mayDelegateMutation } from "./rbac-delegation"; import { PEOPLE_BINDING_PATTERN, peopleBindingProblem } from "./people-binding"; import { logAuthorizationDenial } from "./denial-log"; import { readIdentitySubject, refreshIdentityMembership } from "./identity-subject"; @@ -35,9 +35,11 @@ import { MASTER_ASSIGNED_ROLE_KEYS, takesHandAssignments, catalogForIdpPermissions, + inheritedBuiltInRoles, normalizePermissionDraft, normalizeRoleDraft, resolveAccess, + roleNames, validatePermissionDraft, validateRoleDraft, withIntrinsicImplications, @@ -263,9 +265,12 @@ async function withRbacWriteLock( const next = await readCatalog(transaction); if (!mayDelegateMutation(catalog, next, access, operation, targetId)) { logAuthorizationDenial(actorId, "rbac-store", ["bounded-delegation"]); + const builtIn = inheritedBuiltInRoleChanges(catalog, next); throw new RbacError( 403, - "This change exceeds your delegated authority. Ask a Master Admin.", + builtIn.length + ? `Only a Master Admin can change which roles give ${roleNames(next, builtIn)}.` + : "This change exceeds your delegated authority. Ask a Master Admin.", ); } const after = await auditSnapshot(transaction, next, operation, targetId); @@ -511,17 +516,26 @@ export function handAssignableRole() { /** Refuses a hand-made change to a role that takes none, or that only a Master Admin makes. */ function requireHandAssignment( actorId: string, + catalog: RbacCatalog, target: RoleSummary, access: ResolvedAccess, verb: "assigned" | "revoked", ) { if (!takesHandAssignments(target)) throw new RbacError(400, `Managed roles cannot be ${verb} by hand.`); - if (target.managed && !access.roles.includes(MASTER_ADMIN_ROLE_KEY)) { + if (access.roles.includes(MASTER_ADMIN_ROLE_KEY)) return; + const action = verb === "assigned" ? "assign" : "revoke"; + if (target.managed) { + logAuthorizationDenial(actorId, "rbac-store", ["master-admin"]); + throw new RbacError(403, `Only a Master Admin can ${action} ${target.name}.`); + } + // Holding the role means holding the built-in roles it inherits. + const builtIn = inheritedBuiltInRoles(catalog, target.key); + if (builtIn.length) { logAuthorizationDenial(actorId, "rbac-store", ["master-admin"]); throw new RbacError( 403, - `Only a Master Admin can ${verb === "assigned" ? "assign" : "revoke"} ${target.name}.`, + `Only a Master Admin can ${action} ${target.name}, because it also gives ${roleNames(catalog, builtIn)}.`, ); } } @@ -529,7 +543,7 @@ function requireHandAssignment( export async function assignRole(actorId: string, roleId: string, userId: string) { await withRbacWriteLock(actorId, "role.assign", roleId, async (transaction, catalog, access) => { const target = requireRole(catalog, roleId); - requireHandAssignment(actorId, target, access, "assigned"); + requireHandAssignment(actorId, catalog, target, access, "assigned"); const [found] = await transaction.select({ id: user.id }).from(user).where(eq(user.id, userId)); if (!found) throw new RbacError(404, "That person was not found."); await transaction @@ -546,7 +560,7 @@ export async function unassignRole(actorId: string, roleId: string, userId: stri roleId, async (transaction, catalog, access) => { const target = requireRole(catalog, roleId); - requireHandAssignment(actorId, target, access, "revoked"); + requireHandAssignment(actorId, catalog, target, access, "revoked"); await transaction .delete(userRole) .where(and(eq(userRole.roleId, roleId), eq(userRole.userId, userId))); diff --git a/src/auth/rbac.test.ts b/src/auth/rbac.test.ts index da912c8..4d21de5 100644 --- a/src/auth/rbac.test.ts +++ b/src/auth/rbac.test.ts @@ -10,6 +10,7 @@ import { effectiveRolePermissions, expandPermissionKeys, expandRoleKeys, + inheritedBuiltInRoles, isManagedPermissionKey, isStaticRoleKey, resolveAccess, @@ -20,6 +21,7 @@ import { validateRoleDraft, withIntrinsicImplications, } from "./rbac"; +import { inheritedBuiltInRoleChanges, mayDelegateMutation } from "./rbac-delegation"; function permission(key: string, implies: string[] = [], managed = false): PermissionSummary { return { @@ -436,3 +438,124 @@ describe("administration catalog visibility", () => { expect(visible).toEqual(catalog); }); }); + +describe("built-in roles given through inheritance", () => { + const ROLE_ADMIN = ["idp:roles:write", "idp:roles:assign", "idp:roles:read", "idp:people:read"]; + // The six built-in roles as production has them, with a delegated role administrator. + const base: RbacCatalog = { + permissions: [ + ...MANAGED_PERMISSIONS.map((entry) => permission(entry.key, [...entry.implies], true)), + permission("board:read"), + permission("team:read"), + ], + roles: [ + ...STATIC_ROLES.map((entry) => + role( + entry.key, + entry.key === "direttivo" ? ["board:read"] : [], + entry.key === "direttivo" ? ["socio"] : [...entry.parents], + true, + ), + ), + role("role-admin", ROLE_ADMIN), + role("team", ["team:read"]), + role("team-lead", [], ["team"]), + ], + }; + const actor = resolveAccess(base, ["direttivo", "role-admin", "team"]); + const master = resolveAccess(base, [MASTER_ADMIN_ROLE_KEY]); + const withRole = (catalog: RbacCatalog, entry: RoleSummary): RbacCatalog => ({ + ...catalog, + roles: [...catalog.roles.filter((other) => other.id !== entry.id), entry], + }); + const helper = role("helper", [], ["presidente"]); + const withHelper = withRole(base, helper); + + it("lists the built-in roles a role gives, without the role itself", () => { + expect(inheritedBuiltInRoles(withHelper, "helper")).toEqual([ + "direttivo", + "presidente", + "socio", + ]); + expect(inheritedBuiltInRoles(base, "presidente")).toEqual(["direttivo", "socio"]); + expect(inheritedBuiltInRoles(base, "socio")).toEqual([]); + expect(inheritedBuiltInRoles(base, "team-lead")).toEqual([]); + }); + + it("refuses a delegated writer who creates a role inheriting Presidente, then assigns it", () => { + const draft = { key: "helper", name: "helper", description: "", parents: ["presidente"] }; + // The draft itself is valid: the refusal comes from who is making the change. + expect(validateRoleDraft({ ...draft, permissions: [] }, { catalog: base })).toEqual({}); + expect(resolveAccess(withHelper, ["helper"]).roles).toEqual([ + "direttivo", + "helper", + "presidente", + "socio", + ]); + expect(mayDelegateMutation(base, withHelper, actor, "role.save", helper.id)).toBe(false); + expect(mayDelegateMutation(withHelper, withHelper, actor, "role.assign", helper.id)).toBe( + false, + ); + expect(mayDelegateMutation(withHelper, withHelper, actor, "role.unassign", helper.id)).toBe( + false, + ); + }); + + it("refuses inheriting any built-in role, by a new role or an existing one", () => { + for (const parent of ["socio", "direttivo", "presidente", "segretario", "student"]) { + const created = withRole(base, role("helper", [], [parent])); + expect(mayDelegateMutation(base, created, actor, "role.save", "r-helper")).toBe(false); + const edited = withRole(base, role("team", ["team:read"], [parent])); + expect(mayDelegateMutation(base, edited, actor, "role.save", "r-team")).toBe(false); + } + }); + + it("refuses giving a built-in role through another role", () => { + // A Master Admin made `helper`; inheriting it gives Presidente just the same. + const edited = withRole(withHelper, role("team", ["team:read"], ["helper"])); + expect(mayDelegateMutation(withHelper, edited, actor, "role.save", "r-team")).toBe(false); + // Adding Presidente to `team` also changes what `team-lead` gives. + const parent = withRole(base, role("team", ["team:read"], ["presidente"])); + expect(inheritedBuiltInRoles(parent, "team-lead")).toContain("presidente"); + expect(inheritedBuiltInRoleChanges(base, parent)).toEqual(["direttivo", "presidente", "socio"]); + }); + + it("refuses taking a built-in role back through the graph", () => { + const dropped = withRole(withHelper, role("helper", [], [])); + expect(mayDelegateMutation(withHelper, dropped, actor, "role.save", helper.id)).toBe(false); + const deleted = { ...withHelper, roles: withHelper.roles.filter((e) => e.id !== helper.id) }; + expect(mayDelegateMutation(withHelper, deleted, actor, "role.delete", helper.id)).toBe(false); + }); + + it("leaves Master Admin free to do all of it", () => { + expect(mayDelegateMutation(base, withHelper, master, "role.save", helper.id)).toBe(true); + expect(mayDelegateMutation(withHelper, withHelper, master, "role.assign", helper.id)).toBe( + true, + ); + expect( + validateRoleDraft( + { ...roleDraft("helper"), parents: [MASTER_ADMIN_ROLE_KEY] }, + { + catalog: base, + }, + ).parents, + ).toMatch(/Master Admin/); + }); + + it("still allows ordinary edits and assignments, built-in parents included", () => { + const created = withRole(base, role("helper", ["team:read"], ["team"])); + expect(mayDelegateMutation(base, created, actor, "role.save", "r-helper")).toBe(true); + expect(mayDelegateMutation(created, created, actor, "role.assign", "r-helper")).toBe(true); + expect(mayDelegateMutation(created, created, actor, "role.unassign", "r-helper")).toBe(true); + const deleted = { ...base, roles: base.roles.filter((e) => e.key !== "team-lead") }; + expect(mayDelegateMutation(base, deleted, actor, "role.delete", "r-team-lead")).toBe(true); + // Changing what a Master-made `helper` grants leaves what it inherits alone. + const granted = withRole(withHelper, role("helper", ["team:read"], ["presidente"])); + expect(inheritedBuiltInRoleChanges(withHelper, granted)).toEqual([]); + expect(mayDelegateMutation(withHelper, granted, actor, "role.save", helper.id)).toBe(true); + }); +}); + +function roleDraft(key: string) { + return { key, name: key, description: "", parents: [] as string[], permissions: [] as string[] }; +} diff --git a/src/auth/rbac.ts b/src/auth/rbac.ts index a65238e..7c84bf0 100644 --- a/src/auth/rbac.ts +++ b/src/auth/rbac.ts @@ -343,6 +343,24 @@ export function expandRoleKeys(catalog: RbacCatalog, roleKeys: Iterable) return [...reachable].filter((key) => index.roles.has(key)).sort(); } +/** + * The built-in roles that holding `roleKey` also gives through inheritance, not counting the + * role itself, sorted. Holders are reported as holding these roles everywhere, so only a + * Master Admin may change this list for any role, or give or take back a role for which it + * is not empty. + */ +export function inheritedBuiltInRoles(catalog: RbacCatalog, roleKey: string): string[] { + const managed = new Set(catalog.roles.filter((entry) => entry.managed).map((entry) => entry.key)); + return expandRoleKeys(catalog, [roleKey]).filter((key) => key !== roleKey && managed.has(key)); +} + +/** Role names for a message, such as "Direttivo and Presidente". */ +export function roleNames(catalog: RbacCatalog, keys: readonly string[]) { + return keys + .map((key) => catalog.roles.find((entry) => entry.key === key)?.name ?? key) + .join(" and "); +} + /** The given permissions plus every permission they grant, transitively. */ export function expandPermissionKeys( catalog: RbacCatalog, diff --git a/src/components/rbac/delegation.test.ts b/src/components/rbac/delegation.test.ts index 0bd04c8..13c2a55 100644 --- a/src/components/rbac/delegation.test.ts +++ b/src/components/rbac/delegation.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vite-plus/test"; import type { RbacCatalog } from "@/auth/rbac"; -import { canAssignRole, canGrantPermission, canGrantRole } from "./delegation"; +import { + canAssignRole, + canGrantPermission, + canGrantRole, + canInheritFrom, + confersBuiltInRole, +} from "./delegation"; const catalog: RbacCatalog = { permissions: ["read", "write"].map((key) => ({ @@ -80,3 +86,35 @@ describe("assigning the board offices", () => { expect(canAssignRole({ isMasterAdmin: true, permissions: [] }, offices, direttivo)).toBe(false); }); }); + +describe("roles that inherit a built-in role", () => { + const writer = catalog.roles[0]!; + const presidente = { ...writer, id: "presidente", key: "presidente", managed: true }; + const helper = { + ...writer, + id: "helper", + key: "helper", + permissions: [], + parents: ["presidente"], + }; + const roles: RbacCatalog = { ...catalog, roles: [...catalog.roles, presidente, helper] }; + const delegate = { isMasterAdmin: false, permissions: ["read", "write"] }; + const master = { isMasterAdmin: true, permissions: [] }; + + it("are not offered as parents to anyone but Master Admin", () => { + expect(confersBuiltInRole(roles, helper)).toBe(true); + expect(confersBuiltInRole(roles, writer)).toBe(false); + for (const parent of [presidente, helper]) { + expect(canGrantRole(delegate, roles, parent.key)).toBe(true); + expect(canInheritFrom(delegate, roles, parent)).toBe(false); + expect(canInheritFrom(master, roles, parent)).toBe(true); + } + expect(canInheritFrom(delegate, roles, writer)).toBe(true); + }); + + it("are given and taken back by Master Admin only", () => { + expect(canAssignRole(delegate, roles, helper)).toBe(false); + expect(canAssignRole(master, roles, helper)).toBe(true); + expect(canAssignRole(delegate, roles, writer)).toBe(true); + }); +}); diff --git a/src/components/rbac/delegation.ts b/src/components/rbac/delegation.ts index 8221a22..3c33f35 100644 --- a/src/components/rbac/delegation.ts +++ b/src/components/rbac/delegation.ts @@ -1,6 +1,7 @@ import { effectiveRolePermissions, expandPermissionKeys, + inheritedBuiltInRoles, type RbacCatalog, type RoleSummary, takesHandAssignments, @@ -27,10 +28,27 @@ export function canGrantRole(access: DelegationAccess, catalog: RbacCatalog, key ); } -/** Built-in roles that take assignments are given and taken back by Master Admin only. */ +/** Whether holding this role means holding a built-in role, which only Master Admin confers. */ +export function confersBuiltInRole(catalog: RbacCatalog, role: RoleSummary) { + return role.managed || inheritedBuiltInRoles(catalog, role.key).length > 0; +} + +/** Whether a role may be picked, or dropped, as a parent of another role. */ +export function canInheritFrom(access: DelegationAccess, catalog: RbacCatalog, role: RoleSummary) { + return ( + access.isMasterAdmin || + (!confersBuiltInRole(catalog, role) && canGrantRole(access, catalog, role.key)) + ); +} + +/** + * Built-in roles that take assignments, and roles inheriting any built-in role, are given and + * taken back by Master Admin only. + */ export function canAssignRole(access: DelegationAccess, catalog: RbacCatalog, role: RoleSummary) { return ( takesHandAssignments(role) && - (access.isMasterAdmin || (!role.managed && canGrantRole(access, catalog, role.key))) + (access.isMasterAdmin || + (!confersBuiltInRole(catalog, role) && canGrantRole(access, catalog, role.key))) ); } diff --git a/src/components/rbac/role-form.tsx b/src/components/rbac/role-form.tsx index 67faf70..91f7861 100644 --- a/src/components/rbac/role-form.tsx +++ b/src/components/rbac/role-form.tsx @@ -15,7 +15,7 @@ import { } from "@/auth/rbac"; import { Field, KeyChip } from "@/components/rbac/fields"; import { useAccess } from "@/components/access"; -import { canGrantPermission, canGrantRole } from "@/components/rbac/delegation"; +import { canGrantPermission, canGrantRole, canInheritFrom } from "@/components/rbac/delegation"; import { PickList } from "@/components/rbac/pick-list"; import { useDraftErrors } from "@/components/rbac/use-draft-errors"; import { Button } from "@/components/ui/button"; @@ -72,23 +72,24 @@ export function RoleForm({ const parentOptions = catalog.roles .filter((entry) => entry.key !== (currentKey ?? draft.key.trim().toLowerCase())) - .filter( - (entry) => canGrantRole(access, catalog, entry.key) || draft.parents.includes(entry.key), - ) + .filter((entry) => canInheritFrom(access, catalog, entry) || draft.parents.includes(entry.key)) .map((entry) => { const cycles = currentKey ? roleParentWouldCycle(catalog, currentKey, entry.key) : false; const wildcard = entry.key === MASTER_ADMIN_ROLE_KEY; const outsideAuthority = !canGrantRole(access, catalog, entry.key); + const fixed = !canInheritFrom(access, catalog, entry); return { key: entry.key, label: entry.name, hint: entry.description ?? undefined, - disabled: cycles || wildcard || outsideAuthority, + disabled: cycles || wildcard || fixed, disabledReason: wildcard ? `${entry.name} holds every permission and is granted only by this deployment's configuration, so no role can inherit from it.` : outsideAuthority ? "This role grants permissions you do not hold." - : `${entry.name} already inherits from this role.`, + : fixed + ? (entry.description ?? undefined) + : `${entry.name} already inherits from this role.`, }; }); diff --git a/src/components/users/user-roles.tsx b/src/components/users/user-roles.tsx index a949afe..c2ef446 100644 --- a/src/components/users/user-roles.tsx +++ b/src/components/users/user-roles.tsx @@ -6,7 +6,7 @@ import { type RbacCatalog, takesHandAssignments } from "@/auth/rbac"; import type { UserRoleAssignment } from "@/auth/users"; import { changeRoleMemberFn } from "@/auth/rbac.functions"; import { useAccess } from "@/components/access"; -import { canAssignRole } from "@/components/rbac/delegation"; +import { canAssignRole, confersBuiltInRole } from "@/components/rbac/delegation"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { @@ -56,7 +56,7 @@ export function UserRoles({ .filter( (role) => takesHandAssignments(role) && - (access.isMasterAdmin || !role.managed) && + (access.isMasterAdmin || !confersBuiltInRole(catalog, role)) && !assigned.some((entry) => entry.key === role.key), ) .sort((a, b) => a.name.localeCompare(b.name)); @@ -89,6 +89,8 @@ export function UserRoles({ {assigned.map((entry) => { const role = roleByKey(entry.key); const assignedAt = formatDate(entry.assignedAt); + const removable = + canWrite && (access.isMasterAdmin || !role || !confersBuiltInRole(catalog, role)); return (