diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 9572f2434e..7eae9721b9 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -81,6 +81,10 @@ export interface Config { /** Break-glass owner token store (#9608) — written only by the local * owner CLI (scripts/issue-break-glass-token.ts); hashes only. */ breakGlassFile: string; + /** Outage-queued action writes (#9608, design #1253 section 6): + * writes queued unverified during an Access/IdP outage, held out + * of the actions store until a fresh login confirms the claim. */ + outageQueueFile: string; /** Source freshness invalidation journal, separate from #1739/#3321. */ freshnessFile: string; /** Loopback-only publisher listener; never included in PM_AGG_HOSTS. */ @@ -251,6 +255,10 @@ export function loadConfig(env: Record = process.env env.PM_AGG_BREAK_GLASS_FILE, join(homedir(), ".local", "state", "pm-aggregator", "break-glass-tokens.json"), ), + outageQueueFile: s( + env.PM_AGG_OUTAGE_QUEUE_FILE, + join(homedir(), ".local", "state", "pm-aggregator", "outage-queue.json"), + ), freshnessFile: s(env.PM_AGG_FRESHNESS_FILE, join(homedir(), ".local", "state", "pm-aggregator", "freshness.json")), freshnessPort: parseAggregatorPort(env.PM_AGG_FRESHNESS_PORT, "PM_AGG_FRESHNESS_PORT", "4871"), queueBrokerUrl: s(env.PM_AGG_QUEUE_BROKER_URL, "http://100.99.113.103:4801"), diff --git a/pm-stack/aggregator/src/outage-queue.ts b/pm-stack/aggregator/src/outage-queue.ts new file mode 100644 index 0000000000..3538e39030 --- /dev/null +++ b/pm-stack/aggregator/src/outage-queue.ts @@ -0,0 +1,500 @@ +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { NewAction } from "./actions.ts"; +import { validateAuthor } from "./comments.ts"; +import type { NewAuditEvent } from "./events.ts"; +import type { DashAuthor } from "./model.ts"; + +/** + * Outage queueing for dashboard action writes (#9608, design #1253 + * section 6 — the break-glass posture). + * + * When Access or the IdP is down, the stack must not choose between + * "closed" and "asserted authorship returns". Reads keep working from + * last-known state (the stack is local-first; nothing here touches + * the read path). For writes, this module is the queue half of the + * posture: + * + * - A dashboard action write that arrives while identity verification + * is failing (the server routes only the enforcer's 401 here — a + * 403 means a verified identity contradicted the claim, which is + * not an outage) may be QUEUED instead of refused, but only from a + * stack-local address (see isStackLocalAddress) and only when the + * write is eligible (see outageQueueEligible). + * - A queued write is stamped `provenance: "outage-queued"` with the + * claimed author kept visibly a claim. It lives ONLY in this store: + * it never enters the actions store, so consumer polls + * (GET /api/actions.json?state=new) and every verified-authorship + * surface never see it. Nothing outage-queued is ever silently + * promoted. + * - The entry recovering is not enough: the claimant confirms with a + * fresh login. Confirmation requires the Access-derived author of + * that fresh login to match the claim (kind + id); the write is + * then released into the actions store under the VERIFIED author — + * the re-stamp — or rejected by its claimant. A verified owner may + * also reject a claim that is not theirs: rejection can never + * create authorship, and without it a forged claim could never be + * cleared from the owner's own queue. Confirmation stays + * claimant-only, strictly. + * - Asserted authorship as a fallback mode does not exist: a write + * that cannot queue under the rules above gets the enforcer's + * refusal, exactly as before this module existed. + * + * Queueing, confirmation, and rejection are each written as an audit + * event BEFORE the queue record changes state (the break-glass + * issuance pattern): if the audit write fails, nothing changes. + * + * The store is read fresh from disk on every operation (no cache), + * mirroring BreakGlassTokenStore: the file is the record, and a + * cached copy could resurrect a resolved claim. + */ + +export const OUTAGE_QUEUED_PROVENANCE = "outage-queued" as const; + +export type OutageQueueState = "queued" | "confirmed" | "rejected"; + +export interface OutageQueuedWrite { + id: string; + queuedAt: string; + /** The design section 6 stamp; the write is a claim until confirmed. */ + provenance: typeof OUTAGE_QUEUED_PROVENANCE; + /** The author the write CLAIMED at queue time. Never trusted. */ + claimedAuthor: DashAuthor; + /** The validated write, exactly as validateNewAction produced it + * (its author is the claim). Released only under a verified author. */ + action: NewAction; + state: OutageQueueState; + /** Set when state leaves "queued". */ + resolvedAt?: string; + /** The actions-store id a confirmation released the write as. */ + resolvedActionId?: string; +} + +export interface OutageQueueFile { + version: 1; + writes: OutageQueuedWrite[]; +} + +/** The slice of the audit stream this module depends on (EventsStore). */ +export interface OutageQueueAuditSink { + record: (event: NewAuditEvent) => Promise; +} + +/** + * Whether a validated action write may be outage-queued. Eligibility + * is narrow on purpose: + * + * - The claimed author kind must be one a fresh Access login can + * derive ("drew" for the allowlisted owner, "agent" for any other + * verified identity — see deriveAuthorFromAccess). A "muse" claim + * has no Access derivation, so it could never be confirmed; it + * fails closed instead of stranding in the queue forever. + * - The four preference view verbs (save-view, rename-view, + * delete-view, set-default-view) are applied by the aggregator + * itself inside the POST request; a queue cannot honour that + * applied-in-request contract, so they fail closed during an + * outage. Every other action kind/verb is consumer-applied and + * queues. + * + * Comments are never routed here at all: the comment surface is + * gated on Drew's answer to design question 4 on #1253. + */ +const AGGREGATOR_APPLIED_VIEW_VERBS: ReadonlySet = new Set([ + "save-view", + "rename-view", + "delete-view", + "set-default-view", +]); + +export function outageQueueEligible(action: NewAction): boolean { + if (action.author.kind !== "drew" && action.author.kind !== "agent") return false; + if (action.kind === "preference" && AGGREGATOR_APPLIED_VIEW_VERBS.has(action.verb)) return false; + return true; +} + +/** + * Whether an address is on the stack-local network: loopback, the + * tailnet CGNAT range (100.64.0.0/10), RFC1918 private ranges, or + * IPv6 loopback / unique-local / link-local. The aggregator binds + * loopback + the tailnet address only, so every request it serves + * already arrived over one of those; this check is the fail-closed + * guard that keeps outage queueing from ever engaging if the server + * is bound somewhere wider. Unknown or missing addresses are NOT + * local. + */ +export function isStackLocalAddress(address: string | null | undefined): boolean { + if (typeof address !== "string" || address === "") return false; + let addr = address.trim().toLowerCase(); + // Strip an IPv6 zone id and brackets, if present. + const zone = addr.indexOf("%"); + if (zone >= 0) addr = addr.slice(0, zone); + if (addr.startsWith("[") && addr.endsWith("]")) addr = addr.slice(1, -1); + // IPv4-mapped IPv6 (::ffff:127.0.0.1) is judged as its IPv4 address. + if (addr.startsWith("::ffff:")) addr = addr.slice("::ffff:".length); + if (addr.includes(".")) { + const parts = addr.split("."); + if (parts.length !== 4) return false; + const octets = parts.map((p) => (/^\d{1,3}$/.test(p) ? Number(p) : NaN)); + if (octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false; + const [a, b] = octets as [number, number, number, number]; + if (a === 127) return true; // loopback 127.0.0.0/8 + if (a === 10) return true; // private 10.0.0.0/8 + if (a === 172 && b >= 16 && b <= 31) return true; // private 172.16.0.0/12 + if (a === 192 && b === 168) return true; // private 192.168.0.0/16 + if (a === 100 && b >= 64 && b <= 127) return true; // tailnet CGNAT 100.64.0.0/10 + if (a === 169 && b === 254) return true; // link-local 169.254.0.0/16 + return false; + } + if (addr === "::1" || addr === "::") return true; // IPv6 loopback / unspecified + if (addr.startsWith("fc") || addr.startsWith("fd")) return true; // unique-local fc00::/7 + if (/^fe[89ab]/.test(addr)) return true; // link-local fe80::/10 + return false; +} + +/** + * The confirmation binding: a fresh login confirms a claim only when + * the author DERIVED from its verified Access identity is the claimed + * author (kind + id). The label is display text and never part of the + * match; the released write carries the derived author, label and all. + */ +export function outageClaimMatchesAuthor(claimed: DashAuthor, derived: DashAuthor): boolean { + return claimed.kind === derived.kind && claimed.id === derived.id; +} + +function authorRef(author: DashAuthor): string { + return `${author.kind}:${author.id}`; +} + +export function outageWriteQueuedAuditEvent(write: OutageQueuedWrite): NewAuditEvent { + return { + actor: `claimed:${authorRef(write.claimedAuthor)}`, + kind: "outage-write-queued", + ref: write.action.objectRef, + summary: + `Outage-queued write held for identity confirmation: ${write.action.kind}/${write.action.verb} on ` + + `${write.action.objectRef}, claimed by ${authorRef(write.claimedAuthor)} (unverified claim, ` + + `provenance ${OUTAGE_QUEUED_PROVENANCE}, queue ${write.id})`, + attribution: { confidence: "unknown", asserted: true }, + source: { identity: "pm-aggregator", link: "#9608" }, + }; +} + +export function outageWriteConfirmedAuditEvent(input: { + write: OutageQueuedWrite; + derivedAuthor: DashAuthor; + actionId: string; +}): NewAuditEvent { + return { + actor: authorRef(input.derivedAuthor), + kind: "outage-write-confirmed", + ref: input.write.action.objectRef, + summary: + `Outage-queued write confirmed by a fresh verified login and released as action ${input.actionId}: ` + + `${input.write.action.kind}/${input.write.action.verb} on ${input.write.action.objectRef} ` + + `(queue ${input.write.id}, claimed by ${authorRef(input.write.claimedAuthor)})`, + attribution: { confidence: "authenticated", asserted: true }, + source: { identity: "pm-aggregator", link: "#9608" }, + }; +} + +export function outageWriteRejectedAuditEvent(input: { + write: OutageQueuedWrite; + derivedAuthor: DashAuthor; + byOwner: boolean; +}): NewAuditEvent { + return { + actor: authorRef(input.derivedAuthor), + kind: "outage-write-rejected", + ref: input.write.action.objectRef, + summary: + `Outage-queued write rejected ${input.byOwner ? "by the verified owner" : "by its claimant"}: ` + + `${input.write.action.kind}/${input.write.action.verb} on ${input.write.action.objectRef} ` + + `(queue ${input.write.id}, claimed by ${authorRef(input.write.claimedAuthor)})`, + attribution: { confidence: "authenticated", asserted: true }, + source: { identity: "pm-aggregator", link: "#9608" }, + }; +} + +function validateStoredAction(value: unknown, file: string): NewAction { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new Error(`invalid outage-queue action in ${file}`); + } + const action = value as Record; + const author = validateAuthor(action.author); + if ( + typeof action.clientToken !== "string" || + action.clientToken === "" || + typeof action.kind !== "string" || + typeof action.verb !== "string" || + typeof action.objectRef !== "string" || + action.objectRef === "" || + typeof action.payload !== "object" || + action.payload === null || + !author + ) { + throw new Error(`invalid outage-queue action in ${file}`); + } + return action as unknown as NewAction; +} + +function validateRecord(row: unknown, file: string): OutageQueuedWrite { + if (typeof row !== "object" || row === null || Array.isArray(row)) { + throw new Error(`invalid outage-queue record in ${file}`); + } + const value = row as Record; + const claimedAuthor = validateAuthor(value.claimedAuthor); + if ( + typeof value.id !== "string" || + value.id === "" || + typeof value.queuedAt !== "string" || + Number.isNaN(Date.parse(value.queuedAt)) || + value.provenance !== OUTAGE_QUEUED_PROVENANCE || + !claimedAuthor || + (value.state !== "queued" && value.state !== "confirmed" && value.state !== "rejected") || + (value.resolvedAt !== undefined && + (typeof value.resolvedAt !== "string" || Number.isNaN(Date.parse(value.resolvedAt)))) || + (value.resolvedActionId !== undefined && typeof value.resolvedActionId !== "string") + ) { + throw new Error(`invalid outage-queue record in ${file}`); + } + return { + id: value.id, + queuedAt: value.queuedAt, + provenance: OUTAGE_QUEUED_PROVENANCE, + claimedAuthor, + action: validateStoredAction(value.action, file), + state: value.state as OutageQueueState, + ...(typeof value.resolvedAt === "string" ? { resolvedAt: value.resolvedAt } : {}), + ...(typeof value.resolvedActionId === "string" ? { resolvedActionId: value.resolvedActionId } : {}), + }; +} + +export class OutageQueueStore { + private chain: Promise = Promise.resolve(); + + constructor(private readonly file: string) {} + + async list(): Promise { + return (await this.load()).writes; + } + + async get(id: string): Promise { + const current = await this.load(); + return current.writes.find((w) => w.id === id) ?? null; + } + + /** Find any record (any state) carrying this clientToken. */ + async byClientToken(clientToken: string): Promise { + const current = await this.load(); + return current.writes.find((w) => w.action.clientToken === clientToken) ?? null; + } + + async add(write: OutageQueuedWrite): Promise { + await this.serialize(async () => { + const current = await this.load(); + current.writes.push(write); + await this.persist(current); + }); + } + + /** + * Move a record out of "queued" exactly once, inside the serialized + * section: a record that already resolved (or does not exist) + * returns null and nothing is written. + */ + async resolve( + id: string, + resolution: { state: "confirmed" | "rejected"; resolvedAt: string; resolvedActionId?: string }, + ): Promise { + return this.serialize(async () => { + const current = await this.load(); + const record = current.writes.find((w) => w.id === id); + if (!record || record.state !== "queued") return null; + record.state = resolution.state; + record.resolvedAt = resolution.resolvedAt; + if (resolution.resolvedActionId !== undefined) record.resolvedActionId = resolution.resolvedActionId; + await this.persist(current); + return { ...record }; + }); + } + + private async serialize(fn: () => Promise): Promise { + let result!: T; + const run = this.chain.then(async () => { + result = await fn(); + }); + this.chain = run.then( + () => {}, + () => {}, + ); + await run; + return result; + } + + private async load(): Promise { + let raw: string; + try { + raw = await readFile(this.file, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, writes: [] }; + throw error; + } + const parsed = JSON.parse(raw) as OutageQueueFile; + if (parsed.version !== 1 || !Array.isArray(parsed.writes)) { + throw new Error(`invalid outage-queue file: ${this.file}`); + } + return { version: 1, writes: parsed.writes.map((row) => validateRecord(row, this.file)) }; + } + + private async persist(value: OutageQueueFile): Promise { + await mkdir(dirname(this.file), { recursive: true }); + const tmp = `${this.file}.${randomUUID()}.tmp`; + await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); + await rename(tmp, this.file); + } +} + +/** + * Queue a validated write under its claimed author. Idempotent by + * clientToken, mirroring the actions store: a repost of a token that + * is already in the queue (in any state) returns the existing record + * and writes nothing — no second record, no second audit event. For a + * new record the audit event is recorded BEFORE the record persists: + * if the audit write fails, nothing is queued (fail closed). + */ +export async function queueOutageWrite(input: { + store: OutageQueueStore; + events: OutageQueueAuditSink; + action: NewAction; + now?: Date; +}): Promise<{ record: OutageQueuedWrite; created: boolean }> { + const existing = await input.store.byClientToken(input.action.clientToken); + if (existing) return { record: existing, created: false }; + const record: OutageQueuedWrite = { + id: `oq_${randomUUID()}`, + queuedAt: (input.now ?? new Date()).toISOString(), + provenance: OUTAGE_QUEUED_PROVENANCE, + claimedAuthor: input.action.author, + action: input.action, + state: "queued", + }; + await input.events.record(outageWriteQueuedAuditEvent(record)); + await input.store.add(record); + return { record, created: true }; +} + +export type ReleaseOutageWrite = ( + action: NewAction, +) => Promise<{ ok: true; actionId: string } | { ok: false; status: number; error: string }>; + +export type ConfirmOutageWriteResult = + | { ok: true; record: OutageQueuedWrite; actionId: string } + | { ok: false; status: number; error: string }; + +/** + * Confirm a queued write against the author derived from a fresh + * verified login (the caller enforces the login; this function owns + * the claim match, the release, the audit, and the state move): + * + * - unknown id -> 404; already resolved -> 409; + * - derived author does not match the claim -> 403, nothing changes; + * - the release (the caller's actions-store add, with its item + * checks) fails -> its status/error, record stays queued; + * - the audit write fails -> 500, record stays queued — a retry is + * safe because the release dedupes by clientToken; + * - only after the audit lands is the record marked confirmed, with + * the released action id. + */ +export async function confirmOutageWrite(input: { + store: OutageQueueStore; + events: OutageQueueAuditSink; + id: string; + derivedAuthor: DashAuthor; + release: ReleaseOutageWrite; + now?: Date; +}): Promise { + const record = await input.store.get(input.id); + if (!record) return { ok: false, status: 404, error: "no such outage-queued write" }; + if (record.state !== "queued") { + return { ok: false, status: 409, error: `outage-queued write already ${record.state}` }; + } + if (!outageClaimMatchesAuthor(record.claimedAuthor, input.derivedAuthor)) { + return { + ok: false, + status: 403, + error: "the verified identity does not match the queued claim; only its claimant can confirm it", + }; + } + const released = await input.release({ + ...record.action, + author: input.derivedAuthor, + payload: { ...record.action.payload }, + }); + if (!released.ok) return { ok: false, status: released.status, error: released.error }; + try { + await input.events.record( + outageWriteConfirmedAuditEvent({ write: record, derivedAuthor: input.derivedAuthor, actionId: released.actionId }), + ); + } catch { + return { ok: false, status: 500, error: "outage-write confirmation audit write failed; the write stays queued" }; + } + const resolved = await input.store.resolve(record.id, { + state: "confirmed", + resolvedAt: (input.now ?? new Date()).toISOString(), + resolvedActionId: released.actionId, + }); + if (!resolved) { + return { ok: false, status: 409, error: "outage-queued write was resolved concurrently" }; + } + return { ok: true, record: resolved, actionId: released.actionId }; +} + +export type RejectOutageWriteResult = + | { ok: true; record: OutageQueuedWrite; byOwner: boolean } + | { ok: false; status: number; error: string }; + +/** + * Reject a queued write. The claimant rejects their own claim (same + * match as confirmation); a verified owner (a fresh login deriving + * the drew author) may reject any claim. The audit event is recorded + * before the state move: if it fails, the record stays queued. + */ +export async function rejectOutageWrite(input: { + store: OutageQueueStore; + events: OutageQueueAuditSink; + id: string; + derivedAuthor: DashAuthor; + now?: Date; +}): Promise { + const record = await input.store.get(input.id); + if (!record) return { ok: false, status: 404, error: "no such outage-queued write" }; + if (record.state !== "queued") { + return { ok: false, status: 409, error: `outage-queued write already ${record.state}` }; + } + const isClaimant = outageClaimMatchesAuthor(record.claimedAuthor, input.derivedAuthor); + const isOwner = input.derivedAuthor.kind === "drew" && input.derivedAuthor.id === "drew"; + if (!isClaimant && !isOwner) { + return { + ok: false, + status: 403, + error: "only the queued write's claimant (or the verified owner) can reject it", + }; + } + const byOwner = !isClaimant && isOwner; + try { + await input.events.record( + outageWriteRejectedAuditEvent({ write: record, derivedAuthor: input.derivedAuthor, byOwner }), + ); + } catch { + return { ok: false, status: 500, error: "outage-write rejection audit write failed; the write stays queued" }; + } + const resolved = await input.store.resolve(record.id, { + state: "rejected", + resolvedAt: (input.now ?? new Date()).toISOString(), + }); + if (!resolved) { + return { ok: false, status: 409, error: "outage-queued write was resolved concurrently" }; + } + return { ok: true, record: resolved, byOwner }; +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 7c0237c62b..ac69b59641 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -15,7 +15,7 @@ import { createQuotaRefresher, systemdTrigger } from "./quota-refresh.ts"; import { buildQuotaAnalytics, primeAttemptAggregates, type QuotaAnalytics } from "./analytics-store.ts"; import { decodePathSegment } from "./path-segment.ts"; import { errorBoundaryResponse, notFoundResponse } from "./error-boundary.ts"; -import { ACTION_STATES, ActionsStore, validateNewAction, type DashAction } from "./actions.ts"; +import { ACTION_STATES, ActionsStore, validateNewAction, type DashAction, type NewAction } from "./actions.ts"; import { checkActionAgainstItem, effectiveNeedsOrder, @@ -65,6 +65,15 @@ import { RoadmapAnnotationsStore, validateNewRoadmapAnnotation } from "./roadmap import { createAccessAuthorEnforcer, enforceAccessAuthor } from "./access-identity.ts"; import { IdentityRegistryStore, identityMappingAuditEvent, validateIdentityMapping } from "./identity-registry.ts"; import { BreakGlassTokenStore, authorizeWithBreakGlassToken, presentedBreakGlassToken } from "./break-glass.ts"; +import { + OutageQueueStore, + confirmOutageWrite, + isStackLocalAddress, + outageQueueEligible, + queueOutageWrite, + rejectOutageWrite, + type OutageQueuedWrite, +} from "./outage-queue.ts"; import { STACK_TOKEN_TTL_SECONDS, mintStackToken, type StackTokenRole } from "./stack-token.ts"; import { healthHookAuditEvent } from "./health-hook-audit-event.ts"; import { @@ -405,6 +414,28 @@ const eventsStore = new EventsStore(cfg.eventsFile); const reportRecordsLocation = storeRemotes?.aaLastGood ?? defaultReportRecordsFile(); const identityRegistryStore = new IdentityRegistryStore(cfg.identityRegistryFile); const breakGlassTokenStore = new BreakGlassTokenStore(cfg.breakGlassFile); +const outageQueueStore = new OutageQueueStore(cfg.outageQueueFile); + +/** + * #9608 (design #1253 section 6): the outage-queueing gate for action + * writes whose Access verification failed. Queueing engages only on + * the enforcer's 401 (verification failed — a 403 is a verified + * identity contradicting the claim, not an outage), only from a + * stack-local peer address, and only for eligible writes; anything + * else returns null and the caller serves the enforcer's refusal + * exactly as before. Throws when the queue/audit write itself fails — + * callers map that to a 500 (fail closed: nothing was queued). + */ +async function tryQueueOutageAction( + action: NewAction, + accessStatus: number, + remoteAddress: string | undefined, +): Promise<{ record: OutageQueuedWrite; created: boolean } | null> { + if (accessStatus !== 401) return null; + if (!isStackLocalAddress(remoteAddress)) return null; + if (!outageQueueEligible(action)) return null; + return queueOutageWrite({ store: outageQueueStore, events: eventsStore, action }); +} const freshnessStore = new FreshnessStore(cfg.freshnessFile); /** #3976: the 5-minute anti-entropy reconciler over the freshness @@ -2263,7 +2294,7 @@ const metadataWebhookHandler = createMetadataWebhookHandler({ }, }); -async function handler(req: Request): Promise { +async function handler(req: Request, remoteAddress?: string): Promise { const url = new URL(req.url); const path = url.pathname; const prov = () => source.provenance(); @@ -2815,7 +2846,34 @@ async function handler(req: Request): Promise { // #1253 slice: gate every action write, including non-triage and // preference actions, on the configured Access identity. const actionAccess = await enforceAccessAuthor(req, parsed.value.author); - if (!actionAccess.ok) return json({ error: actionAccess.error }, actionAccess.status); + if (!actionAccess.ok) { + // #9608 (design #1253 section 6): during an Access/IdP outage + // an eligible write from the stack-local network queues as an + // unverified claim (provenance: outage-queued) instead of + // failing — held out of the actions store until its claimant + // confirms it with a fresh login. Anything else keeps the + // enforcer's refusal, byte-identical to before. + try { + const queued = await tryQueueOutageAction(parsed.value, actionAccess.status, remoteAddress); + if (queued) { + return json( + { + queued: true, + provenance: "outage-queued", + queue: queued.record, + ...(queued.created ? {} : { deduped: true }), + }, + 202, + ); + } + } catch (err) { + return json( + { error: `outage queueing failed: ${err instanceof Error ? err.message : err}` }, + 500, + ); + } + return json({ error: actionAccess.error }, actionAccess.status); + } parsed.value.author = actionAccess.author; // #1291/#1293: checks that need the currently published item — // option/survey membership, required-question coverage, proposal @@ -2927,6 +2985,9 @@ async function handler(req: Request): Promise { ok: boolean; action?: unknown; deduped?: boolean; + // #9608: set when the item outage-queued instead of recording. + queued?: boolean; + queueId?: string; error?: string; }[] = []; // One enforcer for the whole batch: the request's JWT is @@ -2944,6 +3005,31 @@ async function handler(req: Request): Promise { } const batchAccess = await enforceBatchAuthor(parsed.value.author); if (!batchAccess.ok) { + // #9608: the single-action outage posture, per item — an + // eligible item queues as an unverified claim; the rest of + // the batch is unaffected. + try { + const queued = await tryQueueOutageAction(parsed.value, batchAccess.status, remoteAddress); + if (queued) { + results.push({ + index, + objectRef, + ok: true, + queued: true, + queueId: queued.record.id, + ...(queued.created ? {} : { deduped: true }), + }); + continue; + } + } catch (err) { + results.push({ + index, + objectRef, + ok: false, + error: `outage queueing failed: ${err instanceof Error ? err.message : err}`, + }); + continue; + } results.push({ index, objectRef, ok: false, error: batchAccess.error }); continue; } @@ -3013,6 +3099,106 @@ async function handler(req: Request): Promise { return json({ error: `invalid result: ${err instanceof Error ? err.message : err}` }, 400); } } + // --- Outage-queued action writes (#9608, design #1253 section 6) --- + // Queued writes appear ONLY on this read surface, stamped + // outage-queued with the claimed author kept a claim — never in + // /api/actions.json — until the claimant confirms one with a fresh + // verified login (confirm) or it is rejected (reject). + if (path === "/api/actions/outage-queue.json") { + const state = url.searchParams.get("state"); + if (state && state !== "queued" && state !== "confirmed" && state !== "rejected") { + return json({ error: "state must be one of: queued, confirmed, rejected" }, 400); + } + let list = await outageQueueStore.list(); + if (state) list = list.filter((w) => w.state === state); + return json({ queue: list }); + } + if (req.method === "POST" && path === "/api/actions/outage-queue/confirm") { + try { + const body = (await readJsonBody(req)) as { id?: unknown }; + if (typeof body.id !== "string" || body.id === "") return json({ error: "id required" }, 400); + const record = await outageQueueStore.get(body.id); + if (!record) return json({ error: "no such outage-queued write" }, 404); + // Confirmation IS a fresh login: the enforcer must succeed with + // a verified identity. The claimed author rides as the asserted + // author, so a verified non-owner presenting an owner claim is + // refused by the enforcer itself, exactly as on a fresh write. + const access = await enforceAccessAuthor(req, record.claimedAuthor); + if (!access.ok) return json({ error: access.error }, access.status); + if (!access.verified) { + return json({ error: "identity confirmation requires a fresh verified login" }, 403); + } + const result = await confirmOutageWrite({ + store: outageQueueStore, + events: eventsStore, + id: record.id, + derivedAuthor: access.author, + release: async (action) => { + // The released write passes the same published-item checks + // as a fresh POST /api/actions (see that route): the item + // may have changed while the write sat in the queue. + if (action.kind === "triage") { + const section = await source.orchestration().catch(() => null); + let item: ReturnType; + if (section) { + item = findTierItem(section, action.objectRef); + const problem = checkActionAgainstItem(action, item, Date.now()); + if (problem) return { ok: false as const, status: 400, error: problem }; + } + if (action.verb === "answer" && action.payload.optionId) { + action.payload.questionId = questionIdForOption(item, action.payload.optionId) ?? "$options"; + } + } + try { + const added = await actionsStore.add(action); + if (added.duplicateOf) { + return { + ok: false as const, + status: 409, + error: `duplicate answer recorded as ${added.action.id}; it points to existing answer action ${added.duplicateOf}`, + }; + } + return { ok: true as const, actionId: added.action.id }; + } catch (err) { + return { + ok: false as const, + status: 500, + error: `action persistence failed: ${err instanceof Error ? err.message : err}`, + }; + } + }, + }); + if (!result.ok) return json({ error: result.error }, result.status); + return json({ confirmed: true, queue: result.record, actionId: result.actionId }); + } catch (err) { + return json({ error: `invalid confirmation: ${err instanceof Error ? err.message : err}` }, 400); + } + } + if (req.method === "POST" && path === "/api/actions/outage-queue/reject") { + try { + const body = (await readJsonBody(req)) as { id?: unknown }; + if (typeof body.id !== "string" || body.id === "") return json({ error: "id required" }, 400); + const record = await outageQueueStore.get(body.id); + if (!record) return json({ error: "no such outage-queued write" }, 404); + // Same fresh-login gate as confirm; rejectOutageWrite owns the + // claimant/owner authorization for the rejection itself. + const access = await enforceAccessAuthor(req, record.claimedAuthor); + if (!access.ok) return json({ error: access.error }, access.status); + if (!access.verified) { + return json({ error: "rejecting a queued write requires a fresh verified login" }, 403); + } + const result = await rejectOutageWrite({ + store: outageQueueStore, + events: eventsStore, + id: record.id, + derivedAuthor: access.author, + }); + if (!result.ok) return json({ error: result.error }, result.status); + return json({ rejected: true, queue: result.record, byOwner: result.byOwner }); + } catch (err) { + return json({ error: `invalid rejection: ${err instanceof Error ? err.message : err}` }, 400); + } + } if (path === "/api/events.json") { // #1739/#3323: the same source-native stream and filters as /events. const pool = await source.projects().catch(() => [] as ProjectPoolItem[]); @@ -5059,14 +5245,14 @@ async function handler(req: Request): Promise { * attribution can never disagree. */ -async function fetchHandler(req: Request): Promise { +async function fetchHandler(req: Request, remoteAddress?: string): Promise { // #1211: the top-level error boundary. A throwing handler degrades // to a styled 500 page (JSON for /api) instead of rejecting the // fetch; the render-health record below still runs, accounting the // failure as an unsuccessful render. let res: Response; try { - res = await dashboardResponseWithinDeadline(req, () => handler(req)); + res = await dashboardResponseWithinDeadline(req, () => handler(req, remoteAddress)); } catch (err) { console.error(`aggregator: handler failed for ${req.method} ${req.url}:`, err); res = errorBoundaryResponse(new URL(req.url).pathname, err); @@ -5128,7 +5314,9 @@ const servers = cfg.hosts.map((hostname) => // the wait plus margin (Bun caps the value at 255). server.timeout(req, Math.min(255, Math.ceil(cfg.promptSyncTimeoutMs / 1000) + 5)); } - return fetchHandler(req); + // #9608: the peer address rides along so the outage-queueing + // path can require a stack-local origin (design #1253 §6). + return fetchHandler(req, server.requestIP(req)?.address); }, websocket: { open(ws) { diff --git a/pm-stack/aggregator/test/config.test.ts b/pm-stack/aggregator/test/config.test.ts index 0e45883a50..dae339e90f 100644 --- a/pm-stack/aggregator/test/config.test.ts +++ b/pm-stack/aggregator/test/config.test.ts @@ -19,6 +19,14 @@ describe("loadConfig mcpx call ledger", () => { }); }); +describe("loadConfig outage queue file (#9608)", () => { + test("uses the state-directory default and accepts an explicit file", () => { + const home = process.env.HOME ?? "/home/test"; + expect(loadConfig({ PM_AGG_DEV: "1" }).outageQueueFile).toBe(`${home}/.local/state/pm-aggregator/outage-queue.json`); + expect(loadConfig({ PM_AGG_DEV: "1", PM_AGG_OUTAGE_QUEUE_FILE: "/tmp/oq.json" }).outageQueueFile).toBe("/tmp/oq.json"); + }); +}); + describe("loadConfig stack-token secret", () => { test("is optional and trimmed", () => { expect(loadConfig({ PM_AGG_DEV: "1" }).stackTokenSecret).toBeNull(); diff --git a/pm-stack/aggregator/test/outage-queue-route-9608.test.ts b/pm-stack/aggregator/test/outage-queue-route-9608.test.ts new file mode 100644 index 0000000000..03358578f8 --- /dev/null +++ b/pm-stack/aggregator/test/outage-queue-route-9608.test.ts @@ -0,0 +1,185 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawn, type Subprocess } from "bun"; +import { existsSync, mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// #9608 route wiring for outage queueing (design #1253 section 6). +// Boots the real server with Access CONFIGURED: a write presented +// without a verifiable Access JWT is the outage case. From the +// loopback (stack-local) test client, an eligible write must queue +// as an unverified outage-queued claim — visible only on the queue +// surface, never in the actions store — while ineligible writes keep +// the enforcer's 401, and confirm/reject refuse without a fresh +// verified login, leaving the record queued. +let proc: Subprocess<"ignore", "pipe", "inherit"> | null = null; +let port = 0; +let actionsFile = ""; +let outageQueueFile = ""; +let queueId = ""; + +const DREW = { kind: "drew", id: "drew", label: "Drew" }; + +function actionBody(overrides: Record = {}): Record { + return { + clientToken: "tok-9608-route-1", + kind: "triage", + verb: "snooze", + objectRef: "gh:developing-today/code#9608", + payload: { until: "2026-11-24T00:00:00.000Z" }, + author: DREW, + ...overrides, + }; +} + +async function post(path: string, body: unknown): Promise { + return fetch(`http://127.0.0.1:${port}${path}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); +} + +beforeAll(async () => { + const dir = mkdtempSync(join(tmpdir(), "outage-queue-route-")); + actionsFile = join(dir, "actions.json"); + outageQueueFile = join(dir, "outage-queue.json"); + port = 5900 + Math.floor(Math.random() * 800); + proc = spawn({ + cmd: ["bun", "run", "src/server.ts"], + cwd: import.meta.dir + "/..", + env: { + ...Bun.env, + PM_AGG_PORT: String(port), + PM_AGG_FRESHNESS_PORT: String(port + 1000), + PM_AGG_SOURCE: "fixtures", + PM_AGG_STORE_BACKEND: "file", + PM_AGG_ACCESS_TEAM_DOMAIN: "team.cloudflareaccess.com", + PM_AGG_ACCESS_AUD: "aggregator-aud", + PM_AGG_OWNER_IDS: "drew@example.com", + PM_AGG_ACTIONS_FILE: actionsFile, + PM_AGG_OUTAGE_QUEUE_FILE: outageQueueFile, + PM_AGG_EVENTS_FILE: join(dir, "events.json"), + PM_AGG_IDENTITY_REGISTRY_FILE: join(dir, "identity-registry.json"), + PM_AGG_BREAK_GLASS_FILE: join(dir, "break-glass-tokens.json"), + PM_AGG_REPORT_RECORDS_FILE: join(dir, "report-records.jsonl"), + // The server opens its metadata DB at boot; in a clean venue the + // default state directory does not exist, so point it at the + // temp dir (the pre-existing boot suites rely on the laptop's + // state dir instead and fail without it — not this suite's bug). + PM_METADATA_DB_PATH: join(dir, "pm-metadata.sqlite"), + }, + stdout: "pipe", + stderr: "inherit", + }); + const deadline = Date.now() + 8000; + let ready = false; + while (Date.now() < deadline) { + try { + const res = await fetch(`http://127.0.0.1:${port}/api/health`); + if (res.ok) { + ready = true; + break; + } + } catch { + /* not up yet */ + } + await Bun.sleep(120); + } + expect(ready).toBe(true); +}, 60_000); + +afterAll(() => { + proc?.kill(); +}); + +describe("outage queueing routes (#9608)", () => { + test("an eligible write with no verifiable identity queues as an unverified claim (202), held out of the actions store", async () => { + const res = await post("/api/actions", actionBody()); + expect(res.status).toBe(202); + const body = (await res.json()) as { + queued: boolean; + provenance: string; + queue: { id: string; state: string; provenance: string; claimedAuthor: unknown }; + }; + expect(body.queued).toBe(true); + expect(body.provenance).toBe("outage-queued"); + expect(body.queue.state).toBe("queued"); + expect(body.queue.provenance).toBe("outage-queued"); + expect(body.queue.claimedAuthor).toEqual(DREW); + queueId = body.queue.id; + expect(queueId.startsWith("oq_")).toBe(true); + + // Held out of verified-authorship surfaces: the actions store — + // the consumers' poll — never sees it. + const actionsRes = await fetch(`http://127.0.0.1:${port}/api/actions.json?state=all`); + const actionsBody = (await actionsRes.json()) as { actions: Array<{ clientToken: string }> }; + expect(actionsBody.actions.some((a) => a.clientToken === "tok-9608-route-1")).toBe(false); + const actionsOnDisk = existsSync(actionsFile) ? readFileSync(actionsFile, "utf8") : ""; + expect(actionsOnDisk).not.toContain("tok-9608-route-1"); + const queueOnDisk = readFileSync(outageQueueFile, "utf8"); + expect(queueOnDisk).toContain("tok-9608-route-1"); + expect(queueOnDisk).toContain("outage-queued"); + + // The queue's own read surface shows the claim, and only there. + const queueRes = await fetch(`http://127.0.0.1:${port}/api/actions/outage-queue.json?state=queued`); + const queueBody = (await queueRes.json()) as { queue: Array<{ id: string; state: string }> }; + expect(queueBody.queue.map((w) => w.id)).toContain(queueId); + const bogus = await fetch(`http://127.0.0.1:${port}/api/actions/outage-queue.json?state=bogus`); + expect(bogus.status).toBe(400); + }, 30_000); + + test("ineligible writes fail closed with the enforcer's 401, exactly as before", async () => { + // A muse claim can never be confirmed by a fresh Access login. + const muse = await post( + "/api/actions", + actionBody({ clientToken: "tok-9608-route-2", author: { kind: "muse", id: "muse", label: "Muse" } }), + ); + expect(muse.status).toBe(401); + // The aggregator-applied view verbs cannot queue. + const view = await post( + "/api/actions", + actionBody({ + clientToken: "tok-9608-route-3", + kind: "preference", + verb: "delete-view", + payload: { viewId: "v1" }, + }), + ); + expect(view.status).toBe(401); + const queueRes = await fetch(`http://127.0.0.1:${port}/api/actions/outage-queue.json`); + const queueBody = (await queueRes.json()) as { queue: Array<{ action: { clientToken: string } }> }; + expect(queueBody.queue.some((w) => w.action.clientToken === "tok-9608-route-2")).toBe(false); + expect(queueBody.queue.some((w) => w.action.clientToken === "tok-9608-route-3")).toBe(false); + }, 30_000); + + test("a batch item queues per-item while the batch still answers 200", async () => { + const res = await post("/api/actions/batch", { + actions: [actionBody({ clientToken: "tok-9608-route-4" })], + }); + expect(res.status).toBe(200); + const body = (await res.json()) as { + results: Array<{ ok: boolean; queued?: boolean; queueId?: string }>; + failed: number; + }; + expect(body.results).toHaveLength(1); + expect(body.results[0]).toMatchObject({ ok: true, queued: true }); + expect(body.results[0]!.queueId!.startsWith("oq_")).toBe(true); + expect(body.failed).toBe(0); + // And it still never entered the actions store. + const actionsOnDisk = existsSync(actionsFile) ? readFileSync(actionsFile, "utf8") : ""; + expect(actionsOnDisk).not.toContain("tok-9608-route-4"); + }, 30_000); + + test("confirm and reject refuse without a fresh verified login; the write stays queued", async () => { + const confirm = await post("/api/actions/outage-queue/confirm", { id: queueId }); + expect(confirm.status).toBe(401); + const reject = await post("/api/actions/outage-queue/reject", { id: queueId }); + expect(reject.status).toBe(401); + const missing = await post("/api/actions/outage-queue/confirm", { id: "oq_missing" }); + expect(missing.status).toBe(404); + const queueRes = await fetch(`http://127.0.0.1:${port}/api/actions/outage-queue.json?state=queued`); + const queueBody = (await queueRes.json()) as { queue: Array<{ id: string; state: string }> }; + expect(queueBody.queue.find((w) => w.id === queueId)?.state).toBe("queued"); + }, 30_000); +}); diff --git a/pm-stack/aggregator/test/outage-queue.test.ts b/pm-stack/aggregator/test/outage-queue.test.ts new file mode 100644 index 0000000000..427b50b98c --- /dev/null +++ b/pm-stack/aggregator/test/outage-queue.test.ts @@ -0,0 +1,319 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { NewAction } from "../src/actions.ts"; +import { EventsStore } from "../src/events.ts"; +import type { NewAuditEvent } from "../src/events.ts"; +import type { DashAuthor } from "../src/model.ts"; +import { + OutageQueueStore, + confirmOutageWrite, + isStackLocalAddress, + outageQueueEligible, + queueOutageWrite, + rejectOutageWrite, +} from "../src/outage-queue.ts"; + +const dirs: string[] = []; +async function setup() { + const dir = await mkdtemp(join(tmpdir(), "outage-queue-")); + dirs.push(dir); + const queueFile = join(dir, "outage-queue.json"); + return { + dir, + queueFile, + events: new EventsStore(join(dir, "events.json")), + store: new OutageQueueStore(queueFile), + }; +} + +afterEach(async () => { + await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +const T0 = new Date("2026-11-23T06:00:00.000Z"); +const DREW: DashAuthor = { kind: "drew", id: "drew", label: "Drew" }; +const AGENT: DashAuthor = { kind: "agent", id: "access|member-17", label: "member@example.com" }; + +function newAction(overrides: Partial = {}): NewAction { + return { + clientToken: "tok-9608-unit-1", + kind: "triage", + verb: "snooze", + objectRef: "gh:developing-today/code#9608", + payload: { until: "2026-11-24T00:00:00.000Z" }, + author: DREW, + ...overrides, + }; +} + +// Oracle: design #1253 section 6 — during an entry/IdP outage, eligible +// writes queue stamped provenance: outage-queued with the claimed +// identity kept a claim, held out of verified-authorship surfaces +// until the claimant confirms by a fresh login (re-stamped verified) +// or rejects; asserted authorship as a fallback does not exist and +// anything else fails closed. +describe("aggregator outage queueing (#9608)", () => { + test("a queued write is stamped outage-queued, keeps the claim, and is audited before it persists", async () => { + const { store, queueFile } = await setup(); + let writesAtAuditTime = -1; + const events = { + record: async (_event: NewAuditEvent) => { + writesAtAuditTime = (await new OutageQueueStore(queueFile).list()).length; + }, + }; + const { record, created } = await queueOutageWrite({ store, events, action: newAction(), now: T0 }); + expect(created).toBe(true); + expect(writesAtAuditTime).toBe(0); + expect(record.provenance).toBe("outage-queued"); + expect(record.state).toBe("queued"); + expect(record.claimedAuthor).toEqual(DREW); + expect(record.action.author).toEqual(DREW); + expect(record.queuedAt).toBe(T0.toISOString()); + // A fresh store instance reads the same record back from disk. + expect(await new OutageQueueStore(queueFile).get(record.id)).toMatchObject({ id: record.id, state: "queued" }); + }); + + test("the queued audit event names the claim as unverified", async () => { + const { store, events } = await setup(); + const { record } = await queueOutageWrite({ store, events, action: newAction(), now: T0 }); + const listed = await events.list({ kind: "outage-write-queued" }); + expect(listed).toHaveLength(1); + expect(listed[0]).toMatchObject({ + actor: "claimed:drew:drew", + ref: "gh:developing-today/code#9608", + attribution: { confidence: "unknown", asserted: true }, + }); + expect(listed[0]!.summary).toContain(record.id); + expect(listed[0]!.summary).toContain("outage-queued"); + }); + + test("if the audit write fails, nothing is queued (fail closed)", async () => { + const { store } = await setup(); + const events = { + record: async (_event: NewAuditEvent) => { + throw new Error("events store unavailable"); + }, + }; + await expect(queueOutageWrite({ store, events, action: newAction(), now: T0 })).rejects.toThrow( + "events store unavailable", + ); + expect(await store.list()).toHaveLength(0); + }); + + test("queueing is idempotent by clientToken: a repost returns the existing record, unaudited twice", async () => { + const { store, events } = await setup(); + const first = await queueOutageWrite({ store, events, action: newAction(), now: T0 }); + const second = await queueOutageWrite({ store, events, action: newAction(), now: T0 }); + expect(second.created).toBe(false); + expect(second.record.id).toBe(first.record.id); + expect(await store.list()).toHaveLength(1); + expect(await events.list({ kind: "outage-write-queued" })).toHaveLength(1); + }); + + test("eligibility: confirmable claims and consumer-applied writes queue; the rest fail closed", () => { + expect(outageQueueEligible(newAction())).toBe(true); // drew, triage + expect(outageQueueEligible(newAction({ author: AGENT }))).toBe(true); // agent claim + expect( + outageQueueEligible(newAction({ kind: "status-request", verb: "request-status", payload: { status: "x" } })), + ).toBe(true); + expect( + outageQueueEligible( + newAction({ kind: "preference", verb: "set-delegation-default", payload: { standingAuto: true } }), + ), + ).toBe(true); + // A muse claim has no Access derivation, so it can never be confirmed. + expect(outageQueueEligible(newAction({ author: { kind: "muse", id: "muse", label: "Muse" } }))).toBe(false); + // The aggregator-applied view verbs cannot honour their contract from a queue. + expect( + outageQueueEligible(newAction({ kind: "preference", verb: "delete-view", payload: { viewId: "v1" } })), + ).toBe(false); + expect( + outageQueueEligible( + newAction({ kind: "preference", verb: "save-view", payload: { viewName: "V", viewFilters: {} } }), + ), + ).toBe(false); + }); + + test("stack-local addresses: loopback, tailnet, and private ranges only", () => { + for (const local of [ + "127.0.0.1", + "127.0.0.53", + "::1", + "::ffff:127.0.0.1", + "100.99.113.103", // amd-6 tailnet + "100.64.0.1", + "100.127.255.255", + "10.0.0.3", + "172.16.0.9", + "172.31.255.255", + "192.168.1.5", + "fd7a:115c:a1e0::1", + "fe80::1", + ]) { + expect(isStackLocalAddress(local)).toBe(true); + } + for (const remote of [ + "8.8.8.8", + "100.128.0.1", // just outside the CGNAT /10 + "100.63.255.255", + "172.32.0.1", + "192.167.0.1", + "203.0.113.9", + "", + "not-an-address", + undefined, + null, + ]) { + expect(isStackLocalAddress(remote)).toBe(false); + } + }); + + test("confirmation releases the write under the VERIFIED author and marks the record confirmed", async () => { + const { store, events } = await setup(); + const { record } = await queueOutageWrite({ store, events, action: newAction(), now: T0 }); + let releasedAction: NewAction | null = null; + const result = await confirmOutageWrite({ + store, + events, + id: record.id, + derivedAuthor: { kind: "drew", id: "drew", label: "Drew (verified)" }, + release: async (action) => { + releasedAction = action; + return { ok: true, actionId: "da-released-1" }; + }, + now: T0, + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.actionId).toBe("da-released-1"); + expect(result.record.state).toBe("confirmed"); + expect(result.record.resolvedActionId).toBe("da-released-1"); + } + // The re-stamp: the released action carries the derived author, + // not the claim (the claim's label differs and must not survive). + expect(releasedAction).not.toBeNull(); + expect(releasedAction!.author).toEqual({ kind: "drew", id: "drew", label: "Drew (verified)" }); + expect(releasedAction!.clientToken).toBe("tok-9608-unit-1"); + const confirmations = await events.list({ kind: "outage-write-confirmed" }); + expect(confirmations).toHaveLength(1); + expect(confirmations[0]).toMatchObject({ actor: "drew:drew", attribution: { confidence: "authenticated" } }); + // A second confirmation is refused: the record already resolved. + const again = await confirmOutageWrite({ + store, + events, + id: record.id, + derivedAuthor: DREW, + release: async () => ({ ok: true, actionId: "da-other" }), + now: T0, + }); + expect(again).toMatchObject({ ok: false, status: 409 }); + }); + + test("confirmation by a different identity is refused and the write stays queued", async () => { + const { store, events } = await setup(); + const { record } = await queueOutageWrite({ store, events, action: newAction({ author: AGENT }), now: T0 }); + let releaseCalled = false; + const result = await confirmOutageWrite({ + store, + events, + id: record.id, + derivedAuthor: DREW, // the owner is not this claim's claimant + release: async () => { + releaseCalled = true; + return { ok: true, actionId: "da-nope" }; + }, + now: T0, + }); + expect(result).toMatchObject({ ok: false, status: 403 }); + expect(releaseCalled).toBe(false); + expect((await store.get(record.id))?.state).toBe("queued"); + expect(await events.list({ kind: "outage-write-confirmed" })).toHaveLength(0); + }); + + test("a failed release leaves the write queued; an unknown id is a 404", async () => { + const { store, events } = await setup(); + const { record } = await queueOutageWrite({ store, events, action: newAction(), now: T0 }); + const failed = await confirmOutageWrite({ + store, + events, + id: record.id, + derivedAuthor: DREW, + release: async () => ({ ok: false, status: 400, error: "item check failed" }), + now: T0, + }); + expect(failed).toMatchObject({ ok: false, status: 400, error: "item check failed" }); + expect((await store.get(record.id))?.state).toBe("queued"); + const missing = await confirmOutageWrite({ + store, + events, + id: "oq_missing", + derivedAuthor: DREW, + release: async () => ({ ok: true, actionId: "da-x" }), + now: T0, + }); + expect(missing).toMatchObject({ ok: false, status: 404 }); + }); + + test("if the confirmation audit write fails, the write stays queued (a retry is safe)", async () => { + const { store } = await setup(); + const { record } = await queueOutageWrite({ + store, + events: { record: async () => {} }, + action: newAction(), + now: T0, + }); + const failingEvents = { + record: async (_event: NewAuditEvent) => { + throw new Error("audit sink down"); + }, + }; + const result = await confirmOutageWrite({ + store, + events: failingEvents, + id: record.id, + derivedAuthor: DREW, + release: async () => ({ ok: true, actionId: "da-released-1" }), + now: T0, + }); + expect(result).toMatchObject({ ok: false, status: 500 }); + expect((await store.get(record.id))?.state).toBe("queued"); + }); + + test("rejection: the claimant rejects; the owner may reject another's claim; a stranger may not", async () => { + const { store, events } = await setup(); + const own = await queueOutageWrite({ + store, + events, + action: newAction({ clientToken: "tok-9608-unit-own" }), + now: T0, + }); + const ownResult = await rejectOutageWrite({ store, events, id: own.record.id, derivedAuthor: DREW, now: T0 }); + expect(ownResult).toMatchObject({ ok: true, byOwner: false }); + expect((await store.get(own.record.id))?.state).toBe("rejected"); + + const agents = await queueOutageWrite({ + store, + events, + action: newAction({ clientToken: "tok-9608-unit-agent", author: AGENT }), + now: T0, + }); + const stranger = await rejectOutageWrite({ + store, + events, + id: agents.record.id, + derivedAuthor: { kind: "agent", id: "access|someone-else", label: "Other" }, + now: T0, + }); + expect(stranger).toMatchObject({ ok: false, status: 403 }); + expect((await store.get(agents.record.id))?.state).toBe("queued"); + const byOwner = await rejectOutageWrite({ store, events, id: agents.record.id, derivedAuthor: DREW, now: T0 }); + expect(byOwner).toMatchObject({ ok: true, byOwner: true }); + expect((await store.get(agents.record.id))?.state).toBe("rejected"); + const rejections = await events.list({ kind: "outage-write-rejected" }); + expect(rejections).toHaveLength(2); + expect(rejections.some((e) => e.summary.includes("by the verified owner"))).toBe(true); + expect(rejections.some((e) => e.summary.includes("by its claimant"))).toBe(true); + }); +});