From d43ea7bfa1c05a90af71901324729c1becab8915 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Thu, 30 Jul 2026 11:00:27 -0400 Subject: [PATCH 1/2] Adopt the stored Support role for staff access (phases 1-3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements docs/ROLE_ADOPTION_PLAN.md phases 1-3: - Phase 1: one unified PolicyDocumentV1 (pegma.dev-policy-1) — customer permissions via defaults, staff permissions via the Support role — schema-validated in tests; createRoleStore(store, 'pegma.dev') bound at the worker composition root over the shared D1 store. - Phase 2: the staff gate resolves stored role assignments per request, uncached; the env allowlist is honored beside the role path (and as fallthrough on role-store failure) until Phase 4 deletes it whole. - Phase 3: PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS seeds a real audited Support assignment (actor system:bootstrap) once per principal, ever — deterministic assignment id keeps a deliberate revocation durable while the env var lingers. Admin role deliberately not mapped yet; it arrives with the Phase 5 management surface. Co-Authored-By: Claude Fable 5 --- docs/ROLE_ADOPTION_PLAN.md | 12 +-- docs/SUPPORT_COMPOSITION.md | 46 +++++---- package-lock.json | 27 +++++ package.json | 2 + worker/src/index.ts | 5 + worker/src/role-bootstrap.ts | 105 +++++++++++++++++++ worker/src/support-access.ts | 119 ++++++++++++++++------ worker/src/support-api.test.ts | 179 ++++++++++++++++++++++++++++++++- worker/src/support-api.ts | 76 ++++++++++++-- worker/src/support-desk.ts | 22 ++++ 10 files changed, 528 insertions(+), 65 deletions(-) create mode 100644 worker/src/role-bootstrap.ts diff --git a/docs/ROLE_ADOPTION_PLAN.md b/docs/ROLE_ADOPTION_PLAN.md index 0197631..bf8774d 100644 --- a/docs/ROLE_ADOPTION_PLAN.md +++ b/docs/ROLE_ADOPTION_PLAN.md @@ -34,16 +34,16 @@ a `Support` role, and the staff gate reading it. ## Phase 1 — policy + role store binding -- [ ] Add `@pegma/authorization-storage` (exact pin, same 0.x line as the +- [x] Add `@pegma/authorization-storage` (exact pin, same 0.x line as the packages already composed). -- [ ] One host policy document (schema-validated in a test with +- [x] One host policy document (schema-validated in a test with `@pegma/authorization-policy`, the way retiregolden.org pins its `rg-policy-v1`): customer support permissions stay granted via `defaults` to any authenticated account (unchanged semantics), and a `Support` role maps to the six staff permissions. Define an `Admin` role name in the policy prose now, but map it only when Phase 5's surface exists to consume it — a role nothing checks is a loaded gun. -- [ ] Bind `createRoleStore(store, 'pegma.dev')` at the worker composition +- [x] Bind `createRoleStore(store, 'pegma.dev')` at the worker composition root, over the SAME D1-backed `Store` the other components share. The application id is one value, forever — changing it strands every assignment. @@ -52,16 +52,16 @@ a `Support` role, and the staff gate reading it. The lockout-safe order proven on retiregolden.org, transplanted: -- [ ] Staff access resolves the full context (stored roles + policy) **per +- [x] Staff access resolves the full context (stored roles + policy) **per request, uncached** — that is what honors the library's 60-second staff-check cache bound; a revocation is effective on the next request. -- [ ] Gate = role **or** legacy allowlist, both honored; a role-store +- [x] Gate = role **or** legacy allowlist, both honored; a role-store failure falls through to the allowlist while the legacy path exists (it stays authoritative until deleted). ## Phase 3 — first-operator seed -- [ ] `PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS` (comma-separated Identity +- [x] `PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS` (comma-separated Identity principal ids): on an authorization touch, a listed principal lacking the grant receives a REAL audited `Support` assignment with actor `system:bootstrap`. Two properties are load-bearing, both learned the diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index 0612d58..d871437 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -13,7 +13,9 @@ 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.1.2` (AccessContext resolution) +- `@pegma/authorization-core@0.2.0` (AccessContext resolution) +- `@pegma/authorization-policy@0.2.0` (PolicyDocumentV1 schema validation) +- `@pegma/authorization-storage@0.2.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`, @@ -39,30 +41,26 @@ two never share a cursor key. ### Customer -Any authenticated pegma.dev account receives customer permissions through host -AccessContext defaults (no paid entitlement): +Any authenticated pegma.dev account receives customer permissions through the +unified host policy's `defaults` (no paid entitlement): - `support.ticket.create` - `support.ticket.read.own` - `support.ticket.reply.own` -Policy version: `pegma.dev-support-customer-1`. +Policy version: `pegma.dev-policy-1` — one `PolicyDocumentV1` for the whole +host, schema-validated in tests (see `docs/ROLE_ADOPTION_PLAN.md`). -### Staff (host allowlist) +### Staff (stored `Support` role) -Staff are **not** a full role store. Operators are allowlisted via env: +Staff access is granted by a stored, audited `Support` role assignment in the +D1-backed role store (`@pegma/authorization-storage`, application id +`pegma.dev`, application scope). The gate re-reads active assignments on every +request, so a revocation is effective on the caller's next request. Non-staff +callers of staff routes receive **403** `forbidden` (not 404). +Unauthenticated callers receive **401**. -| Env | Meaning | -| --- | --- | -| `SUPPORT_STAFF_EMAILS` | Comma-separated verified emails (case-insensitive) | -| `SUPPORT_STAFF_PRINCIPALS` | Comma-separated Identity principal / subject ids | - -A principal is staff only when authenticated **and** (principal id is in -`SUPPORT_STAFF_PRINCIPALS` **or** verified user email is in -`SUPPORT_STAFF_EMAILS`). Non-staff callers of staff routes receive **403** -`forbidden` (not 404). Unauthenticated callers receive **401**. - -Staff AccessContext policy version: `pegma.dev-support-staff-1`. Permissions: +The `Support` role maps to: - `support.queue.read` - `support.ticket.reply.any` @@ -71,6 +69,20 @@ Staff AccessContext policy version: `pegma.dev-support-staff-1`. Permissions: - `support.ticket.manage` - `support.audit.read` +**Bootstrap (one-time seeding).** `PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS` +(comma-separated Identity principal ids) seeds a real audited `Support` +assignment (actor `system:bootstrap`, deterministic assignment id +`bootstrap-support-`) on a listed principal's next authenticated +support request. Each principal is seeded at most once, ever — a revoked seed +stays revoked even while the env var lingers. Delete the var once the first +operator holds the role. + +**Legacy allowlist (Phase 4 deletes it).** `SUPPORT_STAFF_EMAILS` / +`SUPPORT_STAFF_PRINCIPALS` are still honored beside the role path during the +lockout-safe retirement order; if the role store errors, the gate logs and +falls through to the allowlist. Parsing and the legacy resolver are deleted +whole in Phase 4 once the live bootstrap seed is confirmed. + `principalId` is always the Identity principal / account id from the server-side session (`__Host-pegma_session`). Browser-supplied identity fields are ignored. diff --git a/package-lock.json b/package-lock.json index 6e99942..1d1e6e8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,8 @@ "@pegma/audit": "0.2.0", "@pegma/authorization-core": "0.2.0", "@pegma/authorization-identity": "0.2.0", + "@pegma/authorization-policy": "0.2.0", + "@pegma/authorization-storage": "0.2.0", "@pegma/health": "^0.2.0", "@pegma/identity": "0.1.2", "@pegma/logger-cloudflare": "^0.1.1", @@ -3087,6 +3089,31 @@ "node": ">=22" } }, + "node_modules/@pegma/authorization-policy": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-policy/-/authorization-policy-0.2.0.tgz", + "integrity": "sha512-DOrqHfC6mt3SvcyWDyQ/ydMYQWQ7DPOTWXbKFSQoG+noAfBsAT+jxjDlglOXzz2REYCK0x78z5XHRcEztTyPtg==", + "license": "MIT", + "dependencies": { + "@pegma/authorization-contracts": "0.2.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@pegma/authorization-storage": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@pegma/authorization-storage/-/authorization-storage-0.2.0.tgz", + "integrity": "sha512-RceYZ3ctTpOxWy59i/xNinQtWazhBFSuEFlhOObEj4UJcJ2flzCnoZBL8Lls4iHZtsG8UYf/hp4f+ny8PJ90yg==", + "license": "MIT", + "dependencies": { + "@pegma/authorization-contracts": "0.2.0", + "@pegma/storage-core": "0.4.0" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/@pegma/health": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/@pegma/health/-/health-0.2.0.tgz", diff --git a/package.json b/package.json index 76c6b02..ae72af2 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,8 @@ "@pegma/audit": "0.2.0", "@pegma/authorization-core": "0.2.0", "@pegma/authorization-identity": "0.2.0", + "@pegma/authorization-policy": "0.2.0", + "@pegma/authorization-storage": "0.2.0", "@pegma/health": "^0.2.0", "@pegma/identity": "0.1.2", "@pegma/logger-cloudflare": "^0.1.1", diff --git a/worker/src/index.ts b/worker/src/index.ts index ff0d0b3..0b6576f 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -23,6 +23,7 @@ import { runReleaseReconciliation, } from './release-reconciliation'; import { handleGetReleases, readReleasesConfig } from './releases-api'; +import { parseBootstrapPrincipals } from './role-bootstrap'; import { createSupportApi } from './support-api'; import { parseStaffAllowlist } from './support-access'; import { @@ -58,6 +59,10 @@ function createSupportHandler(env: AppEnv, logger: ReturnType`), + * so the assignment record — active OR revoked — is the durable + * "already seeded" marker. A deliberately revoked operator stays revoked + * even while the env var is still configured; re-listing never re-seeds. + * - The seed is human-managed despite its system actor: `system:bootstrap` + * writes once and never touches the assignment again, so it is revocable + * like any human grant. + * + * Delete the env var once the first operator holds the role. + */ + +/** The role-store surface the bootstrap needs. */ +export type BootstrapRoleStore = Pick< + InMemoryStorageAdapter, + 'getRoleAssignment' | 'listActiveRoleAssignments' | 'grantRoleAssignmentWithAudit' +>; + +/** 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; + if (raw === undefined || raw.trim() === '') { + return new Set(); + } + return new Set( + raw + .split(',') + .map((part) => part.trim()) + .filter((part) => part.length > 0), + ); +} + +/** The one bootstrap seed a principal can ever receive. */ +export function bootstrapSupportAssignmentId(principalId: PrincipalId): string { + return `bootstrap-support-${principalId}`; +} + +/** + * Seed the `Support` role for a listed principal, ONCE PER PRINCIPAL, EVER. + * + * Idempotent and race-tolerant: an existing record under the deterministic + * id (any lifecycle state) or a concurrent seed losing on the assignment-id + * guard both report `'already'`. + */ +export async function ensureBootstrapSupport( + roleStore: BootstrapRoleStore, + principalId: PrincipalId, + bootstrapPrincipals: ReadonlySet, + nowEpochMs: () => number = () => Date.now(), +): Promise<'granted' | 'already' | 'not_listed'> { + if (!bootstrapPrincipals.has(principalId)) { + return 'not_listed'; + } + const assignmentId = bootstrapSupportAssignmentId(principalId); + // Active or revoked, an existing record means the one-time seed already + // happened — never seed twice, so revocation is durable. + if ((await roleStore.getRoleAssignment(assignmentId)) !== null) { + return 'already'; + } + // A Support role granted some other way also means nothing to bootstrap. + const active = await roleStore.listActiveRoleAssignments( + principalId, + APPLICATION_SCOPE, + ); + if (active.some((assignment) => assignment.role === SUPPORT_ROLE)) { + return 'already'; + } + const result = await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: assignmentId, + principalId, + role: SUPPORT_ROLE, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'bootstrap' }, + grantedAtEpochMs: nowEpochMs(), + status: 'active', + }, + // Deterministic like the assignment id: exact replays are 'unchanged'. + auditEventId: `evt-${assignmentId}`, + }); + if (result.status === 'granted') { + return 'granted'; + } + // 'unchanged' = exact replay; 'conflict' = another request seeded first — + // converged either way. + return 'already'; +} diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts index 8d9a0ce..80f4b92 100644 --- a/worker/src/support-access.ts +++ b/worker/src/support-access.ts @@ -1,16 +1,13 @@ -import { resolveAccess, type AccessContext } from '@pegma/authorization-core'; +import { + hasPermission, + resolveAccess, + type AccessContext, +} from '@pegma/authorization-core'; +import type { PolicyDocumentV1 } from '@pegma/authorization-policy'; +import type { RoleAssignmentReader } from '@pegma/authorization-storage'; import type { PrincipalId } from '@pegma/spine'; import { supportPermissions } from '@pegma/support-desk-application'; -/** - * Host policy version for pegma.dev product feedback. - * - * Customer permissions are granted to any authenticated account via defaults — - * not a paid entitlement or invented multi-tenant role. - */ -export const SUPPORT_CUSTOMER_POLICY_VERSION = - 'pegma.dev-support-customer-1' as const; - /** Customer permission set for authenticated pegma.dev accounts. */ export const SUPPORT_CUSTOMER_PERMISSIONS = Object.freeze([ supportPermissions.create, @@ -18,15 +15,7 @@ export const SUPPORT_CUSTOMER_PERMISSIONS = Object.freeze([ supportPermissions.replyOwn, ] as const); -/** - * Host policy version for pegma.dev Support Desk staff operators. - * - * Staff are selected by host env allowlists only — not a full role store. - */ -export const SUPPORT_STAFF_POLICY_VERSION = - 'pegma.dev-support-staff-1' as const; - -/** Staff permission set for allowlisted operators. */ +/** Staff permission set, granted via the {@link SUPPORT_ROLE} role. */ export const SUPPORT_STAFF_PERMISSIONS = Object.freeze([ supportPermissions.queueRead, supportPermissions.replyAny, @@ -36,6 +25,52 @@ export const SUPPORT_STAFF_PERMISSIONS = Object.freeze([ supportPermissions.auditRead, ] 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. + */ +export const SUPPORT_ROLE = 'Support' as const; + +/** + * The application partition every pegma.dev authorization record belongs + * to. One value, forever — changing it strands every role assignment. + */ +export const AUTHORIZATION_APPLICATION_ID = 'pegma.dev' as const; + +/** The only scope this host uses (no organizations). */ +export const APPLICATION_SCOPE = Object.freeze({ + kind: 'application', +} as const); + +/** + * The one host policy (docs/ROLE_ADOPTION_PLAN.md Phase 1), + * schema-validated in tests with `@pegma/authorization-policy` so drift + * fails CI. + * + * 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. + */ +export const PEGMA_ACCESS_POLICY: PolicyDocumentV1 = Object.freeze({ + schemaVersion: 1, + version: 'pegma.dev-policy-1', + defaults: [...SUPPORT_CUSTOMER_PERMISSIONS], + roles: Object.freeze({ + [SUPPORT_ROLE]: [...SUPPORT_STAFF_PERMISSIONS], + }), +}); + +/** + * The role-store read surface the staff gate needs — matches the object + * `createRoleStore` from `@pegma/authorization-storage` returns. + */ +export type SupportRoleReader = Pick< + RoleAssignmentReader, + 'listActiveRoleAssignments' +>; + /** Parsed host allowlists for Support Desk staff operators. */ export interface StaffAllowlist { /** Lowercased verified emails. */ @@ -90,22 +125,45 @@ export function emptyStaffAllowlist(): StaffAllowlist { * Resolve an AccessContext for an authenticated Identity principal. * * `principalId` must be the opaque Identity subject / account id from the - * server-side session (never a browser-supplied claim). + * server-side session (never a browser-supplied claim). Customer + * permissions come from the unified policy's `defaults`. */ export function customerAccessContext( principalId: PrincipalId, ): AccessContext { - return resolveAccess( - { principalId }, - { - version: SUPPORT_CUSTOMER_POLICY_VERSION, - defaults: [...SUPPORT_CUSTOMER_PERMISSIONS], - }, + return resolveAccess({ principalId }, PEGMA_ACCESS_POLICY); +} + +/** + * Resolve a staff AccessContext from the STORED `Support` role + * (docs/ROLE_ADOPTION_PLAN.md Phase 2) — the real gate. + * + * Re-resolved on every request, uncached: that is what honors the + * library's 60-second staff-check cache bound; a revocation is effective + * on the next request. Returns `null` when the resolved context does not + * grant the queue permission — callers map that to HTTP 403. + */ +export async function staffAccessContextFromRoles( + principalId: PrincipalId, + roleStore: SupportRoleReader, +): Promise { + const assignments = await roleStore.listActiveRoleAssignments( + principalId, + APPLICATION_SCOPE, + ); + const context = resolveAccess( + { principalId, roles: assignments.map((assignment) => assignment.role) }, + PEGMA_ACCESS_POLICY, ); + return hasPermission(context, supportPermissions.queueRead) + ? context + : null; } /** - * Resolve staff AccessContext when the principal is on the host allowlist. + * LEGACY staff AccessContext from the host env allowlist — honored beside + * the role path during the lockout-safe retirement order + * (docs/ROLE_ADOPTION_PLAN.md Phases 2–4), then deleted whole. * * A principal is staff only when authenticated **and** (principal id is in * `SUPPORT_STAFF_PRINCIPALS` **or** verified user email is in @@ -126,10 +184,7 @@ export function staffAccessContext( return null; } return resolveAccess( - { principalId }, - { - version: SUPPORT_STAFF_POLICY_VERSION, - defaults: [...SUPPORT_STAFF_PERMISSIONS], - }, + { principalId, roles: [SUPPORT_ROLE] }, + PEGMA_ACCESS_POLICY, ); } diff --git a/worker/src/support-api.test.ts b/worker/src/support-api.test.ts index ccdf4c6..3e3cb91 100644 --- a/worker/src/support-api.test.ts +++ b/worker/src/support-api.test.ts @@ -17,13 +17,22 @@ import type { VerifiedIdentityClaims, } from './identity-contracts'; import { createSupportApi } from './support-api'; +import { validatePolicy } from '@pegma/authorization-policy'; import { + APPLICATION_SCOPE, customerAccessContext, parseStaffAllowlist, + PEGMA_ACCESS_POLICY, staffAccessContext, + staffAccessContextFromRoles, + SUPPORT_ROLE, SUPPORT_STAFF_PERMISSIONS, - SUPPORT_STAFF_POLICY_VERSION, } from './support-access'; +import { + bootstrapSupportAssignmentId, + ensureBootstrapSupport, + parseBootstrapPrincipals, +} from './role-bootstrap'; import { createSupportRuntime, formatPegmaTicketSubject, @@ -146,6 +155,9 @@ function patch( function fixture(options: { readonly staffPrincipals?: readonly PrincipalId[]; readonly staffEmails?: readonly string[]; + readonly bootstrapPrincipals?: readonly PrincipalId[]; + /** Override the role store the API sees (e.g. a failing one). */ + readonly roleStoreOverride?: Parameters[0]['roleStore']; } = {}) { const store = createMemoryStore(); const sessions = createSessionStore(store, { logger }); @@ -175,9 +187,18 @@ function fixture(options: { createLimiter: runtime.createLimiter, replyLimiter: runtime.replyLimiter, logger, + roleStore: options.roleStoreOverride ?? runtime.roleStore, + bootstrapPrincipals: new Set(options.bootstrapPrincipals ?? []), staffAllowlist, }); - return { store, sessions, runtime, api, application: runtime.application }; + return { + store, + sessions, + runtime, + roleStore: runtime.roleStore, + api, + application: runtime.application, + }; } async function createCustomerTicket( @@ -542,7 +563,7 @@ describe('staff allowlist and access', () => { 'staff@example.test', ); expect(staffByPrincipal).not.toBeNull(); - expect(staffByPrincipal?.policyVersion).toBe(SUPPORT_STAFF_POLICY_VERSION); + expect(staffByPrincipal?.policyVersion).toBe(PEGMA_ACCESS_POLICY.version); expect(staffByPrincipal?.permissions).toEqual( expect.arrayContaining([...SUPPORT_STAFF_PERMISSIONS]), ); @@ -900,3 +921,155 @@ describe('staff support API', () => { expect(queue.status).toBe(200); }); }); + +describe('Support role store adoption (docs/ROLE_ADOPTION_PLAN.md phases 1–3)', () => { + async function grantSupport( + roleStore: ReturnType['roleStore'], + principalId: PrincipalId, + id = `assign-${principalId}`, + ) { + const granted = await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id, + principalId, + role: SUPPORT_ROLE, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'principal', principalId: 'principal-admin' }, + grantedAtEpochMs: Date.parse('2026-07-30T00:00:00.000Z'), + status: 'active', + }, + auditEventId: `evt-${id}`, + }); + expect(granted.status).toBe('granted'); + } + + it('the host policy validates as a PolicyDocumentV1 (schema drift fails CI)', () => { + const serialized = JSON.parse(JSON.stringify(PEGMA_ACCESS_POLICY)); + expect(validatePolicy(serialized)).toMatchObject({ valid: true }); + expect(validatePolicy({ ...serialized, version: 42 }).valid).toBe(false); + }); + + it('staffAccessContextFromRoles grants via the stored role and honors revocation next call', async () => { + const { roleStore } = fixture(); + expect( + await staffAccessContextFromRoles(principalStaff, roleStore), + ).toBeNull(); + + await grantSupport(roleStore, principalStaff); + const access = await staffAccessContextFromRoles(principalStaff, roleStore); + expect(access).not.toBeNull(); + expect(access?.policyVersion).toBe(PEGMA_ACCESS_POLICY.version); + expect(access?.permissions).toEqual( + expect.arrayContaining([...SUPPORT_STAFF_PERMISSIONS]), + ); + + const current = await roleStore.getRoleAssignment( + `assign-${principalStaff}`, + ); + const revoked = await roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: `assign-${principalStaff}`, + expectedConcurrencyToken: current!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: 'principal-admin' }, + revokedAtEpochMs: Date.parse('2026-07-30T01:00:00.000Z'), + auditEventId: 'evt-revoke-staff', + }); + expect(revoked.status).toBe('revoked'); + // Re-resolved per request — the 60-second bound is honored trivially. + expect( + await staffAccessContextFromRoles(principalStaff, roleStore), + ).toBeNull(); + }); + + it('a role-holder passes staff routes with an EMPTY allowlist (roles are the real gate)', async () => { + const { api, sessions, roleStore } = fixture(); + await grantSupport(roleStore, principalStaff); + const staff = await sessionCookie(sessions, principalStaff, 's'.repeat(43)); + const queue = await api(get('/api/support/admin/queue', staff.cookie)); + expect(queue.status).toBe(200); + }); + + it('denies without role or allowlist; a role-store failure falls back to the legacy allowlist', async () => { + const failing = { + listActiveRoleAssignments: async () => { + throw new Error('role store down'); + }, + getRoleAssignment: async () => null, + grantRoleAssignmentWithAudit: async () => { + throw new Error('role store down'); + }, + } as unknown as Parameters[0]['roleStore']; + + const denied = fixture({ roleStoreOverride: failing }); + const nobody = await sessionCookie(denied.sessions, principalA, 'n'.repeat(43)); + expect( + (await denied.api(get('/api/support/admin/queue', nobody.cookie))).status, + ).toBe(403); + + const legacy = fixture({ + roleStoreOverride: failing, + staffPrincipals: [principalStaff], + }); + const staff = await sessionCookie(legacy.sessions, principalStaff, 'l'.repeat(43)); + expect( + (await legacy.api(get('/api/support/admin/queue', staff.cookie))).status, + ).toBe(200); + }); + + it('bootstrap seeds a listed principal on an authenticated touch, once, revocation-durable', async () => { + const { api, sessions, roleStore } = fixture({ + bootstrapPrincipals: [principalStaff], + }); + const staff = await sessionCookie(sessions, principalStaff, 'b'.repeat(43)); + + // Any authenticated support touch seeds; the next staff call succeeds. + expect( + (await api(get('/api/support/categories', staff.cookie))).status, + ).toBe(200); + expect( + (await api(get('/api/support/admin/queue', staff.cookie))).status, + ).toBe(200); + + const assignmentId = bootstrapSupportAssignmentId(principalStaff); + const stored = await roleStore.getRoleAssignment(assignmentId); + expect(stored?.assignment).toMatchObject({ + role: SUPPORT_ROLE, + grantedBy: { kind: 'system', systemId: 'bootstrap' }, + status: 'active', + }); + + // Human revocation is DURABLE while the env var is still configured: + // the next touch must not resurrect the grant. + const revoked = await roleStore.revokeRoleAssignmentWithAudit({ + assignmentId, + expectedConcurrencyToken: stored!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: 'principal-admin' }, + // After the seed's real-clock grantedAtEpochMs — a revocation must + // not predate its grant. + revokedAtEpochMs: Date.now() + 1_000, + auditEventId: 'evt-revoke-bootstrap', + }); + expect(revoked.status).toBe('revoked'); + expect( + (await api(get('/api/support/categories', staff.cookie))).status, + ).toBe(200); + expect( + await ensureBootstrapSupport( + roleStore, + principalStaff, + new Set([principalStaff]), + ), + ).toBe('already'); + expect( + (await api(get('/api/support/admin/queue', staff.cookie))).status, + ).toBe(403); + }); + + it('parses the bootstrap principal list (trimmed, empties dropped)', () => { + expect( + parseBootstrapPrincipals({ + PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS: ' p-1, ,p-2 ', + }), + ).toEqual(new Set(['p-1', 'p-2'])); + expect(parseBootstrapPrincipals({})).toEqual(new Set()); + }); +}); diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index 4a6b33b..30a3c04 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -26,10 +26,16 @@ import type { IdentityUser, VerifiedIdentityClaims, } from './identity-contracts'; +import { + ensureBootstrapSupport, + type BootstrapRoleStore, +} from './role-bootstrap'; import { customerAccessContext, emptyStaffAllowlist, staffAccessContext, + staffAccessContextFromRoles, + type SupportRoleReader, type StaffAllowlist, } from './support-access'; import { @@ -96,10 +102,19 @@ interface SupportApiOptions { readonly replyLimiter: DurableRateLimiter; readonly logger: Logger; /** - * Host staff allowlist. Prefer injecting from env via `parseStaffAllowlist` + * LEGACY host staff allowlist, honored beside the role path during the + * lockout-safe retirement order (docs/ROLE_ADOPTION_PLAN.md) — deleted + * whole in Phase 4. Prefer injecting from env via `parseStaffAllowlist` * so tests can supply a fixed list without process env. */ readonly staffAllowlist?: StaffAllowlist; + /** + * Audited role store — the REAL staff gate (Phase 2). Absent ⇒ only the + * legacy allowlist can grant staff access. + */ + readonly roleStore?: SupportRoleReader & BootstrapRoleStore; + /** One-time Support bootstrap principals (Phase 3). */ + readonly bootstrapPrincipals?: ReadonlySet; } interface SessionData { @@ -427,6 +442,33 @@ async function requireAuthentication( if (authenticated === null) { throw new ApiError(401, 'authentication_required'); } + // One-time Support bootstrap (docs/ROLE_ADOPTION_PLAN.md Phase 3): any + // authenticated support touch by a listed principal seeds the audited + // grant. Fail OPEN — a seed failure must not break the request; it + // retries on the next touch. The set-membership check short-circuits for + // everyone not listed. + if ( + options.roleStore !== undefined && + options.bootstrapPrincipals !== undefined && + options.bootstrapPrincipals.size > 0 + ) { + try { + const seeded = await ensureBootstrapSupport( + options.roleStore, + authenticated.link.subject, + options.bootstrapPrincipals, + ); + if (seeded === 'granted') { + options.logger.log('warn', 'support.bootstrap_support_seeded', { + principalId: authenticated.link.subject, + }); + } + } catch (error) { + options.logger.log('warn', 'support.bootstrap_support_failed', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + } return authenticated; } @@ -648,10 +690,30 @@ function parseStaffQueueQuery(url: URL): StaffQueueQuery { return query; } -function requireStaffAccess( +async function requireStaffAccess( authenticated: Authenticated, allowlist: StaffAllowlist, + options: SupportApiOptions, ) { + // The Support ROLE is the real gate (docs/ROLE_ADOPTION_PLAN.md Phase 2); + // the env allowlist stays honored as the legacy path until Phase 4 + // deletes it whole. A role-store failure falls through to the allowlist + // rather than 503ing — the legacy path is authoritative until deleted. + if (options.roleStore !== undefined) { + try { + const roleAccess = await staffAccessContextFromRoles( + authenticated.link.subject, + options.roleStore, + ); + if (roleAccess !== null) { + return roleAccess; + } + } catch (error) { + options.logger.log('warn', 'support.staff_role_check_failed', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + } const access = staffAccessContext( authenticated.link.subject, allowlist, @@ -725,7 +787,7 @@ export function createSupportApi( if (request.method === 'GET' && path === '/api/support/admin/queue') { const authenticated = await requireAuthentication(request, options); - const access = requireStaffAccess(authenticated, staffAllowlist); + const access = await requireStaffAccess(authenticated, staffAllowlist, options); const queueQuery = parseStaffQueueQuery(url); const result = await options.application.listStaffQueue( access, @@ -745,7 +807,7 @@ export function createSupportApi( ) { const ticketId = adminMatch[1]!; const authenticated = await requireAuthentication(request, options); - const access = requireStaffAccess(authenticated, staffAllowlist); + const access = await requireStaffAccess(authenticated, staffAllowlist, options); const view = await options.application.readStaffTicket( access, ticketId, @@ -765,7 +827,7 @@ export function createSupportApi( const ticketId = adminMatch[1]!; const authenticated = await requireAuthentication(request, options); await requireCsrf(request, authenticated); - const access = requireStaffAccess(authenticated, staffAllowlist); + const access = await requireStaffAccess(authenticated, staffAllowlist, options); const body = optionalKeysObject( await readJson(request), @@ -857,7 +919,7 @@ export function createSupportApi( await requireCsrf(request, authenticated); // Authorize before debiting the shared customer/staff reply limiter so // non-staff sessions fail closed without mutating quota state. - const access = requireStaffAccess(authenticated, staffAllowlist); + const access = await requireStaffAccess(authenticated, staffAllowlist, options); await enforceRateLimit( options.replyLimiter, authenticated.link.subject, @@ -893,7 +955,7 @@ export function createSupportApi( const authenticated = await requireAuthentication(request, options); await requireCsrf(request, authenticated); // Same order as messages: staff check before shared limiter debit. - const access = requireStaffAccess(authenticated, staffAllowlist); + const access = await requireStaffAccess(authenticated, staffAllowlist, options); await enforceRateLimit( options.replyLimiter, authenticated.link.subject, diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index 3021364..8892c2a 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -9,6 +9,10 @@ import { type Logger, type PrincipalId, } from '@pegma/spine'; +import { + createRoleStore, + type InMemoryStorageAdapter, +} from '@pegma/authorization-storage'; import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; import type { Store } from '@pegma/storage-core'; import { @@ -24,8 +28,12 @@ import { } from '@pegma/support-desk-application'; import { defineTemplate } from '@pegma/support-desk-templates'; import type { IdentityLinkProjector, IdentityPort } from './identity-contracts'; +import { AUTHORIZATION_APPLICATION_ID } from './support-access'; import type { SessionStore } from '@pegma/sessions'; +/** The audited role store surface createRoleStore returns. */ +export type RoleStore = InMemoryStorageAdapter; + /** Host-configured category allowlist for pegma.dev product feedback. */ export const PEGMA_SUPPORT_CATEGORIES = Object.freeze([ 'feedback', @@ -162,6 +170,12 @@ export interface SupportRuntimeEnv { * operators. Combined with {@link SUPPORT_STAFF_EMAILS}. */ readonly SUPPORT_STAFF_PRINCIPALS?: string; + /** + * One-time Support-role bootstrap principals + * (docs/ROLE_ADOPTION_PLAN.md Phase 3). Delete after the first operator + * holds the role — it seeds state, it is never an authorization path. + */ + readonly PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS?: string; } export interface SupportCompositionOptions { @@ -177,6 +191,9 @@ export interface SupportCompositionOptions { export interface SupportRuntime { readonly store: Store; + /** Audited role store bound to this host's application partition + * (docs/ROLE_ADOPTION_PLAN.md Phase 1). */ + readonly roleStore: RoleStore; readonly application: SupportDeskApplication; readonly clock: Clock; readonly createLimiter: DurableRateLimiter; @@ -241,8 +258,13 @@ export function createSupportRuntime( queueTerminalRetentionMilliseconds: SUPPORT_TERMINAL_RETENTION_MS, }); + // Audited role store on the SAME Store, partitioned by this host's + // application id (docs/ROLE_ADOPTION_PLAN.md Phase 1). + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + return Object.freeze({ store, + roleStore, application, clock, createLimiter, From 87550170cfac99e0c28bb6c7b3e93ed2be9898e6 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Thu, 30 Jul 2026 11:45:47 -0400 Subject: [PATCH 2/2] Address review: durable bootstrap marker, legacy-gate permission proof, derived store types MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Bootstrap "already seeded" now lives in a host marker collection (support-bootstrap.markers.v1) written whenever the seed converges — including when Support is already held through another assignment, where the role store refuses a second active tuple and previously left no trace, so revoking that assignment while the env var lingered would have re-granted on the next touch (Codex P1). Grant-before-marker order keeps a crash between the two self-healing. - The legacy allowlist gate now requires the same queue-read permission proof as the role path; allowlisting alone never outranks the policy. - RoleStore / BootstrapRoleStore derive from createRoleStore's return type instead of naming the library's InMemoryStorageAdapter. Co-Authored-By: Claude Fable 5 --- docs/SUPPORT_COMPOSITION.md | 9 ++- worker/src/index.ts | 1 + worker/src/role-bootstrap.ts | 129 ++++++++++++++++++++++++--------- worker/src/support-access.ts | 7 +- worker/src/support-api.test.ts | 54 +++++++++++++- worker/src/support-api.ts | 5 ++ worker/src/support-desk.ts | 17 +++-- 7 files changed, 175 insertions(+), 47 deletions(-) diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index d871437..76f8bd1 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -33,6 +33,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` | +| Bootstrap-seed markers | `support-bootstrap.markers.v1` | Identity keeps its own collections and `pegma-dev-maintenance` cursors. The two never share a cursor key. @@ -73,9 +74,11 @@ The `Support` role maps to: (comma-separated Identity principal ids) seeds a real audited `Support` assignment (actor `system:bootstrap`, deterministic assignment id `bootstrap-support-`) on a listed principal's next authenticated -support request. Each principal is seeded at most once, ever — a revoked seed -stays revoked even while the env var lingers. Delete the var once the first -operator holds the role. +support request. Each principal is seeded at most once, ever: the handled +seed is recorded in the `support-bootstrap.markers.v1` collection — even when +nothing was granted because `Support` was already held through another +assignment — so a later revocation stays revoked while the env var lingers. +Delete the var once the first operator holds the role. **Legacy allowlist (Phase 4 deletes it).** `SUPPORT_STAFF_EMAILS` / `SUPPORT_STAFF_PRINCIPALS` are still honored beside the role path during the diff --git a/worker/src/index.ts b/worker/src/index.ts index 0b6576f..2d8b6a0 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -62,6 +62,7 @@ function createSupportHandler(env: AppEnv, logger: ReturnType`), - * so the assignment record — active OR revoked — is the durable - * "already seeded" marker. A deliberately revoked operator stays revoked - * even while the env var is still configured; re-listing never re-seeds. - * - The seed is human-managed despite its system actor: `system:bootstrap` - * writes once and never touches the assignment again, so it is revocable - * like any human grant. + * "Already seeded" is recorded in a host marker collection, not inferred + * from role state. The role store refuses a second ACTIVE assignment per + * (principal, role, scope) and cannot enumerate revoked assignments + * (authorization-core#24), so no assignment-shaped signal survives every + * case — in particular a listed principal holding `Support` through some + * other assignment would carry no trace, and revoking that assignment + * while the env var lingers would silently re-grant on the next touch. + * The marker is written whenever the seed converges (granted, or nothing + * to grant), making a later revocation durable in all cases. The grant + * itself is human-managed despite its system actor: `system:bootstrap` + * writes once and never touches the assignment again, so it is revocable + * like any human grant. * * Delete the env var once the first operator holds the role. */ +const BOOTSTRAP_MARKER_PARTITION = 'support-bootstrap'; + +/** Durable "the one-time seed already happened" record for one principal. */ +export interface BootstrapMarker { + readonly principalId: string; + readonly seededAtEpochMs: number; + /** Whether the seed granted, or found `Support` already held elsewhere. */ + readonly outcome: 'granted' | 'held_elsewhere'; +} + +function bootstrapMarkerKey(principalId: string): EntityKey { + return { partition: BOOTSTRAP_MARKER_PARTITION, id: principalId }; +} + +function encode(value: BootstrapMarker): StoredRecord { + return { + principalId: value.principalId, + seededAtEpochMs: value.seededAtEpochMs, + outcome: value.outcome, + }; +} + +function decode(record: StoredRecord): BootstrapMarker { + return { + principalId: + typeof record['principalId'] === 'string' ? record['principalId'] : '', + seededAtEpochMs: + typeof record['seededAtEpochMs'] === 'number' + ? record['seededAtEpochMs'] + : 0, + outcome: record['outcome'] === 'held_elsewhere' ? 'held_elsewhere' : 'granted', + }; +} + +/** The host collection holding bootstrap markers (`support-bootstrap.markers.v1`). */ +export function bootstrapMarkerCollection() { + return defineCollection({ + name: 'support-bootstrap.markers.v1', + key: (value) => bootstrapMarkerKey(value.principalId), + codec: { encode, decode }, + }); +} + +/** The marker store surface the bootstrap needs. */ +export type BootstrapMarkerStore = Pick< + CollectionStore, + 'get' | 'insertIfAbsent' +>; + /** The role-store surface the bootstrap needs. */ export type BootstrapRoleStore = Pick< - InMemoryStorageAdapter, - 'getRoleAssignment' | 'listActiveRoleAssignments' | 'grantRoleAssignmentWithAudit' + RoleStore, + 'grantRoleAssignmentWithAudit' >; /** Parse the bootstrap principal allowlist (trimmed, empties dropped). */ @@ -56,12 +111,17 @@ export function bootstrapSupportAssignmentId(principalId: PrincipalId): string { /** * Seed the `Support` role for a listed principal, ONCE PER PRINCIPAL, EVER. * - * Idempotent and race-tolerant: an existing record under the deterministic - * id (any lifecycle state) or a concurrent seed losing on the assignment-id - * guard both report `'already'`. + * Order matters: the grant lands BEFORE the marker, so a crash between the + * two heals on the next touch (the re-grant converges on the deterministic + * assignment id, then the marker is written), while a marker written ahead + * of a failed grant would strand the principal unseeded forever. + * + * Idempotent and race-tolerant: an existing marker, a replayed grant, or a + * concurrent seed losing on the assignment-id guard all report `'already'`. */ export async function ensureBootstrapSupport( roleStore: BootstrapRoleStore, + markers: BootstrapMarkerStore, principalId: PrincipalId, bootstrapPrincipals: ReadonlySet, nowEpochMs: () => number = () => Date.now(), @@ -69,20 +129,10 @@ export async function ensureBootstrapSupport( if (!bootstrapPrincipals.has(principalId)) { return 'not_listed'; } - const assignmentId = bootstrapSupportAssignmentId(principalId); - // Active or revoked, an existing record means the one-time seed already - // happened — never seed twice, so revocation is durable. - if ((await roleStore.getRoleAssignment(assignmentId)) !== null) { - return 'already'; - } - // A Support role granted some other way also means nothing to bootstrap. - const active = await roleStore.listActiveRoleAssignments( - principalId, - APPLICATION_SCOPE, - ); - if (active.some((assignment) => assignment.role === SUPPORT_ROLE)) { + if ((await markers.get(bootstrapMarkerKey(principalId))) !== null) { return 'already'; } + const assignmentId = bootstrapSupportAssignmentId(principalId); const result = await roleStore.grantRoleAssignmentWithAudit({ assignment: { id: assignmentId, @@ -96,10 +146,17 @@ export async function ensureBootstrapSupport( // Deterministic like the assignment id: exact replays are 'unchanged'. auditEventId: `evt-${assignmentId}`, }); - if (result.status === 'granted') { - return 'granted'; - } - // 'unchanged' = exact replay; 'conflict' = another request seeded first — - // converged either way. - return 'already'; + // 'granted'/'unchanged' seeded the assignment. 'conflict' converged too: + // on the assignment id (a pre-marker seed already exists, active or + // revoked) or on the active tuple (`Support` held through another + // assignment — nothing to grant, but the seed is HANDLED and must leave + // a trace so revoking that other assignment can't trigger a reseed). + const heldElsewhere = + result.status === 'conflict' && result.reason === 'active_tuple'; + await markers.insertIfAbsent({ + principalId, + seededAtEpochMs: nowEpochMs(), + outcome: heldElsewhere ? 'held_elsewhere' : 'granted', + }); + return result.status === 'granted' ? 'granted' : 'already'; } diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts index 80f4b92..f65e0c0 100644 --- a/worker/src/support-access.ts +++ b/worker/src/support-access.ts @@ -183,8 +183,13 @@ export function staffAccessContext( if (!principalAllowed && !emailAllowed) { return null; } - return resolveAccess( + const context = resolveAccess( { principalId, roles: [SUPPORT_ROLE] }, PEGMA_ACCESS_POLICY, ); + // Same permission proof as the role path: allowlisting alone never + // outranks what the policy actually grants. + return hasPermission(context, supportPermissions.queueRead) + ? context + : null; } diff --git a/worker/src/support-api.test.ts b/worker/src/support-api.test.ts index 3e3cb91..864191e 100644 --- a/worker/src/support-api.test.ts +++ b/worker/src/support-api.test.ts @@ -188,6 +188,7 @@ function fixture(options: { replyLimiter: runtime.replyLimiter, logger, roleStore: options.roleStoreOverride ?? runtime.roleStore, + bootstrapMarkers: runtime.bootstrapMarkers, bootstrapPrincipals: new Set(options.bootstrapPrincipals ?? []), staffAllowlist, }); @@ -196,6 +197,7 @@ function fixture(options: { sessions, runtime, roleStore: runtime.roleStore, + bootstrapMarkers: runtime.bootstrapMarkers, api, application: runtime.application, }; @@ -1016,7 +1018,7 @@ describe('Support role store adoption (docs/ROLE_ADOPTION_PLAN.md phases 1–3)' }); it('bootstrap seeds a listed principal on an authenticated touch, once, revocation-durable', async () => { - const { api, sessions, roleStore } = fixture({ + const { api, sessions, roleStore, bootstrapMarkers } = fixture({ bootstrapPrincipals: [principalStaff], }); const staff = await sessionCookie(sessions, principalStaff, 'b'.repeat(43)); @@ -1055,6 +1057,7 @@ describe('Support role store adoption (docs/ROLE_ADOPTION_PLAN.md phases 1–3)' expect( await ensureBootstrapSupport( roleStore, + bootstrapMarkers, principalStaff, new Set([principalStaff]), ), @@ -1064,6 +1067,55 @@ describe('Support role store adoption (docs/ROLE_ADOPTION_PLAN.md phases 1–3)' ).toBe(403); }); + it('marks a listed principal already holding Support elsewhere, so revoking that grant cannot be undone by a reseed', async () => { + const { api, sessions, roleStore, bootstrapMarkers } = fixture({ + bootstrapPrincipals: [principalStaff], + }); + // Support held via a NON-bootstrap assignment before the first touch. + await grantSupport(roleStore, principalStaff); + const other = await roleStore.getRoleAssignment(`assign-${principalStaff}`); + const staff = await sessionCookie(sessions, principalStaff, 'm'.repeat(43)); + + // The touch grants nothing (the store refuses a second active + // assignment per tuple) but still records the handled seed — the host + // marker is the ONLY "already seeded" signal; role state is not one. + expect( + (await api(get('/api/support/categories', staff.cookie))).status, + ).toBe(200); + expect( + await roleStore.getRoleAssignment( + bootstrapSupportAssignmentId(principalStaff), + ), + ).toBeNull(); + expect( + await bootstrapMarkers.get({ + partition: 'support-bootstrap', + id: principalStaff, + }), + ).toMatchObject({ principalId: principalStaff, outcome: 'held_elsewhere' }); + + // Revoke the held assignment; the next touch must not re-grant. + const revoked = await roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: other!.assignment.id, + expectedConcurrencyToken: other!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: 'principal-admin' }, + revokedAtEpochMs: Date.now() + 1_000, + auditEventId: `evt-revoke-${other!.assignment.id}`, + }); + expect(revoked.status).toBe('revoked'); + expect( + (await api(get('/api/support/categories', staff.cookie))).status, + ).toBe(200); + expect( + await roleStore.getRoleAssignment( + bootstrapSupportAssignmentId(principalStaff), + ), + ).toBeNull(); + expect( + (await api(get('/api/support/admin/queue', staff.cookie))).status, + ).toBe(403); + }); + it('parses the bootstrap principal list (trimmed, empties dropped)', () => { expect( parseBootstrapPrincipals({ diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index 30a3c04..b49b6c8 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -28,6 +28,7 @@ import type { } from './identity-contracts'; import { ensureBootstrapSupport, + type BootstrapMarkerStore, type BootstrapRoleStore, } from './role-bootstrap'; import { @@ -115,6 +116,8 @@ interface SupportApiOptions { readonly roleStore?: SupportRoleReader & BootstrapRoleStore; /** One-time Support bootstrap principals (Phase 3). */ readonly bootstrapPrincipals?: ReadonlySet; + /** Durable bootstrap-seed markers; required for the seed to run. */ + readonly bootstrapMarkers?: BootstrapMarkerStore; } interface SessionData { @@ -449,12 +452,14 @@ async function requireAuthentication( // everyone not listed. if ( options.roleStore !== undefined && + options.bootstrapMarkers !== undefined && options.bootstrapPrincipals !== undefined && options.bootstrapPrincipals.size > 0 ) { try { const seeded = await ensureBootstrapSupport( options.roleStore, + options.bootstrapMarkers, authenticated.link.subject, options.bootstrapPrincipals, ); diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index 8892c2a..114e72b 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -9,12 +9,9 @@ import { type Logger, type PrincipalId, } from '@pegma/spine'; -import { - createRoleStore, - type InMemoryStorageAdapter, -} from '@pegma/authorization-storage'; +import { createRoleStore } from '@pegma/authorization-storage'; import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; -import type { Store } from '@pegma/storage-core'; +import type { CollectionStore, Store } from '@pegma/storage-core'; import { createSupportDeskApplication, defaultQueueTerminalRetentionMilliseconds, @@ -29,10 +26,14 @@ import { import { defineTemplate } from '@pegma/support-desk-templates'; import type { IdentityLinkProjector, IdentityPort } from './identity-contracts'; import { AUTHORIZATION_APPLICATION_ID } from './support-access'; +import { + bootstrapMarkerCollection, + type BootstrapMarker, +} from './role-bootstrap'; import type { SessionStore } from '@pegma/sessions'; /** The audited role store surface createRoleStore returns. */ -export type RoleStore = InMemoryStorageAdapter; +export type RoleStore = ReturnType; /** Host-configured category allowlist for pegma.dev product feedback. */ export const PEGMA_SUPPORT_CATEGORIES = Object.freeze([ @@ -194,6 +195,8 @@ export interface SupportRuntime { /** Audited role store bound to this host's application partition * (docs/ROLE_ADOPTION_PLAN.md Phase 1). */ readonly roleStore: RoleStore; + /** Durable one-time bootstrap-seed markers (role-bootstrap.ts). */ + readonly bootstrapMarkers: CollectionStore; readonly application: SupportDeskApplication; readonly clock: Clock; readonly createLimiter: DurableRateLimiter; @@ -261,10 +264,12 @@ export function createSupportRuntime( // Audited role store on the SAME Store, partitioned by this host's // application id (docs/ROLE_ADOPTION_PLAN.md Phase 1). const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const bootstrapMarkers = store.collection(bootstrapMarkerCollection()); return Object.freeze({ store, roleStore, + bootstrapMarkers, application, clock, createLimiter,