// #1873 CB4: the revoke of an agent copy's credential binding, for every lifecycle event that ends it // (design docs/plans/2026-11-11_copy-credential-binding-design.md sections 3 and 6). // // One job per copy, in this order, and no lock held across any step: // 1. close the launch gate shuts the copy: no admission, every call refuses (sync, before any // await, so a launch that has not been admitted yet never escapes the stop inventory); // 2. begin the writer records the pending op (`revoking`, a fresh op id) or joins the one pending; // 3. drain the gate aborts the copy's requests in flight and waits for each to settle; // 4. stop every ordinary and thread run of the copy is ended, and the job waits for each run's // end to be acknowledged; // 5. slot the copy's slot file goes; // 6. remote the grant is revoked at the service through the organization's managed adapter, or // recorded `not-managed` when the organization has none; // 7. finish the writer records the unbound tombstone when every step was definite, or keeps the // record revoking with the steps that were not. Only a definite finish reopens the gate // (to the tombstone's own code); the stop is confirmed before that, always. // A throw at any step leaves the record revoking: resume() at the next start runs the same op id // again. Nothing in between resolves, launches or reloads the copy's token. `hooks` are for tests: // hooks[name]() runs at each named point and may throw to simulate a crash there. // // `gate` is the launch gate, or business => gate|null when only some organizations have one (the // gate holds one organization's copies). sweep() also finds a copy a named instance now shadows: the // name is in the file's roles, and its former copy's record is not a finished tombstone. import { BusError } from './broker.mjs'; import { COPY_BINDABLE } from '../../organization/src/agent-copies.mjs'; import { copyBotLogin } from '../../organization/src/copy-bindings.mjs'; import { boundRepositories } from './copy-grant.mjs'; import { giteaGrant } from './gitea-grant.mjs'; import { organizationWriter } from '../../organization/src/organization.mjs'; import { readOrgEntrySync } from '../../organization/src/org-registry.mjs'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; export const REVOKE_POINTS = Object.freeze([ 'beforePublication', 'afterPublication', 'beforeStop', 'afterStop', 'beforeSecret', 'afterSecret', 'beforeRemote', 'afterRemote', 'beforeReceipt', 'afterReceipt', ]); const OWNER_CAUSES = ['revoke', 'unbind']; const definite = (e) => typeof e?.code === 'string' && /^[a-z][a-z0-9-]{1,80}$/.test(e.code) && !e.code.startsWith('outcome-unknown'); export function copyRevoker({ writer, gate = null, credentials, stopRuns, remote = null, definitions = () => ({}), hooks = {} }) { const jobs = new Map(); const gateOf = (business) => (typeof gate === 'function' ? gate(business) : gate) ?? null; const tombstone = (r) => r?.state === 'unbound' && r.revoke?.done === true; const doc = (business) => { try { return writer.read(business).document; } catch { return null; } }; const hook = async (name) => { if (typeof hooks[name] === 'function') await hooks[name](); }; const slot = (business, instance) => business + '/' + instance; async function job(business, instance, { cause, actor = 'bus', owner = false, expect = undefined }) { const gate = gateOf(business); const wasClosed = gate?.closed?.(business, instance) ?? false; gate?.close(business, instance); let begun; try { await hook('beforePublication'); begun = writer.revokeCopyBinding(business, { phase: 'begin', instance, cause, ...(expect ? { expect } : {}) }, { actor, owner, definitions: definitions(business) }); } catch (e) { // An owner's verb refused before any change leaves the copy as it was; a loss the bus found // keeps it closed whatever the writer said. if (definite(e) && !wasClosed && OWNER_CAUSES.includes(cause)) gate?.open(business, instance, true); throw e; } await hook('afterPublication'); if (begun.state !== 'revoking') { gate?.open(business, instance); return begun; } const op = begun.op; const record = writer.read(business).document.copyBindings?.[instance]; if (record?.state !== 'revoking' || record.revoke?.id !== op) throw new BusError('credential-binding-changed'); await gate?.drain(business, instance); await hook('beforeStop'); let stop = 'failed'; try { const r = await stopRuns(business, instance, { op, cause: record.revoke.cause }); if (r?.confirmed === true) stop = 'confirmed'; } catch { stop = 'failed'; } await hook('afterStop'); // The gate is closed and drained: nothing reads the slot again, whether or not every run has // acknowledged its end yet. The record stays revoking until it has. await hook('beforeSecret'); let secret = 'absent'; for (const service of [...new Set([...Object.keys(record.services ?? {}), ...COPY_BINDABLE])].sort()) { let r; try { r = credentials.discardCopy(slot(business, instance), service); } catch { r = 'failed'; } if (r === 'failed') secret = 'failed'; else if (r === 'removed' && secret !== 'failed') secret = 'removed'; } await hook('afterSecret'); await hook('beforeRemote'); const outcomes = {}; for (const service of Object.keys(record.services ?? {}).sort()) { if (typeof record.services[service]?.grantId !== 'string') { outcomes[service] = 'absent'; continue; } // An earlier pass of this op already revoked it at the service. if (record.revoke?.remote?.[service] === 'revoked') { outcomes[service] = 'revoked'; continue; } if (typeof remote !== 'function') { outcomes[service] = 'not-managed'; continue; } try { outcomes[service] = await remote(business, instance, record, service); } catch { outcomes[service] = 'failed'; } if (!['revoked', 'absent', 'not-managed', 'failed'].includes(outcomes[service])) outcomes[service] = 'failed'; } await hook('afterRemote'); await hook('beforeReceipt'); const done = writer.revokeCopyBinding(business, { phase: 'finish', instance, opId: op, steps: { stop, slot: secret, remote: outcomes } }, { actor: 'bus', owner: true, definitions: definitions(business) }); await hook('afterReceipt'); if (done.state === 'unbound') gate?.open(business, instance); else gate?.close(business, instance, 'credential-revoke-failed'); return { ...done, steps: { stop, slot: secret, remote: outcomes } }; } const revoker = { // Run (or join) the copy's revoke and wait for it. Refusals propagate. run(business, instance, opts) { const key = business + '/' + instance; if (jobs.has(key)) return jobs.get(key); const p = job(business, instance, opts).finally(() => jobs.delete(key)); jobs.set(key, p); return p; }, // Fire and forget, for a loss the gate found: the job's outcome is in the record and its receipt. start(business, instance, opts) { revoker.run(business, instance, opts).catch(() => {}); }, has: (business, instance) => jobs.has(business + '/' + instance), // The copy's live binding record (pending, bound or revoking), or null. An unreadable file is null: // the verbs then take their ordinary path, which refuses on the same read. binding(business, instance) { const r = doc(business)?.copyBindings?.[instance]; return r && ['pending', 'bound', 'revoking'].includes(r.state) ? r : null; }, // True while the name's former copy still holds a record that is not a finished tombstone, or its // revoke runs: its slot is not the named instance's yet. An unreadable file answers true. pending(business, instance) { if (jobs.has(business + '/' + instance)) return true; const d = doc(business); if (d === null) return true; const r = d.copyBindings?.[instance]; return r !== undefined && !tombstone(r); }, // The gate's checks for every copy holding a grant, and each shadowed name's cleanup. Returns // nothing; each loss starts its revoke. sweep(business) { try { gateOf(business)?.sweep(business); } catch {} const d = doc(business); if (d === null) return; for (const [instance, r] of Object.entries(d.copyBindings ?? {})) if (Object.hasOwn(d.roles ?? {}, instance) && !tombstone(r) && r.state !== 'revoking') revoker.start(business, instance, { cause: 'shadowed', actor: 'bus' }); }, // Every revoke a previous run of the bus left pending, run again with its own op id. The owner // authorized an owner cause when it began; the host finishes it. Returns the settled outcomes. async resume(business) { const d = doc(business); if (d === null) return []; const pending = Object.entries(d.copyBindings ?? {}).filter(([, r]) => r?.state === 'revoking'); // A pass that already failed a step keeps its failure code while it runs again. for (const [instance, r] of pending) gateOf(business)?.close(business, instance, r.revoke?.failed ? 'credential-revoke-failed' : undefined); return Promise.allSettled(pending.map(([instance, r]) => revoker.run(business, instance, { cause: r.revoke.cause, actor: 'bus', owner: true }))); }, }; return Object.freeze(revoker); } // The remote step for a Gitea grant, through the organization's managed admin slot (row 236's): the // copy's token is deleted by id from its bot user. 204 is `revoked`, 404 `absent`. With no admin slot, // or one on another server than the binding's projects, the organization does not manage the copy's // Gitea and the step is `not-managed`: the record says so and never claims the token is gone. Any // other answer, an admin slot that fails its checks, a server that cannot be reached, bound projects // whose server can no longer be read from the organization file, or a record whose organization // incarnation is not the live organization's (`incarnation`, business => string|null) is `failed`, // and the copy stays fenced until a later pass revokes it. export function giteaCopyRemote({ grant, read, incarnation = null, today = () => new Date().toISOString().slice(0, 10) }) { return async (business, instance, record, service) => { if (service !== 'gitea' || !grant) return 'not-managed'; const m = /^gitea:(\d+):(\d+)$/.exec(record.services?.gitea?.grantId ?? ''); if (!m) return 'failed'; let origin; try { origin = boundRepositories(read(business), record.services.gitea.resources?.projects).origin; } catch { return 'failed'; } if (typeof incarnation === 'function') { let live = null; try { live = incarnation(business); } catch {} if (typeof live !== 'string' || live !== record.orgIncarnation) return 'failed'; } let admin; try { admin = grant.admin(business, (op, run) => run()); } catch (e) { return e?.code === 'grant-admin-missing' ? 'not-managed' : 'failed'; } let adminOrigin = null; try { adminOrigin = new URL(admin.meta.url).origin; } catch {} if (adminOrigin !== origin) return 'not-managed'; if (admin.meta.rotateBy < today()) return 'failed'; const login = copyBotLogin(record.orgIncarnation, record.copyId, 'gitea'); if (!login) return 'failed'; try { await grant.adminChecks(admin.api, admin.meta.account); const r = await admin.api.tokenDelete(login, m[2]); if (r?.status === 204 || r?.status === 200) return 'revoked'; if (r?.status === 404) return 'absent'; return 'failed'; } catch { return 'failed'; } }; } // The managed remote step outside a running bus, for archive and delete from the CLI or the Console: // the organization's Gitea admin slot, its file and its registry incarnation, each read when the // step runs. `transport` and `ca` are the scratch tests' (giteaGrant's own options). const ROLES_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '../../../roles'); export function managedCopyRemote({ configDir, dataRoot, transport = undefined, ca = undefined }) { const writer = organizationWriter({ dir: configDir, rolesDir: ROLES_DIR, dataRoot }); return giteaCopyRemote({ grant: giteaGrant({ configDir, ...(transport ? { transport, ca } : {}) }), read: (id) => writer.read(id).document, incarnation: (id) => readOrgEntrySync(configDir, id)?.incarnation ?? null, }); }