diff --git a/service/src/bridge/checkpoint-proof.test.ts b/service/src/bridge/checkpoint-proof.test.ts index 55be6588..42f581da 100644 --- a/service/src/bridge/checkpoint-proof.test.ts +++ b/service/src/bridge/checkpoint-proof.test.ts @@ -135,10 +135,10 @@ async function fixture({ seedCommitment = true } = {}) { await store.acknowledgeLease(id, incarnationId, assignmentId, assignment.generation, assignment.leaseToken); const lease = { protocolVersion: 1, incarnationId, generation: assignment.generation, leaseToken: assignment.leaseToken } as const; const settlement = { ...lease, status: 'fulfilled', result: creation } as const; - if (seedCommitment) await store.settle(id, assignmentId, settlement, undefined, auth.identityId, false, ticket); + if (seedCommitment) await store.settle(id, assignmentId, settlement, undefined, auth.identityId, false, ticket, auth); const seal = async () => { await store.confirmWorkspaceCleanup(id, assignmentId, { ...lease, status: 'rejected', error: 'local cleanup' }, - undefined, auth.identityId, ticket); + undefined, auth.identityId, ticket, auth); const active = 'codeapi:workspace-requests:v1:active'; for (const key of await client.zrange(active, 0, -1)) await client.zadd(active, 0, key); await requests.reconcile(); diff --git a/service/src/bridge/checkpoint.ts b/service/src/bridge/checkpoint.ts index fc514eb1..828ff740 100644 --- a/service/src/bridge/checkpoint.ts +++ b/service/src/bridge/checkpoint.ts @@ -1,4 +1,5 @@ import type { BridgeSettlement } from '../../../packages/code/src/protocol'; +import { credentialDigestKey, workerIdentityKey } from './pairing'; /** Private receipt data. Admission/negotiation must write this alongside the * exact ownership metadata and epoch; no production path enrolls it yet. */ @@ -16,7 +17,7 @@ export interface CheckpointCandidate { } export function isCheckpointDigest(value: string | undefined): value is string { - return value != null && value.length === 64 && /^[a-f0-9]+$/.test(value); + return typeof value === 'string' && value.length === 64 && /^[a-f0-9]+$/.test(value); } /** Internal HTTP sidecar, not part of the shared BridgeSettlement protocol. */ @@ -74,6 +75,12 @@ export interface CheckpointContext { keys: string[]; args: string[]; epoch: string; + authority?: { + workerId: string; + activeCredentialId: string; + // Only worker-originated votes have a signing credential. + credentialId?: string; + }; } type CheckpointVote = @@ -82,13 +89,16 @@ type CheckpointVote = | { kind: 'finalization'; digest: string; key: string; outcome: string; assignment: string }; /** Append an advisory transition to an existing Redis CAS. The caller still - * owns all normal commit, cleanup and release decisions. Keys/args match the - * layout constructed by RedisBridgeStore.checkpointContext. */ + * owns all normal commit, cleanup and release decisions. The shared receipt + * context occupies keys 1..10 and args 1..9; authority and vote data follow. */ export function checkpointTransition( keys: string[], args: (string | number)[], context: CheckpointContext | undefined, vote: CheckpointVote, ): string[] { - if (context == null || (vote.kind !== 'finalization' && - (vote.candidate.epoch !== context.epoch || !isCheckpointDigest(vote.candidate.commitment)))) return []; + if (context?.authority == null || (vote.kind !== 'finalization' && + (vote.candidate.epoch !== context.epoch || + !isCheckpointDigest(vote.candidate.commitment)))) return []; + const { workerId, activeCredentialId, credentialId } = context.authority; + if (vote.kind !== 'finalization' && credentialId == null) return []; const keyOffset = keys.length; const argOffset = args.length; const k = (i: number) => `KEYS[${keyOffset + i}]`; @@ -97,31 +107,55 @@ export function checkpointTransition( const field = (name: string) => `redis.pcall('HGET', ${receipt}, '${name}')`; const get = (i: number) => `redis.pcall('GET', ${k(i)})`; const put = (name: string, value: string) => `redis.call('HSET', ${receipt}, '${name}', ${value})`; - const value = a(10); - if (vote.kind === 'finalization') keys.push(...context.keys, vote.key); - else if (vote.kind === 'settlement') keys.push(...context.keys, vote.ackKey); - else keys.push(...context.keys); - args.push(...context.args, ...(vote.kind === 'finalization' ? [vote.digest, vote.outcome, vote.assignment] - : vote.kind === 'settlement' ? [vote.candidate.commitment, vote.digest] : [vote.candidate.commitment])); + const activeId = a(10); + const worker = a(11); + const value = a(12); + keys.push(...context.keys, workerIdentityKey(workerId), credentialDigestKey(activeCredentialId)); + args.push(...context.args, activeCredentialId, workerId); + if (vote.kind === 'finalization') { + keys.push(vote.key); + args.push(vote.digest, vote.outcome, vote.assignment); + } else { + // Even during rotation grace, the signing and active credentials can differ. + keys.push(credentialDigestKey(credentialId ?? activeCredentialId)); + args.push(vote.candidate.commitment); + if (vote.kind === 'settlement') { + keys.push(vote.ackKey); + args.push(vote.digest); + } + } // The optional reads use pcall and fail closed on wrong types. No proof // writes can create a receipt, and HSET leaves its original expiry intact. return [ 'do', + ' local function credentialMatches(raw)', + " if type(raw) ~= 'string' or #raw > 8192 then return false end", + ' local ok, credential = pcall(cjson.decode, raw)', + " return ok and type(credential) == 'table' and type(credential.binding) == 'table'", + ` and credential.workerId == ${worker} and credential.identityId == ${a(6)} and credential.binding.tenantId == ${a(8)}`, + ' end', ' local function eligible()', - ` if ${field('metadata')} ~= ${a(1)} or ${field('checkpointAdmissionV1')} ~= ${a(2)} or ${field('epoch')} ~= ${a(3)} then return false end`, + ` if ${field('metadata')} ~= ${a(1)} or ${field('checkpointAdmissionV1')} ~= ${a(2)} or ${field('epoch')} ~= ${a(3)} or redis.call('PTTL', ${receipt}) <= 0 then return false end`, ` if ${get(2)} ~= ${a(3)} or ${get(3)} ~= ${a(4)} or redis.call('EXISTS', ${k(4)}) ~= 0 then return false end`, ` if ${get(5)} ~= ${a(5)} or ${get(6)} ~= ${a(6)} then return false end`, ` if (${get(7)} or '0') ~= ${a(7)} or redis.call('EXISTS', ${k(8)}, ${k(9)}) ~= 0 then return false end`, + ` if ${get(11)} ~= ${activeId} or not credentialMatches(${get(12)}) then return false end`, + ...(vote.kind === 'settlement' ? [] : [ + ` if ${field('checkpointActiveCredentialId')} ~= ${activeId} then return false end`, + ]), + ...(vote.kind === 'finalization' || credentialId === activeCredentialId ? [] : [ + ` if not credentialMatches(${get(13)}) then return false end`, + ]), ` local raw = ${get(10)}`, " if type(raw) ~= 'string' then return false end", ' local ok, registration = pcall(cjson.decode, raw)', " return ok and type(registration) == 'table' and type(registration.binding) == 'table'", - ` and registration.incarnationId == ${a(5)} and registration.identityId == ${a(6)} and registration.binding.tenantId == ${a(8)}`, + ` and registration.workerId == ${worker} and registration.incarnationId == ${a(5)} and registration.identityId == ${a(6)} and registration.binding.tenantId == ${a(8)}`, ' end', ` if eligible() and ${field('checkpointCertificateV1')} == false then`, ...(vote.kind === 'settlement' ? [ - ` if ${get(11)} == ${a(4)} and ${field('checkpointCommitment')} == false and ${field('localCleanup')} == false then`, - ` redis.call('HSET', ${receipt}, 'checkpointCommitment', ${value}, 'checkpointSettlementDigest', ${a(11)}, 'checkpointReceiptDigest', ${a(9)})`, + ` if ${get(14)} == ${a(4)} and ${field('checkpointCommitment')} == false and ${field('localCleanup')} == false then`, + ` redis.call('HSET', ${receipt}, 'checkpointCommitment', ${value}, 'checkpointSettlementDigest', ${a(13)}, 'checkpointReceiptDigest', ${a(9)}, 'checkpointActiveCredentialId', ${activeId})`, ' end', ] : [ ` local commitment = ${field('checkpointCommitment')}`, @@ -133,9 +167,9 @@ export function checkpointTransition( ` ${put('checkpointCleanupVote', 'digest')}`, ] : [ ` digest == ${value} and ${field('resultCommitted')} == false and`, - ` redis.pcall('HGET', ${k(11)}, 'state') == 'completed' and`, - ` redis.pcall('HGET', ${k(11)}, 'outcome') == ${a(11)} and`, - ` redis.pcall('HGET', ${k(11)}, 'assignment') == ${a(12)} then`, + ` redis.pcall('HGET', ${k(13)}, 'state') == 'completed' and`, + ` redis.pcall('HGET', ${k(13)}, 'outcome') == ${a(13)} and`, + ` redis.pcall('HGET', ${k(13)}, 'assignment') == ${a(14)} then`, ` ${put('checkpointFinalizationVote', 'digest')}`, ]), ` if ${field('checkpointCleanupVote')} == digest and ${field('checkpointFinalizationVote')} == digest then`, diff --git a/service/src/bridge/store.ts b/service/src/bridge/store.ts index 8e8940dc..bdd53cf6 100644 --- a/service/src/bridge/store.ts +++ b/service/src/bridge/store.ts @@ -34,7 +34,7 @@ import { hasLaneGit, laneGitPolicy } from './lane-git'; import { BridgeAdmissionQueue, durableAdmissionFence, durableQueuedClaimFence } from './admission'; import type { DurableWorkspaceGuard } from './admission'; import { BridgeWorkspaceSlots } from './slots'; -import type { CheckpointCandidate, CheckpointContext } from './checkpoint'; +import type { CheckpointAdmission, CheckpointCandidate, CheckpointContext } from './checkpoint'; import type { CheckpointProof, CheckpointProofDurability, CheckpointProofRequest } from './checkpoint-proof'; import { readCheckpointProof } from './checkpoint-proof'; import { checkpointTransition, isCheckpointDigest, readCheckpointAdmission } from './checkpoint'; @@ -55,6 +55,8 @@ export type CodeBridgeSettlement = BridgeSettlement< } >; export type CodeBridgeWorkspaceSettlement = BridgeSettlement; +type PairedAuthorization = Awaited>; + type AnyCodeBridgeSettlement = | CodeBridgeSettlement | CodeBridgeWorkspaceSettlement; @@ -2051,6 +2053,7 @@ export class RedisBridgeStore { identityId?: string, quarantineWorkspace = false, checkpointCandidate?: CheckpointCandidate, + authorization?: PairedAuthorization, ): Promise { settlement = withValidCommandFailure(settlement); if (quarantineWorkspace) { @@ -2206,9 +2209,10 @@ export class RedisBridgeStore { String(settlementKeys.length - Number(validatedWorkspaceTool)), ]; const checkpoint = this.checkpointProofEnabled && settlement.status === 'fulfilled' && - checkpointCandidate != null && assignment.worktreeOwnerScope != null + checkpointCandidate != null && isCheckpointDigest(checkpointCandidate.commitment) && + authorization != null && assignment.worktreeOwnerScope != null ? checkpointTransition(settlementKeys, settlementArgs, - await this.readCheckpointContext(assignment, signal), + await this.readCheckpointContext(assignment, { authorization, signal }), { kind: 'settlement', candidate: checkpointCandidate, digest: tokenHash(serializedSettlement), ackKey: settlementKeys[3] }) : []; const script = [ @@ -2409,6 +2413,7 @@ export class RedisBridgeStore { signal?: AbortSignal, identityId?: string, checkpointCandidate?: CheckpointCandidate, + authorization?: PairedAuthorization, ): Promise { await this.quarantineSettledWorkspace( workerId, @@ -2418,6 +2423,7 @@ export class RedisBridgeStore { identityId, false, checkpointCandidate, + authorization, ); } @@ -2429,7 +2435,7 @@ export class RedisBridgeStore { workerId: string, assignmentId: string, request: CheckpointProofRequest, - authorization: Awaited>, + authorization: PairedAuthorization, ): Promise { const durability = this.checkpointProofDurability; if (!this.checkpointProofEnabled || durability == null || authorization.workerId !== workerId || @@ -2474,24 +2480,51 @@ export class RedisBridgeStore { }; } - private async readCheckpointContext(assignment: StoredAssignment, signal?: AbortSignal, tenantId?: string) { + private checkpointVoteAuthority( + receipt: AssignmentOwnership, + admission: CheckpointAdmission, + authorization: PairedAuthorization, + ): CheckpointContext['authority'] { + if (authorization.workerId !== receipt.workerId || authorization.identityId == null || + authorization.identityId !== receipt.workerIdentityId || authorization.binding?.tenantId !== admission.tenantId || + !Number.isSafeInteger(authorization.pairingGeneration) || + String(authorization.pairingGeneration) !== admission.pairingGeneration || + !isCheckpointDigest(authorization.activeCredentialId) || !isCheckpointDigest(authorization.credentialId)) return; + return { workerId: receipt.workerId, activeCredentialId: authorization.activeCredentialId, + credentialId: authorization.credentialId }; + } + + private async readCheckpointContext( + assignment: StoredAssignment, + source: { authorization: PairedAuthorization; signal?: AbortSignal } | { tenantId: string }, + ): Promise { if (assignment.executionKind !== 'workspace_tool' || assignment.durableRequestKey == null || assignment.workspaceLeaseSlot === undefined || assignment.worktreeOwnerScope == null || !isWorkspaceToolRequest(assignment.request) || assignment.request.operation !== 'create_worktree') return; try { - const raw = await this.leaseCommand(this.redis.hgetall(workspaceFenceReceiptKey(assignment.assignmentId)), - signal, 'Checkpoint receipt read'); - if (raw.metadata == null) return; - const receipt = JSON.parse(raw.metadata) as AssignmentOwnership | null; - const admission = readCheckpointAdmission(raw.checkpointAdmissionV1, raw.epoch); + const [metadata, checkpointAdmissionV1, epoch, activeCredentialId] = await this.leaseCommand( + this.redis.hmget(workspaceFenceReceiptKey(assignment.assignmentId), + 'metadata', 'checkpointAdmissionV1', 'epoch', 'checkpointActiveCredentialId'), + 'authorization' in source ? source.signal : undefined, 'Checkpoint receipt read'); + if (metadata == null || checkpointAdmissionV1 == null || epoch == null) return; + const receipt = JSON.parse(metadata) as AssignmentOwnership | null; + const admission = readCheckpointAdmission(checkpointAdmissionV1, epoch); if (receipt == null || admission == null || admission.ownerScope !== assignment.worktreeOwnerScope || - (tenantId != null && admission.tenantId !== tenantId) || + ('tenantId' in source && admission.tenantId !== source.tenantId) || receipt.assignmentId !== assignment.assignmentId || receipt.workerId !== assignment.workerId || receipt.incarnationId !== assignment.incarnationId || receipt.generation !== assignment.generation || receipt.workspaceLeaseSlot !== assignment.workspaceLeaseSlot || receipt.workspaceFence !== assignment.workspaceFence || receipt.workerIdentityId !== assignment.workerIdentityId || receipt.leaseTokenHash !== assignment.leaseTokenHash || - receipt.durableRequestKey !== assignment.durableRequestKey) return; - return this.checkpointContext(receipt, raw); + receipt.durableRequestKey !== assignment.durableRequestKey || receipt.expiresAt !== assignment.expiresAt) return; + const context = this.checkpointContext(receipt, { metadata, checkpointAdmissionV1, epoch }); + if (context == null) return; + // The reconciler has no signed request. It can only extend the authority + // accepted by settlement, not acquire a new one after rotation/re-pairing. + const authority = 'authorization' in source + ? this.checkpointVoteAuthority(receipt, admission, source.authorization) + : activeCredentialId != null && isCheckpointDigest(activeCredentialId) + ? { workerId: receipt.workerId, activeCredentialId } : undefined; + if (authority != null) return { ...context, authority }; } catch { /* An unavailable receipt must not decide ordinary settlement or cleanup. */ } } @@ -2503,6 +2536,7 @@ export class RedisBridgeStore { identityId?: string, quarantine = true, checkpointCandidate?: CheckpointCandidate, + authorization?: PairedAuthorization, ): Promise { // Keep a small, expiring ownership receipt separate from assignment cleanup. // A local guard can fail to clear after the result has already committed. @@ -2563,10 +2597,16 @@ export class RedisBridgeStore { quarantine ? '1' : '0', this.detachedFenceTtlSeconds(receipt), ]; - const checkpoint = this.checkpointProofEnabled && !quarantine && checkpointCandidate != null - ? checkpointTransition(keys, args, this.checkpointContext(receipt, raw), - { kind: 'cleanup', candidate: checkpointCandidate }) - : []; + let checkpoint: string[] = []; + if (this.checkpointProofEnabled && !quarantine && checkpointCandidate != null && authorization != null) { + const admission = readCheckpointAdmission(raw.checkpointAdmissionV1, raw.epoch); + if (admission != null) { + const authority = this.checkpointVoteAuthority(receipt, admission, authorization); + const context = authority == null ? undefined : this.checkpointContext(receipt, raw); + if (context != null) checkpoint = checkpointTransition(keys, args, { ...context, authority }, + { kind: 'cleanup', candidate: checkpointCandidate }); + } + } const accepted = Number( await this.leaseCommand( this.redis.eval( @@ -3122,7 +3162,7 @@ export class RedisBridgeStore { record.id === assignment.assignmentId && record.workerId === assignment.workerId && record.request.operation === 'create_worktree' && assignment.worktreeOwnerScope != null && isWorkspaceToolResult(record.request, settlement.result, record.registration.capabilities.workspaceTools) - ? checkpointTransition(keys, args, await this.readCheckpointContext(assignment, undefined, record.tenantId), { + ? checkpointTransition(keys, args, await this.readCheckpointContext(assignment, { tenantId: record.tenantId }), { kind: 'finalization', key: durableKey, digest: record.checkpointSettlementDigest, outcome: record.rawOutcome, assignment: record.rawAssignment, }) diff --git a/service/src/workspace-tools/requests.test.ts b/service/src/workspace-tools/requests.test.ts index 69a3730f..4c28b177 100644 --- a/service/src/workspace-tools/requests.test.ts +++ b/service/src/workspace-tools/requests.test.ts @@ -1,9 +1,11 @@ import { afterEach, expect, spyOn, test } from 'bun:test'; -import { createHash } from 'node:crypto'; +import { createHash, randomUUID } from 'node:crypto'; import RedisMock from 'ioredis-mock'; import Redis from 'ioredis'; import { BRIDGE_DRAIN_KEY, RedisBridgeStore } from '../bridge/store'; import { BridgeAdmissionQueue } from '../bridge/admission'; +import { credentialDigestKey, RedisBridgePairingStore, workerIdentityKey } from '../bridge/pairing'; +import { createBridgeIdentity, signBridgeRequest } from '../../../packages/code/src/identity'; import type { CodeBridgeAssignment } from '../bridge/store'; import { workspaceDetachedCommandKey } from '../../../packages/code/src/protocol'; import type { BridgeRejectedSettlement, BridgeWorkspaceToolOperation, WorkspaceToolRequest } from '../../../packages/code/src/protocol'; @@ -1187,7 +1189,6 @@ for (const slots of [1, 2]) { // Admission and wire negotiation are intentionally absent in this slice. Only // these real-Redis tests seed a receipt extension or pass candidate metadata. const checkpointTest = testRedisUrl ? test : test.skip; -const identityId = 'paired-worker-identity'; const pairingKey = `codeapi:bridge:v1:pairing-generation:${workerId}`; const slotsKey = `codeapi:bridge:v1:worker:${workerId}:workspace-slots`; const principal = { ...owner, principalSource: 'librechat_jwt' }; @@ -1196,16 +1197,27 @@ const creation = { protocolVersion: 1, operation: 'create_worktree', ...lane, co async function checkpointFixture(admit = true, acknowledge = true) { const proof = new RedisBridgeStore(redis, 600, 1000, 3, false, true, true); await redis.set(pairingKey, '4'); - await redis.set(`codeapi:bridge:v1:stable-identity:${workerId}`, identityId); + const binding = { tenantId: owner.tenantId, principal: { type: 'tenant', id: owner.tenantId } } as const; + const pairings = new RedisBridgePairingStore(redis); + const identity = createBridgeIdentity(); + const code = (await pairings.issue(workerId, binding)).code; + const { credential } = await pairings.redeem({ workerId, code, publicKey: identity.publicKey }); + const authorize = (token = credential) => { + const request = { credential: token, method: 'POST', path: '/test-checkpoint', body: '{}', + nonce: randomUUID(), timestamp: new Date().toISOString() }; + return pairings.authorize({ workerId, ...request, signature: signBridgeRequest(identity.privateKey, request) }); + }; + const auth = await authorize(); + const identityId = auth.identityId!; const generation = await proof.register({ protocolVersion: 1, workerId, incarnationId, identityId, - binding: { tenantId: owner.tenantId, principal: { type: 'tenant', id: owner.tenantId } }, + binding, capabilities: { sandboxProfile: 'native-srt', statefulWorkspace: false, runtimes: ['bash'], workspaceLeaseSlots: 2, requiresReadyConfirmation: true, workspaceTools: { protocolVersion: 1, worktreeOwnerScope: true, operations: ['create_worktree'], workspaces: [{ id: lane.workspaceId, workspaceScopes: ['git_linked_worktree'], operations: ['create_worktree'] }] }, }, - }, { identityId, pairingGeneration: 4 }); + }, auth); await proof.confirmReady(workerId, incarnationId, generation); const requests = new RedisWorkspaceRequests(redis, proof); await requests.submit({ owner: principal, requestId, workerId, requireTenantBinding: true, @@ -1227,11 +1239,13 @@ async function checkpointFixture(admit = true, acknowledge = true) { })); const result = { protocolVersion: 1 as const, generation: assignment.generation, incarnationId, leaseToken: assignment.leaseToken, status: 'fulfilled' as const, result: creation }; - const cleanup = (store = proof, ticket = candidate) => store.confirmWorkspaceCleanup(workerId, id, - rejection(assignment, 'local cleanup confirmed'), undefined, identityId, ticket); - const settle = (store = proof, ticket = candidate, body = result) => - store.settle(workerId, id, body, undefined, identityId, false, ticket); - return { proof, requests, key, id, receipt, settlementKey, candidate, cleanup, settle, result }; + const cleanup = (store = proof, ticket = candidate, authorization: typeof auth | null = auth) => + store.confirmWorkspaceCleanup(workerId, id, rejection(assignment, 'local cleanup confirmed'), + undefined, identityId, ticket, authorization ?? undefined); + const settle = (store = proof, ticket = candidate, body = result, authorization: typeof auth | null = auth) => + store.settle(workerId, id, body, undefined, identityId, false, ticket, authorization ?? undefined); + return { proof, requests, key, id, receipt, settlementKey, candidate, cleanup, settle, result, + auth, authorize, pairings, identityId }; } for (const order of ['cleanup-first', 'finalization-first'] as const) { @@ -1286,7 +1300,7 @@ for (const order of ['cleanup-first', 'finalization-first'] as const) { expect(await redis.pttl(f.receipt)).toBeGreaterThan(0); expect(await f.requests.get(principal, requestId)).toMatchObject({ state: 'completed', result: creation }); expect(await f.requests.get(principal, requestId)).not.toHaveProperty('checkpointSettlementDigest'); - expect(await f.proof.lease(workerId, incarnationId, 0, undefined, identityId, 0)).toBeUndefined(); + expect(await f.proof.lease(workerId, incarnationId, 0, undefined, f.identityId, 0)).toBeUndefined(); } finally { lost.mockRestore(); } }); } @@ -1379,7 +1393,7 @@ checkpointTest('a checkpoint replacement claimant seals a completed outcome and await requests.submit({ owner: principal, requestId: 'request-00000000002', workerId, requireTenantBinding: true, request: creation, queueWaitMs: 300_000, executionTimeoutMs: 30_000 }); await tick(requests); - const successor = (await replacement.lease(workerId, incarnationId, 0, undefined, identityId, 0))!; + const successor = (await replacement.lease(workerId, incarnationId, 0, undefined, f.identityId, 0))!; await expect(f.cleanup()).rejects.toMatchObject({ code: 'ASSIGNMENT_FENCED' }); resume(); await first; @@ -1424,3 +1438,142 @@ checkpointTest('confirmed stop cannot turn a checkpoint settlement into a cleanu expect(await redis.hlen(slotsKey)).toBe(0); expect(await f.requests.get(principal, requestId)).toMatchObject({ state: 'completed', result: creation }); }); + +async function beforeCheckpointCas(phase: 'settlement' | 'cleanup' | 'finalization', action: () => Promise, run: () => Promise) { + const marker = { settlement: "'checkpointCommitment',", cleanup: "'checkpointCleanupVote', digest", + finalization: "'checkpointFinalizationVote', digest" }[phase]; + const original = redis.eval.bind(redis); + let hit = 0; + const race = spyOn(redis, 'eval').mockImplementation((async (...args: Parameters) => { + if (String(args[0]).includes(marker)) { + ++hit; + await action(); + } + return original(...args); + }) as Redis['eval']); + try { await run(); } finally { race.mockRestore(); } + expect(hit).toBe(1); +} + +async function expectOrdinaryCheckpointCompletion(f: Awaited>) { + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).toBeNull(); + expect(await redis.hmget(f.receipt, 'localCleanup', 'resultCommitted')).toEqual(['1', '1']); + expect(await redis.get(laneFence)).toBeNull(); + expect(await redis.hlen(slotsKey)).toBe(0); + const status = await f.requests.get(principal, requestId); + expect(status).toMatchObject({ state: 'completed', result: creation }); + expect(status).not.toHaveProperty('checkpointSettlementDigest'); +} + +for (const phase of ['settlement', 'cleanup'] as const) { + for (const mismatch of ['missing', 'worker', 'tenant', 'identity', 'generation'] as const) { + checkpointTest(`checkpoint ${phase} ignores ${mismatch} paired authorization`, async () => { + const f = await checkpointFixture(); + const auth = { ...f.auth }; + if (mismatch === 'worker') auth.workerId = 'other-worker'; + if (mismatch === 'tenant') auth.binding = { ...auth.binding!, tenantId: 'other-tenant' }; + if (mismatch === 'identity') auth.identityId = 'other-identity'; + if (mismatch === 'generation') auth.pairingGeneration++; + const authorization = mismatch === 'missing' ? null : auth; + await f.settle(f.proof, f.candidate, f.result, phase === 'settlement' ? authorization : f.auth); + expect(await redis.get(f.settlementKey)).toBe(JSON.stringify(f.result)); + await f.cleanup(f.proof, f.candidate, phase === 'cleanup' ? authorization : f.auth); + expect(await redis.hget(f.receipt, phase === 'settlement' ? 'checkpointCommitment' : 'checkpointCleanupVote')).toBeNull(); + await tick(f.requests); + await expectOrdinaryCheckpointCompletion(f); + }); + } + + for (const change of ['rotation', 'signer removed', 'generation', 'credential tenant', 'admission bytes'] as const) { + checkpointTest(`checkpoint ${phase} rechecks ${change} at Redis CAS`, async () => { + const f = await checkpointFixture(); + // Obtain a valid signed authorization during rotation grace, when signing and active digests differ. + await f.pairings.rotate(workerId); + const auth = await f.authorize(); + expect(auth.activeCredentialId).not.toBe(auth.credentialId); + if (phase === 'cleanup') await f.settle(f.proof, f.candidate, f.result, auth); + await beforeCheckpointCas(phase, async () => { + if (change === 'rotation') return f.pairings.rotate(workerId); + if (change === 'signer removed') return redis.del(credentialDigestKey(auth.credentialId)); + if (change === 'generation') return redis.incr(pairingKey); + if (change === 'admission bytes') { + const raw = await redis.hget(f.receipt, 'checkpointAdmissionV1'); + return redis.hset(f.receipt, 'checkpointAdmissionV1', ` ${raw}`); + } + const key = credentialDigestKey(auth.activeCredentialId); + const credential = JSON.parse((await redis.get(key))!); + credential.binding.tenantId = 'other-tenant'; + return redis.set(key, JSON.stringify(credential), 'KEEPTTL'); + }, () => phase === 'settlement' ? f.settle(f.proof, f.candidate, f.result, auth) : f.cleanup(f.proof, f.candidate, auth)); + expect(await redis.get(f.settlementKey)).toBe(JSON.stringify(f.result)); + expect(await redis.hget(f.receipt, phase === 'settlement' ? 'checkpointCommitment' : 'checkpointCleanupVote')).toBeNull(); + if (phase === 'settlement') await f.cleanup(f.proof, f.candidate, auth); + await tick(f.requests); + await expectOrdinaryCheckpointCompletion(f); + }); + } +} + +for (const change of ['rotation', 'revocation', 'active credential removed', 'metadata bytes'] as const) { + checkpointTest(`checkpoint finalization cannot seal if ${change} wins after cleanup`, async () => { + const f = await checkpointFixture(); + await f.settle(); + await f.cleanup(); + expect(await redis.hget(f.receipt, 'checkpointCleanupVote')).not.toBeNull(); + await beforeCheckpointCas('finalization', async () => { + if (change === 'rotation') return f.pairings.rotate(workerId); + if (change === 'revocation') return f.pairings.revoke(workerId); + if (change === 'active credential removed') { + const key = workerIdentityKey(workerId); + expect(await redis.get(key)).toBe(f.auth.activeCredentialId); + return redis.del(credentialDigestKey(f.auth.activeCredentialId)); + } + const raw = await redis.hget(f.receipt, 'metadata'); + return redis.hset(f.receipt, 'metadata', ` ${raw}`); + }, () => tick(f.requests)); + expect(await redis.hget(f.receipt, 'checkpointFinalizationVote')).toBeNull(); + await expectOrdinaryCheckpointCompletion(f); + }); +} + +checkpointTest('fresh authorization after rotation cannot join earlier checkpoint votes', async () => { + const f = await checkpointFixture(); + await f.settle(); + await tick(f.requests); + expect(await redis.hget(f.receipt, 'checkpointFinalizationVote')).not.toBeNull(); + const { credential } = await f.pairings.rotate(workerId); + const auth = await f.authorize(credential); + expect(auth.identityId).toBe(f.auth.identityId); + expect(auth.pairingGeneration).toBe(f.auth.pairingGeneration); + await f.cleanup(f.proof, f.candidate, auth); + expect(await redis.hget(f.receipt, 'checkpointCleanupVote')).toBeNull(); + await expectOrdinaryCheckpointCompletion(f); +}); + +checkpointTest('a live grace signer can vote without changing the active checkpoint authority', async () => { + const f = await checkpointFixture(); + const { credential } = await f.pairings.rotate(workerId); + const grace = await f.authorize(); + const active = await f.authorize(credential); + expect(grace.credentialId).not.toBe(active.credentialId); + expect(grace.activeCredentialId).toBe(active.activeCredentialId); + await f.settle(f.proof, f.candidate, f.result, grace); + await f.cleanup(f.proof, f.candidate, active); + // Expiry of a grace signer after its vote does not change the active pairing. + await redis.del(credentialDigestKey(grace.credentialId)); + await tick(f.requests); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).not.toBeNull(); + expect(await redis.get(laneFence)).toBeNull(); +}); + +for (const phase of ['settlement', 'cleanup'] as const) { + checkpointTest(`real pairing revocation preserves the ordinary ${phase} fence`, async () => { + const f = await checkpointFixture(); + if (phase === 'cleanup') await f.settle(); + await beforeCheckpointCas(phase, () => f.pairings.revoke(workerId), async () => { + await expect(phase === 'settlement' ? f.settle() : f.cleanup()).rejects.toMatchObject({ code: 'ASSIGNMENT_FENCED' }); + }); + expect(await redis.hget(f.receipt, phase === 'settlement' ? 'checkpointCommitment' : 'checkpointCleanupVote')).toBeNull(); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).toBeNull(); + }); +}