diff --git a/docs/ROLE_ADOPTION_PLAN.md b/docs/ROLE_ADOPTION_PLAN.md index 26dee77..7000308 100644 --- a/docs/ROLE_ADOPTION_PLAN.md +++ b/docs/ROLE_ADOPTION_PLAN.md @@ -85,7 +85,16 @@ The lockout-safe order proven on retiregolden.org, transplanted: - [x] Delete the env vars from the Worker configuration and update `SUPPORT_COMPOSITION.md`'s staff section to role-only. -## Phase 5 — the shared admin surface (GATED) +## Phase 5 — the shared admin surface ✓ (2026-07-31) + +**Executed:** `@pegma/authorization-admin@0.4.0` (extracted upstream from +both hosts) composes the surface: `Admin` mapped in policy version +`pegma.dev-policy-2` to the four `admin.*` permissions; one-time +`PEGMA_ADMIN_BOOTSTRAP_PRINCIPALS` seed via the package helper (fresh +opaque ids per attempt — lifecycle history is the already-seeded signal); +`/api/admin/*` + `/staff/roles` gated on `Admin`, with the +last-administrator guard live from the first request and the by-role +holder index at `role-holder-index.v1`. Original gating record follows. Both hosts now want the same role-management surface (lookup → grants view → audited assign/revoke → history). Per the ecosystem's diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index fff7bd1..5cfd842 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -13,9 +13,10 @@ Exact published versions: - `@pegma/support-desk-contracts@0.1.0` - `@pegma/support-desk-core@0.1.0` - `@pegma/support-desk-templates@0.1.0` -- `@pegma/authorization-core@0.3.0` (AccessContext resolution) -- `@pegma/authorization-policy@0.3.0` (PolicyDocumentV1 schema validation) -- `@pegma/authorization-storage@0.3.0` (D1-backed role store) +- `@pegma/authorization-admin@0.4.0` (role administration service) +- `@pegma/authorization-core@0.4.0` (AccessContext resolution) +- `@pegma/authorization-policy@0.4.0` (PolicyDocumentV1 schema validation) +- `@pegma/authorization-storage@0.4.0` (D1-backed role store) Peers already present on the host: `@pegma/storage-core@0.4.0`, `@pegma/storage-cloudflare-d1@0.4.0`, `@pegma/sessions@0.1.0`, @@ -33,6 +34,7 @@ collection name, not by sharing Identity mail cursors or session rows: | Ticket numbers | `support-desk.ticket-numbers.v1` | | Queue projection | `support-desk.queue-index.v1` | | Host maintenance cursors | `pegma-dev-support-maintenance` | +| Role holder index (by-role guard) | `role-holder-index.v1` | Identity keeps its own collections and `pegma-dev-maintenance` cursors. The two never share a cursor key. @@ -157,6 +159,7 @@ Durable rate-limit policies (separate from Identity): | `/feedback/ticket/?id=…` | Customer read + reply | | `/staff/support` | Staff queue (Support role holders) | | `/staff/support/ticket/?id=…` | Staff ticket detail, compose, lifecycle | +| `/staff/roles` | Role administration (Admin role holders) | ## Maintenance and health diff --git a/package-lock.json b/package-lock.json index 04e907f..4059a89 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,10 +10,11 @@ "dependencies": { "@modelcontextprotocol/server": "^2.0.0", "@pegma/audit": "0.2.0", - "@pegma/authorization-core": "0.3.0", - "@pegma/authorization-identity": "0.3.0", - "@pegma/authorization-policy": "0.3.0", - "@pegma/authorization-storage": "0.3.0", + "@pegma/authorization-admin": "0.4.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/authorization-identity": "0.4.0", + "@pegma/authorization-policy": "0.4.0", + "@pegma/authorization-storage": "0.4.0", "@pegma/health": "^0.2.0", "@pegma/identity": "0.1.2", "@pegma/logger-cloudflare": "^0.1.1", @@ -3056,58 +3057,71 @@ "node": ">=22" } }, + "node_modules/@pegma/authorization-admin": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-admin/-/authorization-admin-0.4.0.tgz", + "integrity": "sha512-pnEJ2bI29jP9lnE3lpTnpYUWfjqSuZW/gqq06KPn1+T/bMwhL7b7ff9Ub8wNPaweXZqAUTVq/3YoegmR8ca63Q==", + "license": "MIT", + "dependencies": { + "@pegma/authorization-contracts": "0.4.0", + "@pegma/authorization-storage": "0.4.0" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/@pegma/authorization-contracts": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@pegma/authorization-contracts/-/authorization-contracts-0.3.0.tgz", - "integrity": "sha512-H98/qXSt2iXZJi9U8peXZrRJpGHqNUcfhRAOZpBBCEZu9UFAj5SLhgo6ruiy9Zj0MM+VKXEZouWSV3tGa4HgIA==", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-contracts/-/authorization-contracts-0.4.0.tgz", + "integrity": "sha512-7o+oN/CyBGcDb3rUDzJpLSi7VYS/hAk2h0LfEEPpQmT46Mk/3xLwNrXS6WPuVFT2UMdJNeExgFu7Og6pYbFMMQ==", "license": "MIT", "engines": { "node": ">=22" } }, "node_modules/@pegma/authorization-core": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@pegma/authorization-core/-/authorization-core-0.3.0.tgz", - "integrity": "sha512-xWqg0bYKlmF8npAPytFKDeb59kELmb4CfJndG1EH8/NoLFnKKh+YEAWNkn/VXZbrZjCLAY9qebWbmjuRTVXVZg==", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-core/-/authorization-core-0.4.0.tgz", + "integrity": "sha512-GkagQwyDfKokB2Nm9EAo6cvKB8c90VN6Or6IdaWeMwCeuseOxDZ8ccxKqccW9YorByE6rHhr2nbxjsNWorZTHQ==", "license": "MIT", "dependencies": { - "@pegma/authorization-contracts": "0.3.0" + "@pegma/authorization-contracts": "0.4.0" }, "engines": { "node": ">=22" } }, "node_modules/@pegma/authorization-identity": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@pegma/authorization-identity/-/authorization-identity-0.3.0.tgz", - "integrity": "sha512-GCBXYG75i5c0PxaSo3D6mVah2GhfmXG6KU/jZ0OxKYqY/FzpEHSvuKi03q7JHSJ4VDRNQM31vEgvopIfzdG/bw==", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-identity/-/authorization-identity-0.4.0.tgz", + "integrity": "sha512-u1q8gwgmUyhlUvl0e/n58jodU9Z0oE29yalsPtyUPZpsC6+4p2zQ8bgd9ACixccPfUqhgfp817b17FrjzkFyWA==", "license": "MIT", "dependencies": { - "@pegma/authorization-contracts": "0.3.0" + "@pegma/authorization-contracts": "0.4.0" }, "engines": { "node": ">=22" } }, "node_modules/@pegma/authorization-policy": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@pegma/authorization-policy/-/authorization-policy-0.3.0.tgz", - "integrity": "sha512-+mb3Zuzm2FTnYFPkhs49DTCRsyFmGLlbH6EGLEVdNQPk30KU7SCP0jnUjQD/2DMZy4ACxJRTpHymu5L/M7dmiw==", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-policy/-/authorization-policy-0.4.0.tgz", + "integrity": "sha512-mVU0zLpOgE7hB0UsqPyIl4kytxpuEklq9y4lsHbeBZVnMmxg1tgFmQF0R0WST69MqtDcALepoLOHhe/CBAE4jA==", "license": "MIT", "dependencies": { - "@pegma/authorization-contracts": "0.3.0" + "@pegma/authorization-contracts": "0.4.0" }, "engines": { "node": ">=22" } }, "node_modules/@pegma/authorization-storage": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@pegma/authorization-storage/-/authorization-storage-0.3.0.tgz", - "integrity": "sha512-EEdAwpSP+zSpUTOGcr0r0uyeK/XXhumoUPKgmrtusA1pX7QZgwGN3iuu62v6PpRdvsTgHXQaB0CWHmk5MpIGKw==", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-storage/-/authorization-storage-0.4.0.tgz", + "integrity": "sha512-nha0Ftd7DYKYajUthYR+rTYdJxy1Gsff0aclriEFmdN6NmJaEPW3ZIsg7OY79MUUZ5HpoXiPU7A1Z35QrFUWOw==", "license": "MIT", "dependencies": { - "@pegma/authorization-contracts": "0.3.0", + "@pegma/authorization-contracts": "0.4.0", "@pegma/storage-core": "0.4.0" }, "engines": { diff --git a/package.json b/package.json index 35e4197..770d19d 100644 --- a/package.json +++ b/package.json @@ -20,10 +20,11 @@ "dependencies": { "@modelcontextprotocol/server": "^2.0.0", "@pegma/audit": "0.2.0", - "@pegma/authorization-core": "0.3.0", - "@pegma/authorization-identity": "0.3.0", - "@pegma/authorization-policy": "0.3.0", - "@pegma/authorization-storage": "0.3.0", + "@pegma/authorization-admin": "0.4.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/authorization-identity": "0.4.0", + "@pegma/authorization-policy": "0.4.0", + "@pegma/authorization-storage": "0.4.0", "@pegma/health": "^0.2.0", "@pegma/identity": "0.1.2", "@pegma/logger-cloudflare": "^0.1.1", diff --git a/public/staff-roles.js b/public/staff-roles.js new file mode 100644 index 0000000..968f9c7 --- /dev/null +++ b/public/staff-roles.js @@ -0,0 +1,226 @@ +const statusNode = document.querySelector('#roles-status'); +const signedOut = document.querySelector('#roles-signed-out'); +const forbidden = document.querySelector('#roles-forbidden'); +const panel = document.querySelector('#roles-panel'); +const bootstrapWarning = document.querySelector('#bootstrap-warning'); +const lookupForm = document.querySelector('#lookup-form'); +const principalInput = document.querySelector('#lookup-principal'); +const principalCard = document.querySelector('#principal-card'); +const principalEmail = document.querySelector('#principal-email'); +const principalMeta = document.querySelector('#principal-meta'); +const roleList = document.querySelector('#role-list'); +const assignForm = document.querySelector('#assign-form'); +const assignRole = document.querySelector('#assign-role'); +const historyList = document.querySelector('#history-list'); + +let csrfToken = ''; +let currentPrincipal = ''; + +function showStatus(message, isError = false) { + statusNode.textContent = message; + statusNode.dataset.tone = isError ? 'error' : 'neutral'; +} + +function hideAll() { + signedOut.hidden = true; + forbidden.hidden = true; + panel.hidden = true; +} + +async function api(path, init = {}) { + const headers = new Headers(init.headers); + if (init.body !== undefined) { + headers.set('Content-Type', 'application/json'); + } + if (csrfToken !== '') { + headers.set('X-Pegma-CSRF', csrfToken); + } + const response = await fetch(path, { + ...init, + headers, + credentials: 'same-origin', + }); + const body = await response.json(); + if (!response.ok) { + const error = new Error( + typeof body.error === 'string' ? body.error : 'request_failed', + ); + error.status = response.status; + throw error; + } + return body; +} + +const MUTATION_ERRORS = { + last_administrator: + 'Refused: that is the last active administrator. Grant Admin to someone else first.', + system_managed: 'Refused: that assignment is system-managed.', + duplicate_role: 'That principal already holds the role.', + already_revoked: 'That assignment is already revoked.', + rate_limited: 'Rate limited — wait a moment and try again.', +}; + +function describeActor(actor) { + return actor.kind === 'system' + ? `system:${actor.systemId}` + : actor.principalId; +} + +function renderRoles(roles) { + roleList.replaceChildren(); + if (roles.length === 0) { + const empty = document.createElement('li'); + empty.textContent = 'No active roles.'; + roleList.append(empty); + return; + } + for (const role of roles) { + const li = document.createElement('li'); + const label = document.createElement('strong'); + label.textContent = role.role; + const meta = document.createElement('span'); + meta.className = 'form-note'; + meta.textContent = ` granted by ${describeActor(role.grantedBy)} · ${ + role.managedBy === 'system' ? 'system-managed' : 'human-managed' + } `; + li.append(label, meta); + if (role.managedBy !== 'system') { + const revoke = document.createElement('button'); + revoke.type = 'button'; + revoke.className = 'secondary-button'; + revoke.textContent = 'Revoke'; + revoke.addEventListener('click', async () => { + if ( + !window.confirm( + `Revoke ${role.role} from this principal? The audited record stays.`, + ) + ) { + return; + } + try { + const result = await api( + `/api/admin/assignments/${encodeURIComponent(role.assignmentId)}`, + { method: 'DELETE' }, + ); + showStatus( + result.compensated + ? 'Revoked — the guard restored the principal to keep an administrator.' + : 'Revoked.', + ); + await loadPrincipal(currentPrincipal); + } catch (error) { + showStatus( + MUTATION_ERRORS[error.message] ?? `Revoke failed (${error.message}).`, + true, + ); + } + }); + li.append(revoke); + } + roleList.append(li); + } +} + +function renderHistory(events) { + historyList.replaceChildren(); + if (events.length === 0) { + const empty = document.createElement('li'); + empty.textContent = 'No role history.'; + historyList.append(empty); + return; + } + for (const event of events) { + const li = document.createElement('li'); + const when = new Date(event.atEpochMs).toISOString(); + li.textContent = `${when} — ${event.kind} ${event.role} by ${describeActor( + event.actor, + )}${event.reason ? ` (${event.reason})` : ''}`; + historyList.append(li); + } +} + +async function loadPrincipal(principalId) { + const [detail, history] = await Promise.all([ + api(`/api/admin/principals/${encodeURIComponent(principalId)}`), + api(`/api/admin/principals/${encodeURIComponent(principalId)}/history`), + ]); + currentPrincipal = principalId; + principalEmail.textContent = detail.principal.email; + principalMeta.textContent = `${detail.principal.principalId} · ${detail.principal.status} · created ${detail.principal.createdAt}`; + renderRoles(detail.roles); + renderHistory(history.events); + principalCard.hidden = false; +} + +lookupForm.addEventListener('submit', async (event) => { + event.preventDefault(); + const principalId = principalInput.value.trim(); + if (principalId === '') { + return; + } + showStatus('Loading principal…'); + try { + await loadPrincipal(principalId); + showStatus('Ready.'); + } catch (error) { + principalCard.hidden = true; + showStatus( + error.status === 404 + ? 'No account with that principal id.' + : `Lookup failed (${error.message}).`, + true, + ); + } +}); + +assignForm.addEventListener('submit', async (event) => { + event.preventDefault(); + if (currentPrincipal === '') { + return; + } + const role = assignRole.value; + if ( + role === 'Admin' && + !window.confirm('Grant the Admin role? Admins can change all role assignments.') + ) { + return; + } + try { + await api( + `/api/admin/principals/${encodeURIComponent(currentPrincipal)}/roles`, + { method: 'POST', body: JSON.stringify({ role }) }, + ); + showStatus(`Assigned ${role}.`); + await loadPrincipal(currentPrincipal); + } catch (error) { + showStatus( + MUTATION_ERRORS[error.message] ?? `Assign failed (${error.message}).`, + true, + ); + } +}); + +async function boot() { + hideAll(); + try { + const state = await api('/api/admin/state'); + csrfToken = state.csrfToken; + bootstrapWarning.hidden = state.bootstrapArmed !== true; + panel.hidden = false; + showStatus('Ready.'); + } catch (error) { + if (error.status === 401) { + signedOut.hidden = false; + showStatus('Signed out.'); + return; + } + if (error.status === 403) { + forbidden.hidden = false; + showStatus('No admin access.'); + return; + } + showStatus(`Admin surface unavailable (${error.message}).`, true); + } +} + +boot(); diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index 53d42d1..ba6ba40 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -19,7 +19,7 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ '@pegma/sessions@0.2.0', '@pegma/mail@0.1.1', '@pegma/rate-limit@0.2.0', - '@pegma/authorization-identity@0.3.0', + '@pegma/authorization-identity@0.4.0', '@pegma/storage-core@0.4.0', '@pegma/storage-cloudflare-d1@0.4.1', '@pegma/spine@0.1.1', diff --git a/src/pages/staff/roles.astro b/src/pages/staff/roles.astro new file mode 100644 index 0000000..62aa43a --- /dev/null +++ b/src/pages/staff/roles.astro @@ -0,0 +1,99 @@ +--- +import Base from '../../layouts/Base.astro'; +--- + + +
+

Staff · Role administration

+

Roles

+

+ Look up a principal, review and change stored role assignments, and read + the audited history. Access requires the stored Admin role — this + administers pegma.dev only. +

+
+ +
+ Checking admin access… +
+ + + + + + + + + + + diff --git a/worker/src/admin-api.test.ts b/worker/src/admin-api.test.ts new file mode 100644 index 0000000..9e4d493 --- /dev/null +++ b/worker/src/admin-api.test.ts @@ -0,0 +1,320 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createMemoryStore } from '@pegma/storage-core'; +import { createSessionStore } from '@pegma/sessions'; +import { fixedClock, type Logger, type PrincipalId } from '@pegma/spine'; +import { describe, expect, it, vi } from 'vitest'; +import { createAdminApi } from './admin-api'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import type { + IdentityPort, + IdentityUser, + VerifiedIdentityClaims, +} from './identity-contracts'; +import { createRoleHolderIndex } from './role-holder-index'; +import { ADMIN_ROLE, SUPPORT_ROLE } from './support-access'; +import { + createAdminMutationLimiter, + createSupportRuntime, +} from './support-desk'; + +const admin = 'principal-admin' as PrincipalId; +const secondAdmin = 'principal-admin-2' as PrincipalId; +const member = 'principal-member' as PrincipalId; +const clock = fixedClock('2026-07-31T12:00:00.000Z'); +const logger: Logger = { log: vi.fn() }; + +function userFor(principalId: PrincipalId, email: string): IdentityUser { + return { + principalId, + email, + emailVerified: true, + status: 'active', + createdAt: '2026-07-29T00:00:00.000Z', + updatedAt: '2026-07-29T00:00:00.000Z', + }; +} + +function identityFor( + users: ReadonlyMap, +): IdentityPort { + return { + claimsFor: vi.fn(async (principalId: PrincipalId) => { + const user = users.get(principalId); + if (user === undefined) { + throw Object.assign(new Error('not found'), { code: 'not_found' }); + } + return { + issuer: IDENTITY_ISSUER, + subject: principalId, + emailVerified: true, + } satisfies VerifiedIdentityClaims; + }), + getUser: vi.fn( + async (principalId: PrincipalId) => users.get(principalId) ?? null, + ), + beginPasskeyRegistration: vi.fn(), + finishPasskeyRegistration: vi.fn(), + beginPasskeyAuthentication: vi.fn(), + finishPasskeyAuthentication: vi.fn(), + listPasskeys: vi.fn(async () => []), + removePasskey: vi.fn(async () => true), + }; +} + +let sessionSerial = 0; + +async function sessionCookie( + sessions: ReturnType, + principalId: PrincipalId, + csrfToken = 'c'.repeat(43), +): Promise<{ cookie: string; csrfToken: string }> { + sessionSerial += 1; + const sessionId = `${String(sessionSerial).padStart(2, '0')}${'a'.repeat(41)}`; + await sessions.create(sessionId, { + principalId, + data: JSON.stringify({ + version: 1, + csrfToken, + issuer: IDENTITY_ISSUER, + subject: principalId, + }), + }); + return { cookie: `${SESSION_COOKIE}=${sessionId}`, csrfToken }; +} + +function get(path: string, cookie?: string): Request { + return new Request(`https://pegma.dev${path}`, { + headers: cookie === undefined ? {} : { Cookie: cookie }, + }); +} + +function mutate( + method: 'POST' | 'DELETE', + path: string, + auth: { cookie: string; csrfToken: string }, + body?: unknown, +): Request { + return new Request(`https://pegma.dev${path}`, { + method, + headers: { + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + Cookie: auth.cookie, + 'X-Pegma-CSRF': auth.csrfToken, + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); +} + +function fixture(options: { bootstrapPrincipals?: readonly PrincipalId[] } = {}) { + const store = createMemoryStore(); + const sessions = createSessionStore(store, { logger }); + const users = new Map([ + [admin, userFor(admin, 'admin@example.test')], + [secondAdmin, userFor(secondAdmin, 'admin2@example.test')], + [member, userFor(member, 'member@example.test')], + ]); + const identity = identityFor(users); + const runtime = createSupportRuntime({ + store, + sessions, + identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + clock, + }); + const api = createAdminApi({ + sessions, + identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + roleStore: runtime.roleStore, + holderIndex: createRoleHolderIndex(store), + mutationLimiter: createAdminMutationLimiter(store, clock), + bootstrapPrincipals: new Set(options.bootstrapPrincipals ?? []), + }); + return { api, sessions, roleStore: runtime.roleStore }; +} + +/** Seed the first administrator the way the bootstrap touch would. */ +async function bootstrappedAdmin( + options: { bootstrapArmed?: boolean } = {}, +) { + const world = fixture({ bootstrapPrincipals: [admin] }); + const auth = await sessionCookie(world.sessions, admin, 'b'.repeat(43)); + // The first authenticated admin-surface touch seeds Admin, then passes + // the permission check on the same request. + const state = await world.api(get('/api/admin/state', auth.cookie)); + expect(state.status).toBe(200); + expect(((await state.json()) as { bootstrapArmed: boolean }).bootstrapArmed).toBe( + options.bootstrapArmed ?? true, + ); + return { ...world, auth }; +} + +describe('admin API access', () => { + it('requires authentication and the Admin role, fail-closed order', async () => { + const { api, sessions } = fixture(); + expect((await api(get('/api/admin/state'))).status).toBe(401); + + const nobody = await sessionCookie(sessions, member, 'n'.repeat(43)); + const forbidden = await api(get('/api/admin/state', nobody.cookie)); + expect(forbidden.status).toBe(403); + expect(await forbidden.json()).toEqual({ error: 'forbidden' }); + }); + + it('bootstrap seeds a listed principal on the first touch; the marker is history-durable', async () => { + const { api, roleStore, auth } = await bootstrappedAdmin(); + const held = await roleStore.listActiveRoleAssignments(admin, { + kind: 'application', + }); + expect(held.map((assignment) => assignment.role)).toEqual([ADMIN_ROLE]); + expect(held[0]!.grantedBy).toEqual({ + kind: 'system', + systemId: 'bootstrap', + }); + + // Grant a second admin, then revoke the seeded one; a further touch + // must NOT reseed — lifecycle history is the durable evidence. + const assign = await api( + mutate('POST', `/api/admin/principals/${secondAdmin}/roles`, auth, { + role: ADMIN_ROLE, + }), + ); + expect(assign.status).toBe(201); + const revoke = await api( + mutate( + 'DELETE', + `/api/admin/assignments/${held[0]!.id}`, + auth, + ), + ); + expect(revoke.status).toBe(200); + const after = await api(get('/api/admin/state', auth.cookie)); + expect(after.status).toBe(403); + expect( + await roleStore.listActiveRoleAssignments(admin, { kind: 'application' }), + ).toEqual([]); + }); +}); + +describe('principal views', () => { + it('returns the principal with managedBy-labelled roles, 404 for unknown', async () => { + const { api, auth } = await bootstrappedAdmin(); + const detail = await api( + get(`/api/admin/principals/${admin}`, auth.cookie), + ); + expect(detail.status).toBe(200); + const body = (await detail.json()) as { + principal: { email: string }; + roles: readonly { role: string; managedBy: string }[]; + }; + expect(body.principal.email).toBe('admin@example.test'); + expect(body.roles).toEqual([ + expect.objectContaining({ role: ADMIN_ROLE, managedBy: 'human' }), + ]); + + expect( + (await api(get('/api/admin/principals/unknown-principal', auth.cookie))) + .status, + ).toBe(404); + }); + + it('renders the audited lifecycle history', async () => { + const { api, auth } = await bootstrappedAdmin(); + const assign = await api( + mutate('POST', `/api/admin/principals/${member}/roles`, auth, { + role: SUPPORT_ROLE, + }), + ); + expect(assign.status).toBe(201); + const assigned = (await assign.json()) as { + roles: readonly { assignmentId: string }[]; + }; + const revoke = await api( + mutate( + 'DELETE', + `/api/admin/assignments/${assigned.roles[0]!.assignmentId}`, + auth, + ), + ); + expect(revoke.status).toBe(200); + + const history = await api( + get(`/api/admin/principals/${member}/history`, auth.cookie), + ); + const events = ((await history.json()) as { + events: readonly { kind: string; role: string }[]; + }).events; + expect(events.map((event) => event.kind)).toEqual(['granted', 'revoked']); + }); +}); + +describe('role mutations', () => { + it('assigns allowlisted roles only, to real principals only, once', async () => { + const { api, auth } = await bootstrappedAdmin(); + expect( + ( + await api( + mutate('POST', `/api/admin/principals/${member}/roles`, auth, { + role: 'Owner', + }), + ) + ).status, + ).toBe(400); + expect( + ( + await api( + mutate('POST', '/api/admin/principals/unknown-principal/roles', auth, { + role: SUPPORT_ROLE, + }), + ) + ).status, + ).toBe(404); + + const first = await api( + mutate('POST', `/api/admin/principals/${member}/roles`, auth, { + role: SUPPORT_ROLE, + }), + ); + expect(first.status).toBe(201); + const duplicate = await api( + mutate('POST', `/api/admin/principals/${member}/roles`, auth, { + role: SUPPORT_ROLE, + }), + ); + expect(duplicate.status).toBe(409); + expect(await duplicate.json()).toEqual({ error: 'duplicate_role' }); + }); + + it('refuses to revoke the last administrator with a typed 409', async () => { + const { api, roleStore, auth } = await bootstrappedAdmin(); + const held = await roleStore.listActiveRoleAssignments(admin, { + kind: 'application', + }); + const refusal = await api( + mutate('DELETE', `/api/admin/assignments/${held[0]!.id}`, auth), + ); + expect(refusal.status).toBe(409); + expect(await refusal.json()).toEqual({ error: 'last_administrator' }); + }); + + it('enforces CSRF on mutations', async () => { + const { api, auth } = await bootstrappedAdmin(); + const missingCsrf = new Request( + `https://pegma.dev/api/admin/principals/${member}/roles`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + Cookie: auth.cookie, + }, + body: JSON.stringify({ role: SUPPORT_ROLE }), + }, + ); + expect((await api(missingCsrf)).status).toBe(403); + }); +}); diff --git a/worker/src/admin-api.ts b/worker/src/admin-api.ts new file mode 100644 index 0000000..ce3d98f --- /dev/null +++ b/worker/src/admin-api.ts @@ -0,0 +1,317 @@ +import { + createRoleAdministration, + ensureSeededAssignment, + type RoleAdministration, + type RoleAdministrationStore, + type RoleHolderIndex, +} from '@pegma/authorization-admin'; +import { hasPermission, resolveAccess } from '@pegma/authorization-core'; +import type { DurableRateLimiter } from '@pegma/rate-limit'; +import type { SessionStore } from '@pegma/sessions'; +import type { Logger, PrincipalId } from '@pegma/spine'; +import { + ApiError, + authenticate, + enforceRateLimit, + exactObject, + json, + readJson, + requireCsrf, + requireSameOriginMutation, + type Authenticated, +} from './api-auth'; +import type { + IdentityLinkProjector, + IdentityPort, +} from './identity-contracts'; +import { + ADMIN_ROLE, + APPLICATION_SCOPE, + PEGMA_ACCESS_POLICY, + SUPPORT_ROLE, +} from './support-access'; + +/** + * Role-administration API (docs/ROLE_ADOPTION_PLAN.md Phase 5): the host + * HTTP envelope over `@pegma/authorization-admin`. One admin tool per + * site — this instance administers pegma.dev only. Every route is gated + * on a permission the stored `Admin` role grants; the service itself does + * not re-check callers. + */ + +const PRINCIPAL_PATH = + /^\/api\/admin\/principals\/([A-Za-z0-9._~-]{1,200})(?:\/(roles|history))?$/u; +const ASSIGNMENT_PATH = /^\/api\/admin\/assignments\/([A-Za-z0-9._~-]{1,200})$/u; + +/** The only roles the surface may assign; entitlements are not roles. */ +const ASSIGNABLE_ROLES: ReadonlySet = Object.freeze( + new Set([SUPPORT_ROLE, ADMIN_ROLE]), +); + +export interface AdminApiOptions { + readonly sessions: SessionStore; + readonly identity: IdentityPort; + readonly identityLinkFromClaims: IdentityLinkProjector; + readonly logger: Logger; + /** The audited role store (full surface: reads + audited mutations). */ + readonly roleStore: RoleAdministrationStore; + /** Host by-role holder index (role-holder-index.ts). */ + readonly holderIndex: RoleHolderIndex; + /** Durable limiter for role mutations. */ + readonly mutationLimiter: DurableRateLimiter; + /** + * One-time Admin bootstrap principals (`PEGMA_ADMIN_BOOTSTRAP_PRINCIPALS`). + * Delete the var once the first administrator holds the role; the + * surface reports `bootstrapArmed` while it is set. + */ + readonly bootstrapPrincipals: ReadonlySet; +} + +async function rolesView( + administration: RoleAdministration, + principalId: PrincipalId, +) { + const grants = await administration.viewGrants( + principalId, + APPLICATION_SCOPE, + ); + return grants.map(({ assignment, managedBy }) => ({ + assignmentId: assignment.id, + role: assignment.role, + grantedBy: assignment.grantedBy, + grantedAtEpochMs: assignment.grantedAtEpochMs, + managedBy, + })); +} + +/** Authenticated pegma.dev role-administration API. */ +export function createAdminApi( + options: AdminApiOptions, +): (request: Request) => Promise { + const administration = createRoleAdministration({ + store: options.roleStore, + holderIndex: options.holderIndex, + policy: { administratorRole: ADMIN_ROLE }, + }); + + async function requireAdminAccess( + request: Request, + permission: string, + ): Promise { + const authenticated = await authenticate(request, options); + if (authenticated === null) { + throw new ApiError(401, 'authentication_required'); + } + // One-time Admin bootstrap: an authenticated admin-surface touch by a + // listed principal seeds the audited grant BEFORE the permission + // check — the first administrator does not hold the role yet. Fail + // OPEN: a seed failure must not break the request; it retries on the + // next touch. Fresh opaque ids per attempt are safe because lifecycle + // history is the already-seeded signal (`docs/ADMINISTRATION.md`). + if ( + options.bootstrapPrincipals.size > 0 && + options.bootstrapPrincipals.has(authenticated.link.subject) + ) { + try { + const seeded = await ensureSeededAssignment({ + store: options.roleStore, + holderIndex: options.holderIndex, + principalId: authenticated.link.subject, + role: ADMIN_ROLE, + scope: APPLICATION_SCOPE, + assignmentId: crypto.randomUUID(), + auditEventId: crypto.randomUUID(), + }); + if (seeded === 'granted') { + options.logger.log('warn', 'admin.bootstrap_admin_seeded', { + principalId: authenticated.link.subject, + }); + } else if (seeded === 'conflict') { + options.logger.log('error', 'admin.bootstrap_admin_conflict', { + principalId: authenticated.link.subject, + }); + } + } catch (error) { + options.logger.log('warn', 'admin.bootstrap_admin_failed', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + } + // Re-resolved per request, uncached: a revocation is effective on the + // caller's next request. Fail closed on store errors — a 503, never a + // quiet allow or a misleading 403. + let roles; + try { + roles = await options.roleStore.listActiveRoleAssignments( + authenticated.link.subject, + APPLICATION_SCOPE, + ); + } catch (error) { + options.logger.log('error', 'admin.role_check_failed', { + error: error instanceof Error ? error.name : 'unknown', + }); + throw new ApiError(503, 'service_unavailable'); + } + const context = resolveAccess( + { + principalId: authenticated.link.subject, + roles: roles.map((assignment) => assignment.role), + }, + PEGMA_ACCESS_POLICY, + ); + if (!hasPermission(context, permission)) { + throw new ApiError(403, 'forbidden'); + } + return authenticated; + } + + return async (request) => { + const url = new URL(request.url); + const path = url.pathname; + try { + if (request.method === 'GET' && path === '/api/admin/state') { + const authenticated = await requireAdminAccess( + request, + 'admin.principal.read', + ); + return json({ + bootstrapArmed: options.bootstrapPrincipals.size > 0, + csrfToken: authenticated.csrfToken, + }); + } + + const principalMatch = PRINCIPAL_PATH.exec(path); + if (principalMatch !== null) { + const principalId = principalMatch[1] as PrincipalId; + const section = principalMatch[2]; + + if (request.method === 'GET' && section === undefined) { + await requireAdminAccess(request, 'admin.principal.read'); + const user = await options.identity.getUser(principalId); + if (user === null) { + throw new ApiError(404, 'not_found'); + } + return json({ + principal: { + principalId: user.principalId, + email: user.email, + status: user.status, + createdAt: user.createdAt, + }, + roles: await rolesView(administration, principalId), + }); + } + + if (request.method === 'GET' && section === 'history') { + await requireAdminAccess(request, 'admin.audit.read'); + const events = await administration.listHistory( + principalId, + APPLICATION_SCOPE, + ); + return json({ events }); + } + + if (request.method === 'POST' && section === 'roles') { + requireSameOriginMutation(request); + const authenticated = await requireAdminAccess( + request, + 'admin.role.assign', + ); + await requireCsrf(request, authenticated); + await enforceRateLimit( + options.mutationLimiter, + authenticated.link.subject, + ); + const body = exactObject(await readJson(request), ['role']); + const role = body.role; + if (typeof role !== 'string' || !ASSIGNABLE_ROLES.has(role)) { + throw new ApiError(400, 'invalid_role'); + } + // The target must be a real account — an assignment to a typo'd + // principal would be an unreachable grant. + if ((await options.identity.getUser(principalId)) === null) { + throw new ApiError(404, 'not_found'); + } + const result = await administration.assignRole({ + principalId, + role, + scope: APPLICATION_SCOPE, + actor: { + kind: 'principal', + principalId: authenticated.link.subject, + }, + }); + if (result.status === 'duplicate') { + throw new ApiError(409, 'duplicate_role'); + } + if (result.status === 'conflict') { + throw new ApiError(409, 'conflict'); + } + return json( + { roles: await rolesView(administration, principalId) }, + { status: 201 }, + ); + } + } + + const assignmentMatch = ASSIGNMENT_PATH.exec(path); + if (assignmentMatch !== null && request.method === 'DELETE') { + requireSameOriginMutation(request); + const authenticated = await requireAdminAccess( + request, + 'admin.role.revoke', + ); + await requireCsrf(request, authenticated); + await enforceRateLimit( + options.mutationLimiter, + authenticated.link.subject, + ); + const result = await administration.revokeRole({ + assignmentId: assignmentMatch[1]!, + actor: { + kind: 'principal', + principalId: authenticated.link.subject, + }, + }); + switch (result.status) { + case 'revoked': + if (result.compensated) { + options.logger.log('warn', 'admin.last_admin_compensated', { + assignmentId: assignmentMatch[1], + }); + } + return json({ revoked: true, compensated: result.compensated }); + case 'not_found': + throw new ApiError(404, 'not_found'); + case 'already_revoked': + throw new ApiError(409, 'already_revoked'); + case 'system_managed': + throw new ApiError(409, 'system_managed'); + case 'last_administrator': + throw new ApiError(409, 'last_administrator'); + case 'conflict': + throw new ApiError(409, 'conflict'); + } + } + + throw new ApiError(404, 'not_found'); + } catch (error) { + if (error instanceof ApiError) { + return json( + { error: error.code }, + { + status: error.status, + headers: + error.retryAfterSeconds === undefined + ? {} + : { 'Retry-After': String(error.retryAfterSeconds) }, + }, + ); + } + options.logger.log('error', 'admin.unhandled_error', { + error: error instanceof Error ? error.name : 'unknown', + }); + return json({ error: 'internal_error' }, { status: 500 }); + } + }; +} diff --git a/worker/src/api-auth.ts b/worker/src/api-auth.ts new file mode 100644 index 0000000..2c8dd4e --- /dev/null +++ b/worker/src/api-auth.ts @@ -0,0 +1,382 @@ +/** + * Session-authenticated API primitives shared by the Support Desk API and + * the role-administration API: cookie session resolution against Identity, + * CSRF and same-origin enforcement for mutations, strict JSON parsing, and + * the typed error envelope. Extracted from the Support Desk API when the + * admin surface became its second consumer; behavior, error codes, and + * emitted log events are unchanged (diff against the pre-extraction + * support-api.ts to verify). + */ +import type { Logger, PrincipalId } from '@pegma/spine'; +import type { SessionStore } from '@pegma/sessions'; +import type { DurableRateLimiter } from '@pegma/rate-limit'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import type { + IdentityLinkKey, + IdentityLinkProjector, + IdentityPort, + IdentityUser, + VerifiedIdentityClaims, +} from './identity-contracts'; + +export const JSON_LIMIT = 64 * 1024; +export const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/u; +const SESSION_DATA_KEYS = new Set([ + 'version', + 'csrfToken', + 'issuer', + 'subject', +]); + +interface SessionData { + readonly version: 1; + readonly csrfToken: string; + readonly issuer: typeof IDENTITY_ISSUER; + readonly subject: PrincipalId; +} + +export interface Authenticated { + readonly rawSessionId: string; + readonly csrfToken: string; + readonly link: IdentityLinkKey; + readonly user: IdentityUser; +} + +/** The ports session authentication needs; both APIs supply supersets. */ +export interface AuthenticationOptions { + readonly sessions: SessionStore; + readonly identity: IdentityPort; + readonly identityLinkFromClaims: IdentityLinkProjector; + readonly logger: Logger; +} + +export class ApiError extends Error { + constructor( + readonly status: number, + readonly code: string, + readonly retryAfterSeconds?: number, + ) { + super(code); + } +} + +export class InvalidatedSessionError extends ApiError { + constructor() { + super(401, 'authentication_required'); + } +} + +export function json(body: unknown, init: ResponseInit = {}): Response { + const headers = new Headers(init.headers); + headers.set('Cache-Control', 'no-store'); + headers.set('Pragma', 'no-cache'); + headers.set('Content-Type', 'application/json; charset=utf-8'); + headers.set('X-Content-Type-Options', 'nosniff'); + headers.set('Vary', 'Cookie'); + return Response.json(body, { ...init, headers }); +} + +function cookieValue(request: Request, name: string): string | null { + const header = request.headers.get('Cookie'); + if (header === null || header.length > 8_192) { + return null; + } + let found: string | null = null; + for (const part of header.split(';')) { + const separator = part.indexOf('='); + if (separator < 0 || part.slice(0, separator).trim() !== name) { + continue; + } + if (found !== null) { + return null; + } + found = part.slice(separator + 1).trim(); + } + return found !== null && TOKEN_PATTERN.test(found) ? found : null; +} + +export function isPlainObject( + value: unknown, +): value is Record { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + Object.getPrototypeOf(value) === Object.prototype + ); +} + +export function exactObject( + value: unknown, + keys: readonly string[], +): Record { + if ( + !isPlainObject(value) || + Object.keys(value).length !== keys.length || + keys.some((key) => !Object.hasOwn(value, key)) + ) { + throw new ApiError(400, 'invalid_request'); + } + return value; +} + +export function optionalKeysObject( + value: unknown, + required: readonly string[], + optional: readonly string[], +): Record { + if (!isPlainObject(value)) { + throw new ApiError(400, 'invalid_request'); + } + const allowed = new Set([...required, ...optional]); + const keys = Object.keys(value); + if ( + keys.some((key) => !allowed.has(key)) || + required.some((key) => !Object.hasOwn(value, key)) + ) { + throw new ApiError(400, 'invalid_request'); + } + return value; +} + +/** + * Validate a host-supplied string. + * @param options.allowMultiline When true, HT LF/CR/TAB are permitted (message + * bodies from textareas). Other C0/C1 controls remain rejected. + */ +export function boundedString( + value: unknown, + minimum: number, + maximum: number, + options: { allowMultiline?: boolean } = {}, +): string { + if ( + typeof value !== 'string' || + value.length < minimum || + value.length > maximum + ) { + throw new ApiError(400, 'invalid_request'); + } + // Never write literal control characters into source; use escapes. + // Multiline fields may include \t, \n, \r only. + const controlPattern = options.allowMultiline + ? /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/u + : /[\u0000-\u001F\u007F-\u009F]/u; + if (controlPattern.test(value)) { + throw new ApiError(400, 'invalid_request'); + } + return value; +} + +export async function readJson(request: Request): Promise { + const contentType = request.headers.get('Content-Type')?.split(';', 1)[0]; + if (contentType?.trim().toLowerCase() !== 'application/json') { + throw new ApiError(415, 'json_required'); + } + const declaredLength = request.headers.get('Content-Length'); + if ( + declaredLength !== null && + (!/^\d+$/u.test(declaredLength) || Number(declaredLength) > JSON_LIMIT) + ) { + throw new ApiError(413, 'request_too_large'); + } + if (request.body === null) { + throw new ApiError(400, 'invalid_json'); + } + + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + while (true) { + const chunk = await reader.read(); + if (chunk.done) { + break; + } + length += chunk.value.byteLength; + if (length > JSON_LIMIT) { + await reader.cancel(); + throw new ApiError(413, 'request_too_large'); + } + chunks.push(chunk.value); + } + } finally { + reader.releaseLock(); + } + + const bytes = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + try { + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch { + throw new ApiError(400, 'invalid_json'); + } +} + +export function requireSameOriginMutation(request: Request): void { + const url = new URL(request.url); + if ( + url.origin !== IDENTITY_ISSUER || + request.headers.get('Origin') !== IDENTITY_ISSUER || + request.headers.get('Sec-Fetch-Site') !== 'same-origin' + ) { + throw new ApiError(403, 'cross_origin_denied'); + } +} + +async function fixedTimeEqual(first: string, second: string): Promise { + const encoder = new TextEncoder(); + const [firstDigest, secondDigest] = await Promise.all([ + crypto.subtle.digest('SHA-256', encoder.encode(first)), + crypto.subtle.digest('SHA-256', encoder.encode(second)), + ]); + const firstBytes = new Uint8Array(firstDigest); + const secondBytes = new Uint8Array(secondDigest); + let difference = 0; + for (let index = 0; index < firstBytes.length; index += 1) { + difference |= firstBytes[index]! ^ secondBytes[index]!; + } + return difference === 0; +} + +function parseSessionData(value: string): SessionData | null { + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + return null; + } + const csrfToken = + typeof parsed === 'object' && + parsed !== null && + 'csrfToken' in parsed && + typeof parsed.csrfToken === 'string' + ? parsed.csrfToken + : ''; + if ( + !isPlainObject(parsed) || + Object.keys(parsed).length !== SESSION_DATA_KEYS.size || + Object.keys(parsed).some((key) => !SESSION_DATA_KEYS.has(key)) || + parsed.version !== 1 || + !TOKEN_PATTERN.test(csrfToken) || + parsed.issuer !== IDENTITY_ISSUER || + typeof parsed.subject !== 'string' || + parsed.subject.length === 0 + ) { + return null; + } + return { + version: 1, + csrfToken, + issuer: IDENTITY_ISSUER, + subject: parsed.subject as PrincipalId, + }; +} + +async function invalidateSession( + rawSessionId: string, + options: AuthenticationOptions, +): Promise { + try { + await options.sessions.destroy(rawSessionId); + } catch (error) { + options.logger.log('error', 'support.session_invalidation_cleanup_failed'); + throw error; + } + throw new InvalidatedSessionError(); +} + +export async function authenticate( + request: Request, + options: AuthenticationOptions, +): Promise { + const rawSessionId = cookieValue(request, SESSION_COOKIE); + if (rawSessionId === null) { + return null; + } + const record = await options.sessions.get(rawSessionId); + if (record === null) { + throw new InvalidatedSessionError(); + } + const data = parseSessionData(record.data); + if (data === null || data.subject !== record.principalId) { + return invalidateSession(rawSessionId, options); + } + + let claims: VerifiedIdentityClaims; + try { + claims = await options.identity.claimsFor(record.principalId); + } catch (error) { + const code = + typeof error === 'object' && error !== null && 'code' in error + ? (error as { readonly code?: unknown }).code + : undefined; + if (code === 'invalid_state' || code === 'not_found') { + return invalidateSession(rawSessionId, options); + } + throw error; + } + + let link: IdentityLinkKey; + try { + link = options.identityLinkFromClaims(claims); + } catch { + return invalidateSession(rawSessionId, options); + } + if ( + claims.emailVerified !== true || + link.issuer !== data.issuer || + link.subject !== data.subject + ) { + return invalidateSession(rawSessionId, options); + } + + const user = await options.identity.getUser(link.subject); + if ( + user === null || + user.principalId !== link.subject || + user.status !== 'active' || + user.emailVerified !== true + ) { + return invalidateSession(rawSessionId, options); + } + return { + rawSessionId, + csrfToken: data.csrfToken, + link, + user, + }; +} + +export async function requireCsrf( + request: Request, + authenticated: Authenticated, +): Promise { + const supplied = request.headers.get('X-Pegma-CSRF') ?? ''; + if ( + !TOKEN_PATTERN.test(supplied) || + !(await fixedTimeEqual(supplied, authenticated.csrfToken)) + ) { + throw new ApiError(403, 'csrf_denied'); + } +} + +export async function enforceRateLimit( + limiter: DurableRateLimiter, + key: string, +): Promise { + const decision = await limiter.allow(key); + if (!decision.allowed) { + const retryAfterSeconds = + decision.retryAfter !== undefined && + Number.isFinite(decision.retryAfter) && + decision.retryAfter > 0 + ? Math.ceil(decision.retryAfter / 1_000) + : undefined; + throw new ApiError(429, 'rate_limited', retryAfterSeconds); + } +} diff --git a/worker/src/index.ts b/worker/src/index.ts index 0a900d9..fd622f5 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -23,9 +23,15 @@ import { runReleaseReconciliation, } from './release-reconciliation'; import { handleGetReleases, readReleasesConfig } from './releases-api'; -import { parseBootstrapPrincipals } from './role-bootstrap'; +import { + parseAdminBootstrapPrincipals, + parseBootstrapPrincipals, +} from './role-bootstrap'; +import { createAdminApi } from './admin-api'; +import { createRoleHolderIndex } from './role-holder-index'; import { createSupportApi } from './support-api'; import { + createAdminMutationLimiter, createProductionSupportRuntime, probeSupportStore, supportHealthProbeEnabled, @@ -62,7 +68,19 @@ function createSupportHandler(env: AppEnv, logger: ReturnType; -/** Parse the bootstrap principal allowlist (trimmed, empties dropped). */ -export function parseBootstrapPrincipals(env: { - readonly PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS?: string; -}): ReadonlySet { - const raw = env.PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS; +function parsePrincipalList(raw: string | undefined): ReadonlySet { if (raw === undefined || raw.trim() === '') { return new Set(); } @@ -46,6 +42,20 @@ export function parseBootstrapPrincipals(env: { ); } +/** Parse the Support bootstrap allowlist (trimmed, empties dropped). */ +export function parseBootstrapPrincipals(env: { + readonly PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS?: string; +}): ReadonlySet { + return parsePrincipalList(env.PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS); +} + +/** Parse the Admin bootstrap allowlist (docs/ROLE_ADOPTION_PLAN.md Phase 5). */ +export function parseAdminBootstrapPrincipals(env: { + readonly PEGMA_ADMIN_BOOTSTRAP_PRINCIPALS?: string; +}): ReadonlySet { + return parsePrincipalList(env.PEGMA_ADMIN_BOOTSTRAP_PRINCIPALS); +} + /** The one bootstrap seed a principal can ever receive. */ export function bootstrapSupportAssignmentId(principalId: PrincipalId): string { return `bootstrap-support-${principalId}`; diff --git a/worker/src/role-holder-index.ts b/worker/src/role-holder-index.ts new file mode 100644 index 0000000..ad1943e --- /dev/null +++ b/worker/src/role-holder-index.ts @@ -0,0 +1,81 @@ +import type { RoleHolderIndex } from '@pegma/authorization-admin'; +import { + defineCollection, + type EntityKey, + type Store, + type StoredRecord, +} from '@pegma/storage-core'; + +/** + * Host implementation of `@pegma/authorization-admin`'s holder-index port + * (the `docs/STORAGE.md` superset-with-verification recipe): rows are + * written BEFORE grants, never deleted, and every reader verifies + * candidates against the authoritative role store — a dangling row from a + * crashed or refused grant is harmless noise. The index may over-report; + * it must never under-report a grant that exists, which is what lets the + * last-administrator guard fail only in the safe direction. + */ + +const HOLDER_PARTITION_PREFIX = 'role|'; + +interface HolderRow { + readonly role: string; + readonly principalId: string; + readonly assignmentId: string; +} + +function holderKey(row: HolderRow): EntityKey { + return { + partition: `${HOLDER_PARTITION_PREFIX}${row.role}`, + id: row.assignmentId, + }; +} + +function encode(value: HolderRow): StoredRecord { + return { + role: value.role, + principalId: value.principalId, + assignmentId: value.assignmentId, + }; +} + +function decode(record: StoredRecord): HolderRow { + return { + role: typeof record['role'] === 'string' ? record['role'] : '', + principalId: + typeof record['principalId'] === 'string' ? record['principalId'] : '', + assignmentId: + typeof record['assignmentId'] === 'string' ? record['assignmentId'] : '', + }; +} + +/** The by-role holder rows (`role-holder-index.v1`). */ +export function roleHolderIndexCollection() { + return defineCollection({ + name: 'role-holder-index.v1', + key: holderKey, + codec: { encode, decode }, + }); +} + +/** Bind the holder-index port over the host's shared Store. */ +export function createRoleHolderIndex(store: Store): RoleHolderIndex { + const rows = store.collection(roleHolderIndexCollection()); + return Object.freeze({ + async record(row) { + await rows.put({ + role: row.role, + principalId: row.principalId, + assignmentId: row.assignmentId, + }); + }, + async listByRole(role) { + const stored = await rows.list(`${HOLDER_PARTITION_PREFIX}${role}`); + return stored.map((row) => ({ + role: row.role, + principalId: row.principalId, + assignmentId: row.assignmentId, + })); + }, + } satisfies RoleHolderIndex); +} diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts index 1b7da9d..8bbbebb 100644 --- a/worker/src/support-access.ts +++ b/worker/src/support-access.ts @@ -25,12 +25,22 @@ export const SUPPORT_STAFF_PERMISSIONS = Object.freeze([ supportPermissions.auditRead, ] as const); +/** The support-operator role name (docs/ROLE_ADOPTION_PLAN.md). */ +export const SUPPORT_ROLE = 'Support' as const; + /** - * The operator role name (docs/ROLE_ADOPTION_PLAN.md). An `Admin` role is - * deliberately NOT mapped yet — it arrives with the Phase 5 management - * surface; a role nothing checks is a loaded gun. + * The role-administration role name — mapped since the Phase 5 surface + * shipped; the permissions below are exactly what the admin API checks. */ -export const SUPPORT_ROLE = 'Support' as const; +export const ADMIN_ROLE = 'Admin' as const; + +/** Admin permission set, granted via the {@link ADMIN_ROLE} role. */ +export const ADMIN_PERMISSIONS = Object.freeze([ + 'admin.principal.read', + 'admin.role.assign', + 'admin.role.revoke', + 'admin.audit.read', +] as const); /** * The application partition every pegma.dev authorization record belongs @@ -51,14 +61,17 @@ export const APPLICATION_SCOPE = Object.freeze({ * Customer permissions are granted to any authenticated account via * `defaults` — not a paid entitlement or invented multi-tenant role (there * is no billing ledger on pegma.dev; roles are the only stored grant). - * Staff permissions are granted via the stored, audited `Support` role. + * Staff permissions are granted via the stored, audited `Support` role, + * and role administration via the stored, audited `Admin` role — mapped + * with the Phase 5 surface (version 2 of the document). */ export const PEGMA_ACCESS_POLICY: PolicyDocumentV1 = Object.freeze({ schemaVersion: 1, - version: 'pegma.dev-policy-1', + version: 'pegma.dev-policy-2', defaults: [...SUPPORT_CUSTOMER_PERMISSIONS], roles: Object.freeze({ [SUPPORT_ROLE]: [...SUPPORT_STAFF_PERMISSIONS], + [ADMIN_ROLE]: [...ADMIN_PERMISSIONS], }), }); diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index e45c05e..d46158e 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -26,6 +26,19 @@ import type { IdentityUser, VerifiedIdentityClaims, } from './identity-contracts'; +import { + ApiError, + authenticate, + boundedString, + enforceRateLimit, + exactObject, + json, + optionalKeysObject, + readJson, + requireCsrf, + requireSameOriginMutation, + type Authenticated, +} from './api-auth'; import { ensureBootstrapSupport, type BootstrapRoleStore, @@ -45,14 +58,6 @@ import { type PegmaSupportCategory, } from './support-desk'; -const JSON_LIMIT = 64 * 1024; -const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/u; -const SESSION_DATA_KEYS = new Set([ - 'version', - 'csrfToken', - 'issuer', - 'subject', -]); const TICKET_ID_PATH = /^\/api\/support\/tickets\/([A-Za-z0-9._~-]{1,200})(?:\/(replies))?$/u; const ADMIN_TICKET_PATH = @@ -107,323 +112,6 @@ interface SupportApiOptions { readonly bootstrapPrincipals?: ReadonlySet; } -interface SessionData { - readonly version: 1; - readonly csrfToken: string; - readonly issuer: typeof IDENTITY_ISSUER; - readonly subject: PrincipalId; -} - -interface Authenticated { - readonly rawSessionId: string; - readonly csrfToken: string; - readonly link: IdentityLinkKey; - readonly user: IdentityUser; -} - -class ApiError extends Error { - constructor( - readonly status: number, - readonly code: string, - readonly retryAfterSeconds?: number, - ) { - super(code); - } -} - -class InvalidatedSessionError extends ApiError { - constructor() { - super(401, 'authentication_required'); - } -} - -function json( - body: unknown, - init: ResponseInit = {}, -): Response { - const headers = new Headers(init.headers); - headers.set('Cache-Control', 'no-store'); - headers.set('Pragma', 'no-cache'); - headers.set('Content-Type', 'application/json; charset=utf-8'); - headers.set('X-Content-Type-Options', 'nosniff'); - headers.set('Vary', 'Cookie'); - return Response.json(body, { ...init, headers }); -} - -function cookieValue(request: Request, name: string): string | null { - const header = request.headers.get('Cookie'); - if (header === null || header.length > 8_192) { - return null; - } - let found: string | null = null; - for (const part of header.split(';')) { - const separator = part.indexOf('='); - if (separator < 0 || part.slice(0, separator).trim() !== name) { - continue; - } - if (found !== null) { - return null; - } - found = part.slice(separator + 1).trim(); - } - return found !== null && TOKEN_PATTERN.test(found) ? found : null; -} - -function isPlainObject(value: unknown): value is Record { - return ( - typeof value === 'object' && - value !== null && - !Array.isArray(value) && - Object.getPrototypeOf(value) === Object.prototype - ); -} - -function exactObject( - value: unknown, - keys: readonly string[], -): Record { - if ( - !isPlainObject(value) || - Object.keys(value).length !== keys.length || - keys.some((key) => !Object.hasOwn(value, key)) - ) { - throw new ApiError(400, 'invalid_request'); - } - return value; -} - -function optionalKeysObject( - value: unknown, - required: readonly string[], - optional: readonly string[], -): Record { - if (!isPlainObject(value)) { - throw new ApiError(400, 'invalid_request'); - } - const allowed = new Set([...required, ...optional]); - const keys = Object.keys(value); - if ( - keys.some((key) => !allowed.has(key)) || - required.some((key) => !Object.hasOwn(value, key)) - ) { - throw new ApiError(400, 'invalid_request'); - } - return value; -} - -/** - * Validate a host-supplied string. - * @param options.allowMultiline When true, HT LF/CR/TAB are permitted (message - * bodies from textareas). Other C0/C1 controls remain rejected. - */ -function boundedString( - value: unknown, - minimum: number, - maximum: number, - options: { allowMultiline?: boolean } = {}, -): string { - if ( - typeof value !== 'string' || - value.length < minimum || - value.length > maximum - ) { - throw new ApiError(400, 'invalid_request'); - } - // Never write literal control characters into source; use escapes. - // Multiline fields may include \t, \n, \r only. - const controlPattern = options.allowMultiline - ? /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/u - : /[\u0000-\u001F\u007F-\u009F]/u; - if (controlPattern.test(value)) { - throw new ApiError(400, 'invalid_request'); - } - return value; -} - -async function readJson(request: Request): Promise { - const contentType = request.headers.get('Content-Type')?.split(';', 1)[0]; - if (contentType?.trim().toLowerCase() !== 'application/json') { - throw new ApiError(415, 'json_required'); - } - const declaredLength = request.headers.get('Content-Length'); - if ( - declaredLength !== null && - (!/^\d+$/u.test(declaredLength) || Number(declaredLength) > JSON_LIMIT) - ) { - throw new ApiError(413, 'request_too_large'); - } - if (request.body === null) { - throw new ApiError(400, 'invalid_json'); - } - - const reader = request.body.getReader(); - const chunks: Uint8Array[] = []; - let length = 0; - try { - while (true) { - const chunk = await reader.read(); - if (chunk.done) { - break; - } - length += chunk.value.byteLength; - if (length > JSON_LIMIT) { - await reader.cancel(); - throw new ApiError(413, 'request_too_large'); - } - chunks.push(chunk.value); - } - } finally { - reader.releaseLock(); - } - - const bytes = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - try { - return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); - } catch { - throw new ApiError(400, 'invalid_json'); - } -} - -function requireSameOriginMutation(request: Request): void { - const url = new URL(request.url); - if ( - url.origin !== IDENTITY_ISSUER || - request.headers.get('Origin') !== IDENTITY_ISSUER || - request.headers.get('Sec-Fetch-Site') !== 'same-origin' - ) { - throw new ApiError(403, 'cross_origin_denied'); - } -} - -async function fixedTimeEqual(first: string, second: string): Promise { - const encoder = new TextEncoder(); - const [firstDigest, secondDigest] = await Promise.all([ - crypto.subtle.digest('SHA-256', encoder.encode(first)), - crypto.subtle.digest('SHA-256', encoder.encode(second)), - ]); - const firstBytes = new Uint8Array(firstDigest); - const secondBytes = new Uint8Array(secondDigest); - let difference = 0; - for (let index = 0; index < firstBytes.length; index += 1) { - difference |= firstBytes[index]! ^ secondBytes[index]!; - } - return difference === 0; -} - -function parseSessionData(value: string): SessionData | null { - let parsed: unknown; - try { - parsed = JSON.parse(value); - } catch { - return null; - } - const csrfToken = - typeof parsed === 'object' && - parsed !== null && - 'csrfToken' in parsed && - typeof parsed.csrfToken === 'string' - ? parsed.csrfToken - : ''; - if ( - !isPlainObject(parsed) || - Object.keys(parsed).length !== SESSION_DATA_KEYS.size || - Object.keys(parsed).some((key) => !SESSION_DATA_KEYS.has(key)) || - parsed.version !== 1 || - !TOKEN_PATTERN.test(csrfToken) || - parsed.issuer !== IDENTITY_ISSUER || - typeof parsed.subject !== 'string' || - parsed.subject.length === 0 - ) { - return null; - } - return { - version: 1, - csrfToken, - issuer: IDENTITY_ISSUER, - subject: parsed.subject as PrincipalId, - }; -} - -async function invalidateSession( - rawSessionId: string, - options: SupportApiOptions, -): Promise { - try { - await options.sessions.destroy(rawSessionId); - } catch (error) { - options.logger.log('error', 'support.session_invalidation_cleanup_failed'); - throw error; - } - throw new InvalidatedSessionError(); -} - -async function authenticate( - request: Request, - options: SupportApiOptions, -): Promise { - const rawSessionId = cookieValue(request, SESSION_COOKIE); - if (rawSessionId === null) { - return null; - } - const record = await options.sessions.get(rawSessionId); - if (record === null) { - throw new InvalidatedSessionError(); - } - const data = parseSessionData(record.data); - if (data === null || data.subject !== record.principalId) { - return invalidateSession(rawSessionId, options); - } - - let claims: VerifiedIdentityClaims; - try { - claims = await options.identity.claimsFor(record.principalId); - } catch (error) { - const code = - typeof error === 'object' && error !== null && 'code' in error - ? (error as { readonly code?: unknown }).code - : undefined; - if (code === 'invalid_state' || code === 'not_found') { - return invalidateSession(rawSessionId, options); - } - throw error; - } - - let link: IdentityLinkKey; - try { - link = options.identityLinkFromClaims(claims); - } catch { - return invalidateSession(rawSessionId, options); - } - if ( - claims.emailVerified !== true || - link.issuer !== data.issuer || - link.subject !== data.subject - ) { - return invalidateSession(rawSessionId, options); - } - - const user = await options.identity.getUser(link.subject); - if ( - user === null || - user.principalId !== link.subject || - user.status !== 'active' || - user.emailVerified !== true - ) { - return invalidateSession(rawSessionId, options); - } - return { - rawSessionId, - csrfToken: data.csrfToken, - link, - user, - }; -} - async function requireAuthentication( request: Request, options: SupportApiOptions, @@ -462,35 +150,6 @@ async function requireAuthentication( return authenticated; } -async function requireCsrf( - request: Request, - authenticated: Authenticated, -): Promise { - const supplied = request.headers.get('X-Pegma-CSRF') ?? ''; - if ( - !TOKEN_PATTERN.test(supplied) || - !(await fixedTimeEqual(supplied, authenticated.csrfToken)) - ) { - throw new ApiError(403, 'csrf_denied'); - } -} - -async function enforceRateLimit( - limiter: DurableRateLimiter, - key: string, -): Promise { - const decision = await limiter.allow(key); - if (!decision.allowed) { - const retryAfterSeconds = - decision.retryAfter !== undefined && - Number.isFinite(decision.retryAfter) && - decision.retryAfter > 0 - ? Math.ceil(decision.retryAfter / 1_000) - : undefined; - throw new ApiError(429, 'rate_limited', retryAfterSeconds); - } -} - function publicTicketSummary(ticket: CustomerTicketSummary) { return { id: ticket.id, diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index 13dde4c..6bca8cf 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -157,6 +157,12 @@ export interface SupportRuntimeEnv { readonly IDENTITY_DB: D1Database; /** When `"true"`, health includes a lightweight Support Desk store probe. */ readonly SUPPORT_HEALTH_PROBE?: string; + /** + * One-time Admin bootstrap principals for the role-administration + * surface (docs/ROLE_ADOPTION_PLAN.md Phase 5). Delete after the first + * administrator holds the role. + */ + readonly PEGMA_ADMIN_BOOTSTRAP_PRINCIPALS?: string; /** * One-time Support-role bootstrap principals * (docs/ROLE_ADOPTION_PLAN.md Phase 3). Delete after the first operator @@ -206,6 +212,17 @@ function durableLimiter( ); } +/** + * Durable limiter for role-administration mutations (assign/revoke). + * Separate policy from the Support Desk limits; same shared Store. + */ +export function createAdminMutationLimiter( + store: Store, + clock: Clock = systemClock, +): DurableRateLimiter { + return durableLimiter(store, 'pegma.admin.role.mutate', 30, 60 * 60_000, clock); +} + /** * Production Support Desk composition for pegma.dev. *