Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -373,7 +377,7 @@ The backend only names the actor; this IdP resolves the actor's own access and r
| `team:<key>:member` | `admin:access` + `people:write`, or the Lead of that team |
| `team:<key>: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.

Expand Down
8 changes: 7 additions & 1 deletion docs/rbac-security-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/auth/mcp-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions src/auth/people-binding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<PeopleRoleChange> = {}) =>
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();
});
7 changes: 7 additions & 0 deletions src/auth/people-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
MASTER_ADMIN_ROLE_KEY,
effectiveRolePermissions,
expandRoleKeys,
inheritedBuiltInRoles,
isManagedPermissionKey,
roleNames,
} from "./rbac";

/**
Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand Down
32 changes: 32 additions & 0 deletions src/auth/rbac-delegation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
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(
Expand Down Expand Up @@ -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) {
Expand Down
39 changes: 39 additions & 0 deletions src/auth/rbac-security.integration.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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]);
Expand Down
26 changes: 20 additions & 6 deletions src/auth/rbac-store.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -35,9 +35,11 @@ import {
MASTER_ASSIGNED_ROLE_KEYS,
takesHandAssignments,
catalogForIdpPermissions,
inheritedBuiltInRoles,
normalizePermissionDraft,
normalizeRoleDraft,
resolveAccess,
roleNames,
validatePermissionDraft,
validateRoleDraft,
withIntrinsicImplications,
Expand Down Expand Up @@ -263,9 +265,12 @@ async function withRbacWriteLock<T>(
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);
Expand Down Expand Up @@ -511,25 +516,34 @@ 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)}.`,
);
}
}

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
Expand All @@ -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)));
Expand Down
Loading
Loading