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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions docs/ROLE_ADOPTION_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
49 changes: 32 additions & 17 deletions docs/SUPPORT_COMPOSITION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand All @@ -31,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.
Expand All @@ -39,30 +42,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`
Expand All @@ -71,6 +70,22 @@ 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-<principalId>`) on a listed principal's next authenticated
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
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.
Expand Down
27 changes: 27 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -58,6 +59,11 @@ function createSupportHandler(env: AppEnv, logger: ReturnType<typeof createAppLo
createLimiter: supportRuntime.createLimiter,
replyLimiter: supportRuntime.replyLimiter,
logger,
// The Support ROLE is the real staff gate; the allowlist is the legacy
// path until Phase 4 of docs/ROLE_ADOPTION_PLAN.md deletes it.
roleStore: supportRuntime.roleStore,
bootstrapMarkers: supportRuntime.bootstrapMarkers,
bootstrapPrincipals: parseBootstrapPrincipals(env),
staffAllowlist: parseStaffAllowlist(env),
});
return { supportRuntime, api };
Expand Down
162 changes: 162 additions & 0 deletions worker/src/role-bootstrap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import type { PrincipalId } from '@pegma/spine';
import {
defineCollection,
type CollectionStore,
type EntityKey,
type StoredRecord,
} from '@pegma/storage-core';
import { APPLICATION_SCOPE, SUPPORT_ROLE } from './support-access';
import type { RoleStore } from './support-desk';

/**
* One-time Support-role bootstrap (docs/ROLE_ADOPTION_PLAN.md Phase 3).
*
* `PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS` lists Identity principal ids that
* receive a REAL audited `Support` assignment on their next authenticated
* support touch. The env var seeds state; it is never itself an
* authorization path — every later check reads the role store.
*
* "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<BootstrapMarker>({
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<BootstrapMarker>,
'get' | 'insertIfAbsent'
>;

/** The role-store surface the bootstrap needs. */
export type BootstrapRoleStore = Pick<
RoleStore,
'grantRoleAssignmentWithAudit'
>;

/** Parse the bootstrap principal allowlist (trimmed, empties dropped). */
export function parseBootstrapPrincipals(env: {
readonly PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS?: string;
}): ReadonlySet<string> {
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.
*
* 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<string>,
nowEpochMs: () => number = () => Date.now(),
): Promise<'granted' | 'already' | 'not_listed'> {
if (!bootstrapPrincipals.has(principalId)) {
return 'not_listed';
}
if ((await markers.get(bootstrapMarkerKey(principalId))) !== null) {
return 'already';
}
const assignmentId = bootstrapSupportAssignmentId(principalId);
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}`,
});
// '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';
}
Loading