Applied AI-Accelerated Government Development

Enforce a Closed Role Set

Updated

Intermediate

What you'll learn

~30 min
  • Map the raw role names from `platform.identity.rolesFrom()` onto a closed role set with one resolution order and default deny
  • Wrap every route handler in withPermission(), built on requireSession() from Lesson 3
  • Compare a hierarchy of roles with capability-based permissions and record which your agency chooses
  • Write a contract test that imports every route file, checks that each exported HTTP method carries the policy its wrapper declared, and fails on any route with no decision

A closed set, one order, default deny

Access control fails in two quiet ways: a route nobody decided about, and a user nobody mapped to anything. A closed role set closes both. The set of roles is fixed in code, there is one order in which a user’s roles are resolved to one of them, and anything unmapped is denied.

The reference app uses five example roles. Yours may be different; the pattern is what you keep.

ProblemThe patternWhere your platform lesson lands itYou decide
Who may do whatA closed role set fixed in code: five ordered roles (viewer, operator, manager, admin, superadmin). The alternative is capability-based permissions (a user holds named abilities, with no ladder)Unchanged on every platformWhether your duties form a ladder
Where the raw role names come fromplatform.identity.rolesFrom(claims) returns the provider’s names; this lesson maps them onto the closed set. Entra app roles are one example: values defined on the app registration, arriving in the roles claim34: Entra app roles · 35: claims the IdP puts in its userinfo response · 36: the provider’s claim of record. Directory groups are the other source, with a strategy for the group-overage caseWhich source your directory team can maintain
A user with no recognized roleNo access (the alternative: a read-only default)UnchangedWhether “no role” may ever see data
How you know every route is decidedA contract test that imports every route file and checks each exported method carries the policy declared for it, then walks every role and route pair (the alternative: a review checklist)UnchangedWhether a missed route should fail the build
ℹWhere the roles come from

Lesson 3 stores the strings that platform.identity.rolesFrom(claims) returned, an array, in the session as session.roles. They are the provider’s own names: the local mock provider sends Intake.Operator, and your agency’s provider sends whatever its directory team defined. This lesson maps those strings onto the closed set; it does not read groups.


Plan the change with your agent

Open your workspace agent at the project root with the Lesson 3 session helper (src/lib/auth/session.ts) and your project-memory file (AGENTS.md from Lesson 2) in place, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and ask:

Read our session helper (src/lib/auth/session.ts from Lesson 3) and our project-memory file (AGENTS.md), and plan role-based route permissions that deny access by default unless a route is explicitly marked public. Ask me anything unclear before writing code.

What to check in the plan before you approve

  • src/lib/auth/roles.ts defines the ordered closed set ROLES = ["viewer", "operator", "manager", "admin", "superadmin"], maps raw provider role names through ROLE_CLAIM_MAP, ignores unknown names, picks the highest mapped role, and returns null when nothing matches (no database lookup, group fallback, or default role).
  • src/lib/auth/permissions.ts maps resource:action keys to a minimum Role and checkAccess(role, resource, action) returns false on a null role, unknown role, or unknown key.
  • src/lib/auth/with-permission.ts attaches frozen policy metadata under POLICY = Symbol.for("app.policy") on withPermission(resource, action, handler) and publicRoute(reason, handler), calls requireSession(store), throws SafeError("Forbidden", 403) on denial, and routes every error through fail().

If the agent’s initial plan includes a fallback default role or reads token claims directly instead of session.roles, push back before approving:

Do not fall back to a default viewer role when no claim matches; return null and deny by default.

What you get

SESSION Closed role set: planning it, then asking what the old chain did
  1. Typed in the terminal: claude
  2. Mode:Plan mode
  3. You type in the session: Read our session helper (src/lib/auth/session.ts from Lesson 3) and our project-memory file (AGENTS.md), and plan role-based route permissions that deny access by default unless a route is explicitly marked public. Ask me anything unclear before writing code.
  4. The tool replies: Proposed plan: 1. src/lib/auth/roles.ts: closed ROLES tuple, ROLE_CLAIM_MAP for raw provider role strings, and resolveRole(names) returning the highest mapped role or null. 2. src/lib/auth/permissions.ts: PERMISSIONS matrix of minimum role per resource:action and checkAccess() with default deny. 3. src/lib/auth/with-permission.ts: withPermission() and publicRoute() attaching frozen metadata under Symbol.for("app.policy"), calling requireSession(store), and routing errors through fail(). Should a signed-in user with no matching role claim fall back to viewer or be denied?
  5. You type in the session: Do not fall back to a default viewer role when no claim matches; return null and deny by default. Build it.
  6. The tool replies: I created: - src/lib/auth/roles.ts: ROLES, ROLE_CLAIM_MAP, resolveRole(names). It maps each raw name, drops names it does not know, and returns the highest. No match returns null. - src/lib/auth/permissions.ts: PERMISSIONS (minimum role per resource:action) and checkAccess(), which returns false for a null role, an unknown key, or an unknown role. - src/lib/auth/with-permission.ts: requireSession(store), then resolveRole, then checkAccess, then the handler. Denial is a SafeError 403 passed through fail(). I used the strings Intake.Viewer through Intake.SuperAdmin as placeholders. They must match the role names your provider actually sends; the local mock sends Intake.Operator.
  7. You type in the session: An older version of this layer fell back to a database lookup, then directory groups, then a default viewer role. Why did you leave those out?
  8. The tool replies: Each fallback widens who gets in. - A default viewer role means a user whose mapping is broken still reads data. Default deny turns that into a visible 403 that someone has to fix. - A database role beside the provider's role names gives you two sources of truth that can disagree. If you want database-held roles, make that the only source instead of a fallback. - A groups step is only safe with an overage plan. Some providers put an overage indicator in the token instead of the list when a user belongs to too many groups, and you would need a follow-up directory call to resolve it. That call is specific to your provider and nothing in your notes names it, so I did not write it. If your directory team can only maintain groups, tell me and I will add a groups source behind that caveat, still with default deny.
  9. You type in the session: Keep it as is. Now write the test that proves every route has a decision.
  10. The tool replies: Created tests/contract/rbac.test.ts and src/lib/auth/route-policy.ts. The policy file maps every route handler (for example, GET /api/incidents) to its resource and action. The test imports every route.ts under src/app and checks each exported member named GET, HEAD, POST, PUT, PATCH, DELETE or OPTIONS. Each one must carry the POLICY metadata that withPermission() or publicRoute() attaches, and that metadata must equal the ROUTE_POLICY entry for the method and path. A method with no metadata fails, a method with no entry fails, and an entry whose route no longer exports that method fails. Then it walks every role against every protected entry and checks the decision against tests/contract/expected-decisions.json, which is reviewed like code. The default-deny cases are separate tests: a null role, a role string that is not in the set, an unknown resource, and an unknown action. Two negative cases plant a raw HEAD handler and a wrapper whose resource disagrees with the policy file, and expect both to be reported.
  11. You type in the session: Add a new route file that exports a raw HEAD handler, with no wrapper and no policy entry, and run the test.
  12. The tool replies: I added src/app/api/scratch/route.ts with export async function HEAD() { return new Response(null) }, then ran the test. 1 failed: HEAD /api/scratch is exported but carries no policy. Wrap it in withPermission() or publicRoute(). I then wrapped it in withPermission("incidents", "read", ...) without adding a ROUTE_POLICY entry and it failed again: HEAD /api/scratch has no entry in ROUTE_POLICY. I deleted the scratch file and reran: all passed.

Illustrative session; exact output varies by tool and agency configuration.


Resolve once, in one order

Lesson 3 put the raw names that rolesFrom returned in the session as session.roles. Resolve it at request time rather than at sign-in, so a mapping change applies to sessions that are already open.

REFERENCE CODE src/lib/auth/roles.ts: closed role set and claim-to-role resolution open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
src/lib/auth/roles.ts
export const ROLES = ["viewer", "operator", "manager", "admin", "superadmin"] as const;
export type Role = (typeof ROLES)[number];
// Keys are the raw names your provider sends, as platform.identity.rolesFrom() returns them.
// With Entra ID they are the app-role values defined on the app registration.
export const ROLE_CLAIM_MAP: Record<string, Role> = {
"Intake.Viewer": "viewer",
"Intake.Operator": "operator",
"Intake.Manager": "manager",
"Intake.Admin": "admin",
"Intake.SuperAdmin": "superadmin",
};
export const levelOf = (r: Role) => ROLES.indexOf(r);
// One order: map, ignore the unknown, take the highest. No match is null, not "viewer".
export function resolveRole(names: readonly string[]): Role | null {
let best: Role | null = null;
for (const n of names) {
const r = ROLE_CLAIM_MAP[n];
if (r && (best === null || levelOf(r) > levelOf(best))) best = r;
}
return best;
}

The old design had a four-step chain: token claim, then a database row, then group membership, then a default viewer. Only the first step survives here. The other three were each a way to grant access when the token said nothing, which is the case you most want to see fail.

If your directory team maintains groups instead

Group names such as App-Platform-Operators can feed the same map, with one caveat you must design for. A token lists a user’s groups only up to a limit; past it, some providers (Entra ID is one) send an overage indicator and expect a follow-up call to the directory. Decide before you build what happens then: the safe answer is to deny and alert, which is what resolveRole does with an empty list. Do not add a step that falls through to a default role.


The permission check

REFERENCE CODE src/lib/auth/permissions.ts: minimum-role permission matrix and default-deny checkAccess() open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
src/lib/auth/permissions.ts
import { type Role, ROLES, levelOf } from "./roles";
export type Action = "read" | "create" | "update" | "delete" | "approve" | "export";
// Value = the MINIMUM role. Add a feature's keys here (Lesson 6's registration ledger).
export const PERMISSIONS: Record<string, Role> = {
"incidents:read": "viewer",
"incidents:create": "operator",
"incidents:update": "operator",
"incidents:delete": "admin",
"incidents:approve": "manager",
"incidents:export": "manager",
"users:read": "admin",
"users:update": "admin",
"audit-log:read": "admin",
"audit-log:export": "superadmin",
};
export function checkAccess(role: Role | null, resource: string, action: Action): boolean {
if (role === null || !ROLES.includes(role)) return false;
const min = PERMISSIONS[`${resource}:${action}`];
if (min === undefined) return false; // unknown key: default deny
return levelOf(role) >= levelOf(min);
}

Every denial path returns false before any comparison happens. The comparison runs only for a known role against a known key.


withPermission() on top of requireSession()

requireSession() from Lesson 3 proves who is calling and throws a SafeError 401 if nobody is. withPermission() adds what they may do. The fail() helper and SafeError live in @/lib/response, which Lesson 7 builds in full; here you need only that fail(route, err) turns a SafeError into its status and message and turns anything else into a generic 500.

REFERENCE CODE src/lib/auth/with-permission.ts: route wrappers attaching frozen policy metadata open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
src/lib/auth/with-permission.ts
import type { NextRequest } from "next/server";
import { store } from "@/lib/auth/store";
import { SafeError, fail } from "@/lib/response";
import { requireSession } from "./session";
import { resolveRole, type Role } from "./roles";
import { checkAccess, type Action } from "./permissions";
import type { RoutePolicy } from "./route-policy";
type AppSession = Awaited<ReturnType<typeof requireSession>> & { role: Role };
// Metadata key. Symbol.for gives the same symbol to the app and to the contract test.
export const POLICY = Symbol.for("app.policy");
// Non-enumerable, read-only, frozen: it cannot be copied by a spread or overwritten by accident.
function bind<F extends (...args: never[]) => unknown>(wrapped: F, policy: RoutePolicy): F {
Object.defineProperty(wrapped, POLICY, { value: Object.freeze({ ...policy }) });
return wrapped;
}
export function policyOf(handler: unknown): unknown {
return typeof handler === "function" ? (handler as unknown as Record<symbol, unknown>)[POLICY] : undefined;
}
export function withPermission<C = unknown>(
resource: string,
action: Action,
handler: (req: NextRequest, session: AppSession, ctx: C) => Promise<Response>,
) {
const wrapped = async (req: NextRequest, ctx: C): Promise<Response> => {
try {
const s = await requireSession(store); // 401 if no valid session
const role = resolveRole(s.roles);
if (!checkAccess(role, resource, action)) throw new SafeError("Forbidden", 403);
return await handler(req, { ...s, role: role! }, ctx);
} catch (err) {
return fail(`${resource}:${action}`, err);
}
};
return bind(wrapped, { resource, action });
}
// The one explicit way to leave a method open. The reason is written down and must match ROUTE_POLICY.
export function publicRoute<C = unknown>(
reason: string,
handler: (req: NextRequest, ctx: C) => Promise<Response>,
) {
if (!reason.trim()) throw new Error("publicRoute() needs a reason");
const wrapped = async (req: NextRequest, ctx: C): Promise<Response> => {
try {
return await handler(req, ctx);
} catch (err) {
return fail("public", err);
}
};
return bind(wrapped, { public: true, reason });
}

Here is a reference example of how your agent wraps a protected route handler:

src/app/api/incidents/route.ts
import { withPermission } from "@/lib/auth/with-permission";
import { listResponse } from "@/lib/response";
export const GET = withPermission("incidents", "read", async (req) => {
// ... query, then:
return listResponse([], { page: 1, pageSize: 25, total: 0 });
});

Here is the reference pattern for a route that is open on purpose, declaring its reason:

src/app/api/health/route.ts
import { publicRoute } from "@/lib/auth/with-permission";
export const GET = publicRoute("liveness probe, returns no data", async () => new Response("ok"));
⚠proxy.ts is not the place for this

Do not put role checks in proxy.ts. It does coarse routing, and Server Functions are POST requests to the page route, so a matcher exclusion skips them. Every route handler and Server Function checks for itself, which is what withPermission() is for.

The client side is cosmetic

The page can hide a button the user may not use, but the server decides. In this reference pattern, your agent computes what the user may do on the server and passes it down as plain props:

// src/app/(protected)/incidents/page.tsx (server component)
const role = resolveRole((await requireSession(store)).roles);
const can = { approve: checkAccess(role, "incidents", "approve") };
return <IncidentsView can={can} />;

No client library is needed, and nothing on the client is trusted.


The alternative: capabilities instead of a ladder

If your duties do not stack (an auditor who reads logs but never edits cases, a records officer who exports but never approves), a ladder of roles forces awkward compromises. Capability-based permissions fit better: the role names the provider sends are the capabilities, and the check is set membership (reference snippet shown):

// capability form: the raw names ARE the capabilities
const CAPABILITIES = new Set(["incidents.read", "incidents.approve", "audit.read" /* ... */]);
export const can = (names: readonly string[], cap: string) =>
CAPABILITIES.has(cap) && names.includes(cap);

The trade is real. You lose the one-line “manager can do what operator can do” and gain exactness, and you carry a longer list in the directory. Default deny still applies: a capability not in the set is false. Whichever you pick, write it and its reason in docs/adr/.


Prove it

The contract test binds the policy file to the code. It imports every route file, so a handler cannot hide from discovery by how it is written (export const, a synchronous export function, a re-export). For every exported HTTP method it checks that the function carries the POLICY metadata a wrapper attached, and that the metadata equals the policy file’s entry for that method and path. It then makes every role face every protected route and compares the result to a reviewed expectation file, and checks that the denial paths are denials. Here is the reference policy table your agent writes in src/lib/auth/route-policy.ts:

src/lib/auth/route-policy.ts
import type { Action } from "./permissions";
export type RoutePolicy =
| { resource: string; action: Action }
| { public: true; reason: string };
// Key: "<METHOD> <URL path>" (route groups such as (protected) are not part of the URL).
// One entry per exported method.
export const ROUTE_POLICY: Record<string, RoutePolicy> = {
"GET /api/incidents": { resource: "incidents", action: "read" },
"POST /api/incidents": { resource: "incidents", action: "create" },
"GET /api/health": { public: true, reason: "liveness probe, returns no data" },
};
REFERENCE TEST tests/contract/rbac.test.ts: contract test binding every exported route method to ROUTE_POLICY open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
tests/contract/rbac.test.ts
import { isDeepStrictEqual } from "node:util";
import { describe, it, expect } from "vitest";
import { ROLES } from "@/lib/auth/roles";
import { checkAccess, type Action } from "@/lib/auth/permissions";
import { ROUTE_POLICY, type RoutePolicy } from "@/lib/auth/route-policy";
import { policyOf, withPermission, publicRoute } from "@/lib/auth/with-permission";
import expected from "./expected-decisions.json";
const METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] as const;
type RouteModule = Record<string, unknown>;
// Every route file Next can serve. Vite resolves the glob at test time, so a new file is picked up with no list to edit.
const files = import.meta.glob("/src/app/**/route.{ts,tsx,js,jsx,mjs}");
export function routePath(file: string): string {
const segments = file
.replace(/^\/src\/app/, "")
.replace(/\/route\.[a-z]+$/, "")
.split("/")
.filter((seg) => seg !== "" && !/^\(.*\)$/.test(seg)); // route groups are not in the URL
return "/" + segments.join("/");
}
// Every problem with one route module, as text. An empty list is a pass.
export function problems(mod: RouteModule, path: string, policy: Record<string, RoutePolicy> = ROUTE_POLICY): string[] {
const out: string[] = [];
for (const m of METHODS) {
if (!(m in mod)) continue; // covers const, function, async function and re-exports
const key = `${m} ${path}`;
const attached = policyOf(mod[m]);
if (attached === undefined) {
out.push(`${key} is exported but carries no policy. Wrap it in withPermission() or publicRoute().`);
continue;
}
const declared = policy[key];
if (declared === undefined) out.push(`${key} has no entry in ROUTE_POLICY. Every route needs a decision.`);
else if (!isDeepStrictEqual(attached, declared)) {
out.push(`${key} declares ${JSON.stringify(attached)} in code but ${JSON.stringify(declared)} in ROUTE_POLICY.`);
}
}
return out;
}
const loaded = await Promise.all(
Object.entries(files).map(async ([file, load]) => ({ path: routePath(file), mod: (await load()) as RouteModule })),
);
const found = loaded.flatMap(({ path, mod }) => METHODS.filter((m) => m in mod).map((m) => `${m} ${path}`)).sort();
describe("every route has a decision, bound to the code", () => {
it("finds the route files (an empty glob would pass everything)", () => {
expect(loaded.length).toBeGreaterThan(0);
});
it.each(loaded.map((l) => [l.path, l] as const))("%s: every exported method carries the policy ROUTE_POLICY lists", (_path, l) => {
expect(problems(l.mod, l.path)).toEqual([]);
});
it("has no policy entry for a method that no route exports", () => {
expect(Object.keys(ROUTE_POLICY).filter((k) => !found.includes(k))).toEqual([]);
});
it("gives every public route a written reason", () => {
for (const [key, p] of Object.entries(ROUTE_POLICY)) {
if ("public" in p) expect(p.reason.trim(), key).not.toBe("");
}
});
});
describe("the check itself fails when it should", () => {
const ok = async () => new Response(null);
it("fails a raw exported HEAD handler", () => {
expect(problems({ HEAD: ok }, "/api/incidents")).toEqual([
"HEAD /api/incidents is exported but carries no policy. Wrap it in withPermission() or publicRoute().",
]);
});
it("fails a wrapper whose resource disagrees with ROUTE_POLICY", () => {
const mod = { GET: withPermission("incidents", "export", ok) }; // the policy file says incidents:read
expect(problems(mod, "/api/incidents")).toHaveLength(1);
});
it("fails a public wrapper where ROUTE_POLICY says protected", () => {
expect(problems({ GET: publicRoute("no reason to be open", ok) }, "/api/incidents")).toHaveLength(1);
});
it("passes a correctly wrapped method", () => {
expect(problems({ GET: withPermission("incidents", "read", ok) }, "/api/incidents")).toEqual([]);
});
it("refuses a public route with no reason", () => {
expect(() => publicRoute(" ", ok)).toThrow();
});
});
describe("every role x route pair is decided", () => {
for (const [key, p] of Object.entries(ROUTE_POLICY)) {
if ("public" in p) continue; // public routes have no role decision
for (const role of ROLES) {
it(`${role} on ${key}`, () => {
const got = checkAccess(role, p.resource, p.action);
expect(typeof got).toBe("boolean");
expect((expected as Record<string, Record<string, boolean>>)[key]?.[role]).toBe(got);
});
}
}
});
describe("default deny", () => {
it("denies no role", () => expect(checkAccess(null, "incidents", "read")).toBe(false));
it("denies a role outside the set", () => expect(checkAccess("root" as never, "incidents", "read")).toBe(false));
it("denies an unknown resource", () => expect(checkAccess("superadmin", "nope", "read")).toBe(false));
it("denies an unknown action", () => expect(checkAccess("superadmin", "incidents", "teleport" as Action)).toBe(false));
});

expected-decisions.json is the table a reviewer reads: one object per protected route key, one boolean per role. A change to the permission matrix changes it, so the diff in a pull request shows exactly who gained or lost access.

Route modules are imported for real, so they must be importable in the test environment: create database pools and clients lazily inside handlers, or mock them in the Vitest setup file. A route file that throws on import fails this test, which is the safe direction.

Plant two faults against the real tree, one at a time. Add src/app/api/scratch/route.ts with export async function HEAD() { return new Response(null); }: the first group fails naming HEAD /api/scratch. Change an existing route to withPermission("incidents", "export", ...) while the policy file still says read: it fails showing both policies. Revert each afterward. The second group runs the same two plants against in-memory modules on every run, so the check that catches them is itself checked.

ℹFail-closed by design

The metadata is read from the exported function. A handler wrapped again by something that returns a new function (a cache or logging decorator placed outside withPermission()) loses it and fails the test; put such decorators inside the wrapper. Next serves only the HTTP-method names this test checks, so any other export (dynamic, revalidate) is configuration and is not a route.


KNOWLEDGE CHECK

A user signs in with a role name your map does not contain, and is in a directory group that sounds like an operator group. What does the closed set do?

KNOWLEDGE CHECK

Your team adds a route file that exports a raw HEAD handler, with no withPermission() wrapper. What should happen, and why is that a contract test rather than a code review item?


Key takeaway

Fix the roles in code, resolve the raw names from platform.identity.rolesFrom() by one order (map, ignore the unknown, take the highest), and deny everything that does not resolve. Build withPermission() on requireSession(), keep proxy.ts out of authorization, and let a contract test import every route file and check that each exported HTTP method carries the policy ROUTE_POLICY lists for it, then enumerate every role and route pair, so a route nobody decided about, or one whose code disagrees with the policy file, fails the build. Five roles are the reference app’s choice and capabilities are a legitimate one; the decision and its reason go in docs/adr/.

LEADERSHIP DECISION
Which role set the agency fixes, and who approves a change to ROLE_CLAIM_MAP or ROUTE_POLICY.
PRACTITIONER ACTION
Run the contract test, add a scratch route to watch it fail, then write the ADR for your role set.
SUCCESS MEASURE
Audit finding avoided: zero routes without a recorded access decision at assessment.

Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided

Search lessons