diff --git a/packages/code/src/protocol.ts b/packages/code/src/protocol.ts index af9eedd7..e7f5ee50 100644 --- a/packages/code/src/protocol.ts +++ b/packages/code/src/protocol.ts @@ -996,6 +996,8 @@ const WORKSPACE_COMMAND_RESULT_KEYS = new Set([ const WORKSPACE_SEARCH_MATCH_KEYS = new Set(['path', 'line', 'column', 'text']); export interface BridgeWorkerCapabilities { + /** Opt in to negotiating the dark checkpoint lease ticket, not worktree ownership. */ + checkpointLeaseTicketV1?: true; /** Opt-in protocol: maximum concurrently leased independent workspace roots. */ workspaceLeaseSlots?: number; statefulWorkspace: boolean; @@ -1027,6 +1029,7 @@ export interface BridgeWorkerRegistrationResponse { supportedWorkspaceToolOperations?: BridgeWorkspaceToolOperation[]; /** This bridge can bind a durable creation lease to its authenticated caller. */ supportedWorktreeOwnerScope?: true; + supportedCheckpointLeaseTicketV1?: true; /** Write modes this Code API can safely route to a capability-aware worker. */ supportedWorkspaceWriteFileModes?: WorkspaceWriteFileMode[]; /** Edit modes this Code API can safely route to a capability-aware worker. */ @@ -1161,6 +1164,8 @@ export interface BridgeAssignment { request: BridgeSandboxRequest | WorkspaceToolRequest; /** Bridge-derived principal scope for explicit creation, never caller request data. */ worktreeOwnerScope?: string; + /** Advisory only. The surrounding lease supplies the assignment, generation, incarnation and slot. */ + checkpointLeaseTicket?: { version: 1; epoch: string }; } export interface BridgeLeaseResponse { @@ -2465,6 +2470,7 @@ export function isValidBridgeWorkerCapabilities( if (typeof value !== 'object' || value === null) return false; const capabilities = value as Record; return ( + (capabilities.checkpointLeaseTicketV1 === undefined || capabilities.checkpointLeaseTicketV1 === true) && (capabilities.workspaceLeaseSlots === undefined || (Number.isSafeInteger(capabilities.workspaceLeaseSlots) && Number(capabilities.workspaceLeaseSlots) >= 1 && diff --git a/service/src/bridge/checkpoint-lease-ticket.test.ts b/service/src/bridge/checkpoint-lease-ticket.test.ts new file mode 100644 index 00000000..016afa78 --- /dev/null +++ b/service/src/bridge/checkpoint-lease-ticket.test.ts @@ -0,0 +1,445 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import { expect, spyOn, test } from 'bun:test'; +import express from 'express'; + +import { + createBridgeIdentity, + signBridgeRequest, +} from '../../../packages/code/src/identity'; +import { workspaceIsolationKey } from '../../../packages/code/src/protocol'; +import { startTestRedis } from '../test/redis'; +import type { WorkspaceRequestOwner } from '../workspace-tools/requests'; +import { RedisWorkspaceRequests } from '../workspace-tools/requests'; +import { RedisBridgePairingStore, credentialDigestKey } from './pairing'; +import { createBridgeRouter } from './router'; +import { RedisBridgeStore } from './store'; + +const workerId = 'checkpoint-worker'; +const incarnationId = 'checkpoint-incarnation'; +const worker = `codeapi:bridge:v1:worker:${workerId}`; +const binding = { + tenantId: 'tenant', + principal: { type: 'tenant', id: 'tenant' }, +} as const; +const owner = { + tenantId: binding.tenantId, + userId: 'user', + principalSource: 'librechat_jwt', +} as const; +const creation = { + protocolVersion: 1, + operation: 'create_worktree', + workspaceId: 'primary', + worktree: 'lane', + commit: 'a'.repeat(40), +} as const; +const epochKey = `${worker}:workspace:${createHash('sha256') + .update( + `native-workspace:${workspaceIsolationKey( + 'primary', + undefined, + 'lane' + )}` + ) + .digest('hex')}:quarantined:epoch`; + +async function fixture( + options: { + enabled?: boolean; + optIn?: true; + scope?: true; + paired?: boolean; + bound?: boolean; + requireTenantBinding?: boolean; + trusted?: boolean; + slots?: number; + remove?: boolean; + } = {} +) { + const redis = await startTestRedis(); + const pairings = new RedisBridgePairingStore(redis); + const store = new RedisBridgeStore( + redis, + 600, + 1000, + 2, + false, + true, + false, + undefined, + options.enabled === false ? undefined : true + ); + const identity = createBridgeIdentity(); + const app = express(); + const paired = options.paired !== false; + app.use(express.json()); + app.use( + createBridgeRouter({ + enabled: true, + store, + pairings, + authMode: paired ? 'paired' : 'static', + configuredWorkerId: workerId, + adminToken: 'test-admin', + }) + ); + const server = createServer(app); + async function close(): Promise { + server.close(); + server.closeAllConnections(); + await redis.closeTestServer(); + } + try { + const credential = paired + ? ( + await pairings.redeem({ + workerId, + code: ( + await pairings.issue( + workerId, + options.bound === false ? undefined : binding + ) + ).code, + publicKey: identity.publicKey, + }) + ).credential + : ''; + const authArgs = (path: string, payload: object, key = credential) => { + const proof = { + credential: key, + path, + method: 'POST', + timestamp: new Date().toISOString(), + nonce: randomUUID(), + body: JSON.stringify(payload), + }; + return { + ...proof, + signature: signBridgeRequest(identity.privateKey, proof), + }; + }; + const auth = paired + ? await pairings.authorize({ ...authArgs('/test', {}), workerId }) + : undefined; + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + if (address == null || typeof address === 'string') + throw new Error('Expected a local TCP listener'); + const post = async ( + path: string, + payload: object, + key = credential + ) => { + const proof = authArgs(path, payload, key); + return fetch(`http://127.0.0.1:${address.port}${path}`, { + method: 'POST', + body: proof.body, + headers: { + 'Content-Type': 'application/json', + ...(paired + ? { + Authorization: `Bridge ${key}`, + 'X-LibreChat-Code-Timestamp': proof.timestamp, + 'X-LibreChat-Code-Nonce': proof.nonce, + 'X-LibreChat-Code-Signature': proof.signature, + } + : { Authorization: 'Bearer test-admin' }), + }, + }); + }; + const operations = ['create_worktree', 'remove_worktree'] as const; + const registered = await post('/workers/register', { + protocolVersion: 1, + workerId, + incarnationId, + capabilities: { + sandboxProfile: 'native-srt', + statefulWorkspace: false, + runtimes: ['bash'], + workspaceLeaseSlots: options.slots ?? 2, + requiresReadyConfirmation: true, + checkpointLeaseTicketV1: options.optIn, + workspaceTools: { + protocolVersion: 1, + worktreeOwnerScope: options.scope, + operations, + workspaces: [ + { + id: 'primary', + workspaceScopes: ['git_linked_worktree'], + operations, + }, + ], + }, + }, + }); + expect(registered.status).toBe(200); + const registration = await registered.json(); + expect( + ( + await post(`/workers/${workerId}/ready`, { + protocolVersion: 1, + incarnationId, + registrationGeneration: registration.registrationGeneration, + }) + ).status + ).toBe(200); + const requests = new RedisWorkspaceRequests(redis, store); + const submit = ( + caller: WorkspaceRequestOwner = options.trusted === false + ? { ...owner, principalSource: undefined } + : owner + ) => + requests.submit({ + owner: caller, + workerId, + requireTenantBinding: + options.requireTenantBinding ?? + (paired && options.bound !== false), + requestId: randomUUID(), + request: options.remove + ? { + protocolVersion: 1, + operation: 'remove_worktree', + workspaceId: creation.workspaceId, + worktree: creation.worktree, + } + : creation, + queueWaitMs: 300_000, + executionTimeoutMs: 30_000, + }); + const lease = ( + optIn = true, + slot: number | undefined = options.slots === 1 ? undefined : 0, + key = credential + ) => + post( + `/workers/${workerId}/lease`, + { + protocolVersion: 1, + incarnationId, + waitMs: 0, + workspaceLeaseSlot: slot, + ...(optIn ? { checkpointLeaseTicketV1: true } : {}), + }, + key + ); + return { + redis, + store, + requests, + registration, + submit, + lease, + auth, + credential, + pairings, + close, + }; + } catch (error) { + await close(); + throw error; + } +} + +const negotiated = { optIn: true, scope: true } as const; +const receiptKey = (id: string) => + `codeapi:bridge:v1:assignment:${id}:workspace-fence-owner`; + +test('enqueue binds the exact epoch and duplicate authenticated leases return the same inert ticket', async () => { + const f = await fixture(negotiated); + try { + expect(f.registration.supportedCheckpointLeaseTicketV1).toBe(true); + await f.redis.set(epochKey, '9007199254740992'); + const status = await f.submit(); + expect(status).not.toHaveProperty('checkpointLeaseTicket'); + await f.requests.reconcile(); + expect(await f.redis.get(epochKey)).toBe('9007199254740993'); + const wrong = await f.lease(true, 0, 'invalid-credential'); + expect(wrong.status).toBe(401); + expect( + (await (await f.lease(true, 1)).json()).assignment + ).toBeUndefined(); + const oldPoll = (await (await f.lease(false)).json()).assignment; + expect(oldPoll.worktreeOwnerScope).toMatch(/^[a-f0-9]{64}$/); + expect(oldPoll).not.toHaveProperty('checkpointLeaseTicket'); + const [first, second] = await Promise.all([f.lease(), f.lease()]); + const a = (await first.json()).assignment; + expect(a.assignmentId).toBe(oldPoll.assignmentId); + expect(a.checkpointLeaseTicket).toEqual({ + version: 1, + epoch: '9007199254740993', + }); + expect((await second.json()).assignment.checkpointLeaseTicket).toEqual( + a.checkpointLeaseTicket + ); + const receipt = receiptKey(a.assignmentId); + expect(await f.redis.hget(receipt, 'epoch')).toBe( + a.checkpointLeaseTicket.epoch + ); + expect(await f.redis.hget(receipt, 'checkpointAdmissionV1')).toBeNull(); + } finally { + await f.close(); + } +}); + +const legacyCases = [ + ['default-off server', { ...negotiated, enabled: false }, false], + ['ownership-only worker', { scope: true }, false], + ['worker without ownership', { optIn: true }, false], + ['static worker', { ...negotiated, paired: false }, false], + ['unbound paired worker', { ...negotiated, bound: false }, false], + ['single-slot worker', { ...negotiated, slots: 1 }, false], + [ + 'non-tenant-required request', + { ...negotiated, requireTenantBinding: false }, + true, + ], + ['untrusted owner', { ...negotiated, trusted: false }, true], + ['worktree removal', { ...negotiated, remove: true }, true], +] as const; + +test.each(legacyCases)( + '%s gets ordinary work without a ticket', + async (_name, options, offered) => { + const f = await fixture(options); + try { + expect(f.registration.supportedCheckpointLeaseTicketV1).toBe( + offered ? true : undefined + ); + await f.submit(); + await f.requests.reconcile(); + const response = await f.lease(); + expect(response.status).toBe(200); + const { assignment } = await response.json(); + expect(assignment).toBeDefined(); + expect(assignment).not.toHaveProperty('checkpointLeaseTicket'); + expect( + await f.redis.hget( + receiptKey(assignment.assignmentId), + 'checkpointLeaseTicketV1' + ) + ).toBeNull(); + } finally { + await f.close(); + } + } +); + +test.each([ + 'epoch advanced', + 'credential rotated', + 'pairing changed', + 'slot revoked', + 'deadline expired', +] as const)( + '%s suppresses the ticket even on a duplicate claim', + async violation => { + const f = await fixture(negotiated); + try { + await expect( + f.submit({ ...owner, tenantId: 'other' }) + ).rejects.toMatchObject({ code: 'WORKER_UNAUTHORIZED' }); + await f.submit(); + await f.requests.reconcile(); + const { assignment } = await (await f.lease()).json(); + expect(assignment.checkpointLeaseTicket).toEqual({ + version: 1, + epoch: '1', + }); + if (violation === 'epoch advanced') await f.redis.incr(epochKey); + if (violation === 'credential rotated') + await f.pairings.rotate(workerId, f.auth!.credentialId); + if (violation === 'pairing changed') + await f.redis.incr( + `codeapi:bridge:v1:pairing-generation:${workerId}` + ); + if (violation === 'slot revoked') + await f.redis.hdel(`${worker}:workspace-slots`, 'a:0'); + if (violation === 'deadline expired') + await f.redis.del( + `codeapi:bridge:v1:assignment:${assignment.assignmentId}:deadline` + ); + const response = await f.lease(); + expect(response.status).toBe(200); + expect((await response.json()).assignment).not.toHaveProperty( + 'checkpointLeaseTicket' + ); + } finally { + await f.close(); + } + } +); + +test('credential lost after authorization cannot issue a ticket', async () => { + const f = await fixture(negotiated); + try { + await f.submit(); + await f.requests.reconcile(); + await f.redis.del(credentialDigestKey(f.auth!.credentialId)); + const assignment = await f.store.lease( + workerId, + incarnationId, + 0, + undefined, + f.auth!.identityId, + 0, + f.auth + ); + expect(assignment).toBeDefined(); + expect(assignment).not.toHaveProperty('checkpointLeaseTicket'); + } finally { + await f.close(); + } +}); + +test('enqueue CAS continues ordinary work if opt-in is withdrawn after the registration read', async () => { + const f = await fixture(negotiated); + const other = f.redis.duplicate(); + const send = f.redis.sendCommand.bind(f.redis); + let raced = false; + const hook = spyOn(f.redis, 'sendCommand').mockImplementation( + (command, stream) => { + if ( + !raced && + command.name === 'eval' && + String(command.args[0]).includes( + "'checkpointLeaseTicketV1', cjson.encode" + ) + ) { + raced = true; + return (async () => { + const raw = JSON.parse((await other.get(worker))!); + delete raw.capabilities.checkpointLeaseTicketV1; + await other.set(worker, JSON.stringify(raw), 'KEEPTTL'); + return send(command, stream); + })(); + } + return send(command, stream); + } + ); + try { + await f.submit(); + await f.requests.reconcile(); + expect(raced).toBe(true); + const { assignment } = await (await f.lease()).json(); + expect(assignment.worktreeOwnerScope).toMatch(/^[a-f0-9]{64}$/); + expect(assignment).not.toHaveProperty('checkpointLeaseTicket'); + expect( + await f.redis.hget(receiptKey(assignment.assignmentId), 'epoch') + ).toBe('1'); + expect( + await f.redis.hget( + receiptKey(assignment.assignmentId), + 'checkpointLeaseTicketV1' + ) + ).toBeNull(); + } finally { + hook.mockRestore(); + other.disconnect(); + await f.close(); + } +}); diff --git a/service/src/bridge/router.ts b/service/src/bridge/router.ts index 49301ad9..c7ae0f71 100644 --- a/service/src/bridge/router.ts +++ b/service/src/bridge/router.ts @@ -574,15 +574,7 @@ router.post( return; } const authorization = options.authMode === 'paired' - ? ( - res.locals.bridgeWorkerAuthorization as { - identityId: string; - pairingGeneration: number; - credentialId: string; - activeCredentialId: string; - binding?: BridgeWorkerBinding; - } - ) + ? res.locals.bridgeWorkerAuthorization as Awaited> : undefined; const trustedRegistration: BridgeWorkerRegistration & { binding?: BridgeWorkerBinding; @@ -631,6 +623,8 @@ router.post( ...(options.workspaceImportFile === true ? ['import_file' as const] : []), ], supportedWorktreeOwnerScope: true, + ...(options.store.offersCheckpointLeaseTicket(trustedRegistration, authorization) + ? { supportedCheckpointLeaseTicketV1: true } : {}), supportedWorkspaceWriteFileModes: ['replace', 'create'], supportedWorkspaceEditFileModes: ['single', 'batch'], supportedWorkspaceEditFileFeatures: [...WORKSPACE_EDIT_FILE_FEATURES], @@ -766,6 +760,7 @@ router.post( !validIncarnationId(body.incarnationId) || !Number.isFinite(requestedWait) || requestedWait < 0 || + (body.checkpointLeaseTicketV1 !== undefined && body.checkpointLeaseTicketV1 !== true) || (body.workspaceLeaseSlot !== undefined && (!Number.isSafeInteger(body.workspaceLeaseSlot) || Number(body.workspaceLeaseSlot) < 0 || @@ -787,17 +782,17 @@ router.post( res.once('close', abortLease); let assignment: CodeBridgeAssignment | undefined; try { + const authorization = options.authMode === 'paired' + ? res.locals.bridgeWorkerAuthorization as Awaited> + : undefined; assignment = await options.store.lease( workerId, body.incarnationId, Math.min(requestedWait, MAX_LEASE_WAIT_MS), leaseController.signal, - ( - res.locals.bridgeWorkerAuthorization as - | { identityId: string } - | undefined - )?.identityId, + authorization?.identityId, body.workspaceLeaseSlot === undefined ? undefined : Number(body.workspaceLeaseSlot), + body.checkpointLeaseTicketV1 === true ? authorization : undefined, ); if (leaseController.signal.aborted) { if (assignment != null) await options.store.returnLease(assignment); diff --git a/service/src/bridge/store.ts b/service/src/bridge/store.ts index 8e8940dc..ac59c7b8 100644 --- a/service/src/bridge/store.ts +++ b/service/src/bridge/store.ts @@ -41,6 +41,8 @@ import { checkpointTransition, isCheckpointDigest, readCheckpointAdmission } fro import type { StoredWorkspaceRequest } from '../workspace-tools/requests'; const PREFIX = 'codeapi:bridge:v1'; +type PairedAuthorization = Awaited>; + export const BRIDGE_DRAIN_KEY = `${PREFIX}:maintenance:drain`; const POLL_INTERVAL_MS = 100; const DEFAULT_WORKER_TTL_SECONDS = 60; @@ -171,6 +173,12 @@ type AssignmentOwnership = Pick< | 'durableRequestKey' >; +function ownership(assignment: StoredAssignment): AssignmentOwnership { + const { assignmentId, workerId, incarnationId, workspaceFence, workspaceLeaseSlot, + generation, leaseTokenHash, workerIdentityId, expiresAt, durableRequestKey } = assignment; + return { assignmentId, workerId, incarnationId, workspaceFence, workspaceLeaseSlot, + generation, leaseTokenHash, workerIdentityId, expiresAt, durableRequestKey }; +} const NATIVE_WORKSPACE_FENCE_PREFIX = 'native-workspace:'; /** Fence keys of the linked-worktree lanes enqueued beneath a checkout fence. */ @@ -224,6 +232,7 @@ export interface RegisteredBridgeWorker extends BridgeWorkerRegistration { binding?: BridgeWorkerBinding; credentialId?: string; identityId?: string; + checkpointTicketPairingGeneration?: string; } export interface BridgeWorkerStatus { @@ -611,6 +620,8 @@ export class RedisBridgeStore { /** Internal proof transitions only; not wired to deployment configuration or negotiation. */ private readonly checkpointProofEnabled = false, private readonly checkpointProofDurability?: CheckpointProofDurability, + /** Test-only until ticket consumption and publication are ready. */ + private readonly checkpointLeaseTicketsEnabled = false, ) { if ( !Number.isSafeInteger(maxWorkspaceLeaseSlots) || @@ -623,6 +634,19 @@ export class RedisBridgeStore { } } + offersCheckpointLeaseTicket(registration: RegisteredBridgeWorker, auth: PairedAuthorization | undefined): boolean { + return this.checkpointLeaseTicketsEnabled && auth != null && auth.workerId === registration.workerId && + auth.identityId != null && auth.identityId === registration.identityId && + auth.binding != null && auth.binding.tenantId === registration.binding?.tenantId && + auth.credentialId === auth.activeCredentialId && auth.credentialId === registration.credentialId && + Number.isSafeInteger(auth.pairingGeneration) && auth.pairingGeneration >= 0 && + registration.capabilities.checkpointLeaseTicketV1 === true && + registration.capabilities.workspaceTools?.worktreeOwnerScope === true && + registration.capabilities.workspaceTools.operations.includes('create_worktree') && + registration.capabilities.requiresReadyConfirmation === true && + this.workspaceLeaseCapacity(registration.capabilities.workspaceLeaseSlots) > 1; + } + workspaceLeaseCapacity(requested = 1): number { return Math.min(this.maxWorkspaceLeaseSlots, requested); } @@ -808,8 +832,15 @@ export class RedisBridgeStore { identityId?: string; pairingGeneration?: number; activeCredentialId?: string; - }, + } + | PairedAuthorization, ): Promise { + registration = { ...registration }; + delete registration.checkpointTicketPairingGeneration; + if (typeof authorization === 'object' && 'workerId' in authorization && + this.offersCheckpointLeaseTicket(registration, authorization)) { + registration.checkpointTicketPairingGeneration = String(authorization.pairingGeneration); + } if (registration.capabilities.workspaceLeaseSlots !== undefined) { if ( !isValidBridgeWorkerCapabilities(registration.capabilities) || @@ -1112,7 +1143,12 @@ export class RedisBridgeStore { throw new BridgeStoreError('WORKER_FENCED', 'Code environment changed before admission'); } try { - await this.enqueueForActiveIncarnation(assignment, assignmentTtlSeconds(Date.parse(assignment.expiresAt)), ready.readyToken, guard); + const ticketRegistration = this.checkpointLeaseTicketsEnabled && record.requireTenantBinding && + ready.registration.binding?.tenantId === record.tenantId && ready.readyToken != null && + slot !== undefined && isCheckpointDigest(assignment.worktreeOwnerScope) && + ready.registration.checkpointTicketPairingGeneration != null ? ready.registration : undefined; + await this.enqueueForActiveIncarnation(assignment, assignmentTtlSeconds(Date.parse(assignment.expiresAt)), + ready.readyToken, guard, ticketRegistration); } catch (error) { // The atomic drain check rejected enqueue; release only our reservation. if (!(error instanceof BridgeDrainError)) throw error; @@ -1717,6 +1753,7 @@ export class RedisBridgeStore { signal?: AbortSignal, identityId?: string, slot?: number, + ticketAuth?: PairedAuthorization, ): Promise { if (slot !== undefined) { const registration = await this.registration(workerId); @@ -1829,10 +1866,20 @@ export class RedisBridgeStore { workspaceFence: _workspaceFence, durableRequestKey: _durableRequestKey, worktreeOwnerScope, + checkpointLeaseTicket: _checkpointLeaseTicket, ...wireAssignment } = assignment; + const ticket = this.checkpointLeaseTicketsEnabled && ticketAuth != null + ? await this.leaseCommand(this.checkpointLeaseTicket(assignment, registration, ticketAuth), + signal, 'Bridge checkpoint lease ticket') + : undefined; + if (signalAborted(signal)) { + await this.returnLease(assignment); + return undefined; + } return { ...wireAssignment, + ...(ticket != null ? { checkpointLeaseTicket: ticket } : {}), ...(worktreeOwnerScope != null && registration.capabilities.workspaceTools?.worktreeOwnerScope === true ? { worktreeOwnerScope } : {}), remainingMs: Math.max( @@ -1854,6 +1901,54 @@ export class RedisBridgeStore { return undefined; } + private async checkpointLeaseTicket( + assignment: StoredAssignment, + registration: RegisteredBridgeWorker, + auth: PairedAuthorization, + ): Promise { + const { workerId, incarnationId, assignmentId, workspaceLeaseSlot: slot, workspaceFence, + durableRequestKey } = assignment; + const pairingGeneration = registration.checkpointTicketPairingGeneration; + if (!this.offersCheckpointLeaseTicket(registration, auth) || + pairingGeneration !== String(auth.pairingGeneration) || + assignment.workerIdentityId !== auth.identityId || slot === undefined || workspaceFence == null || + durableRequestKey == null || assignment.executionKind !== 'workspace_tool' || + (assignment.request as WorkspaceToolRequest).operation !== 'create_worktree' || + !isCheckpointDigest(assignment.worktreeOwnerScope) || auth.binding == null || auth.identityId == null) return; + const parent = workspaceFenceParent(workspaceFence); + if (parent == null) return; + const fence = workspaceQuarantineKey(workerId, workspaceFence); + const keys = [ + workspaceFenceReceiptKey(assignmentId), `${fence}:epoch`, fence, workspaceQuarantineKey(workerId, parent), + workerKey(workerId), workerReadyKey(workerId), workerIncarnationKey(workerId), + workerStableIdentityKey(workerId), `${PREFIX}:pairing-generation:${workerId}`, + workerIdentityKey(workerId), credentialDigestKey(auth.credentialId), + leaseClaimKey(workerId, incarnationId, slot), `${workerKey(workerId)}:workspace-slots`, + assignmentKey(assignmentId), assignmentDeadlineKey(assignmentId), durableRequestKey, + incarnationFenceKey(workerId, incarnationId), quarantineKey(workerId, incarnationId), + cancellationKey(assignmentId), settlementKey(assignmentId), + ]; + const epoch = await this.redis.eval([ + "local function get(key) return redis.pcall('GET', KEYS[key]) end", + "local function field(key, name) return redis.pcall('HGET', KEYS[key], name) end", + "local raw = field(1, 'checkpointLeaseTicketV1')", + "if type(raw) ~= 'string' then return nil end", + 'local ok, ticket = pcall(cjson.decode, raw)', + "if not ok or type(ticket) ~= 'table' or type(ticket.epoch) ~= 'string' or type(ticket.ready) ~= 'string' then return nil end", + "if field(1, 'metadata') ~= ARGV[1] or field(1, 'epoch') ~= ticket.epoch or get(2) ~= ticket.epoch or get(3) ~= ARGV[2] then return nil end", + "if get(5) ~= ARGV[3] or get(6) ~= ticket.ready or get(7) ~= ARGV[4] or get(8) ~= ARGV[5] then return nil end", + "if ticket.pairingGeneration ~= ARGV[6] or (get(9) or '0') ~= ARGV[6] or get(10) ~= ARGV[7] or type(get(11)) ~= 'string' then return nil end", + 'if ticket.ownerScope ~= ARGV[10] or ticket.tenantId ~= ARGV[11] or ticket.credentialId ~= ARGV[7] then return nil end', + "if get(12) ~= ARGV[2] or field(13, 'a:' .. ARGV[8]) ~= ARGV[2] or field(13, 'i:' .. ARGV[8]) ~= ARGV[4] then return nil end", + "if get(14) ~= ARGV[9] or get(15) ~= '1' or field(16, 'state') ~= 'admitted' or field(16, 'assignment') ~= ARGV[9] then return nil end", + "if redis.call('EXISTS', KEYS[4], KEYS[17], KEYS[18], KEYS[19], KEYS[20]) ~= 0 then return nil end", + 'return ticket.epoch', + ].join('\n'), keys.length, ...keys, JSON.stringify(ownership(assignment)), assignmentId, + JSON.stringify(registration), incarnationId, auth.identityId, pairingGeneration, auth.credentialId, + String(slot), JSON.stringify(assignment), assignment.worktreeOwnerScope, auth.binding.tenantId); + if (typeof epoch === 'string' && /^[1-9][0-9]{0,18}$/.test(epoch)) return { version: 1, epoch }; + } + async acknowledgeLease( workerId: string, incarnationId: string, @@ -2868,7 +2963,15 @@ export class RedisBridgeStore { ttlSeconds: number, readyToken?: string, guard?: DurableWorkspaceGuard, + ticketRegistration?: RegisteredBridgeWorker, ): Promise { + const ticketGeneration = ticketRegistration?.checkpointTicketPairingGeneration; + const ticketCredential = ticketRegistration?.credentialId; + const ticketTenant = ticketRegistration?.binding?.tenantId; + const ticketOwner = assignment.worktreeOwnerScope; + const bindTicket = guard != null && ticketTenant != null && ticketGeneration != null && ticketCredential != null && + ticketRegistration?.identityId === assignment.workerIdentityId && assignment.workerIdentityId != null && + ticketOwner != null && readyToken != null; const script = [ "if redis.call('EXISTS', KEYS[#KEYS]) == 1 then return -3 end", 'local keyCount = tonumber(ARGV[10])', @@ -2924,6 +3027,15 @@ export class RedisBridgeStore { " local epoch = redis.call('GET', KEYS[9])", ' if redis.call(\'PTTL\', KEYS[9]) < tonumber(ARGV[12]) * 1000 then redis.call(\'EXPIRE\', KEYS[9], ARGV[12]) end', " redis.call('HSET', KEYS[8], 'metadata', ARGV[8], 'epoch', epoch)", + ...(bindTicket ? [ + " if ARGV[9] == 'lane' and redis.pcall('GET', KEYS[#KEYS-5]) == ARGV[14] and", + " (redis.pcall('GET', KEYS[#KEYS-4]) or '0') == ARGV[15] and", + " redis.pcall('GET', KEYS[#KEYS-3]) == ARGV[16] and", + " redis.pcall('GET', KEYS[#KEYS-2]) == ARGV[17] and type(redis.pcall('GET', KEYS[#KEYS-1])) == 'string' then", + // Deliberately not checkpointAdmissionV1: a ticket cannot opt this lease into proof votes. + " redis.call('HSET', KEYS[8], 'checkpointLeaseTicketV1', cjson.encode({epoch = epoch, pairingGeneration = ARGV[15], ready = ARGV[7], ownerScope = ARGV[18], tenantId = ARGV[19], credentialId = ARGV[17]}))", + ' end', + ] : []), ' redis.call(\'EXPIRE\', KEYS[8], ARGV[12])', 'end', ...(guard == null ? [] : [ @@ -2951,18 +3063,6 @@ export class RedisBridgeStore { ), ); } - const receipt: AssignmentOwnership = { - assignmentId: assignment.assignmentId, - workerId: assignment.workerId, - incarnationId: assignment.incarnationId, - workspaceFence: assignment.workspaceFence, - workspaceLeaseSlot: assignment.workspaceLeaseSlot, - generation: assignment.generation, - leaseTokenHash: assignment.leaseTokenHash, - workerIdentityId: assignment.workerIdentityId, - expiresAt: assignment.expiresAt, - durableRequestKey: assignment.durableRequestKey, - }; let fenceScope: '' | 'lane' | 'checkout' | 'detached' = ''; if (assignment.workspaceLeaseSlot !== undefined) { keys.push( @@ -2999,6 +3099,8 @@ export class RedisBridgeStore { assignment.workspaceLeaseSlot === undefined ? lockKey(assignment.workerId) : `${workerKey(assignment.workerId)}:workspace-slots`); if (guard == null) keys.push(assignment.workspaceLeaseSlot === undefined ? lockKey(assignment.workerId) : `${workerKey(assignment.workerId)}:workspace-slots`); + if (bindTicket) keys.push(workerKey(assignment.workerId), `${PREFIX}:pairing-generation:${assignment.workerId}`, + workerStableIdentityKey(assignment.workerId), workerIdentityKey(assignment.workerId), credentialDigestKey(ticketCredential)); keys.push(BRIDGE_DRAIN_KEY); const result = await this.redis.eval( script, @@ -3011,12 +3113,13 @@ export class RedisBridgeStore { String(ttlSeconds * 1000), String(Date.parse(assignment.expiresAt)), readyToken ?? '', - JSON.stringify(receipt), + JSON.stringify(ownership(assignment)), fenceScope, keyCount, guard?.token ?? '', guard == null ? ttlSeconds : assignmentOutcomeTtlSeconds(assignment), this.detachedFenceTtlSeconds(assignment), + ...(bindTicket ? [JSON.stringify(ticketRegistration), ticketGeneration, assignment.workerIdentityId!, ticketCredential, ticketOwner, ticketTenant] : []), ); if (Number(result) === -4) throw new BridgeStoreError('ASSIGNMENT_FENCED', 'Bridge assignment reservation was revoked before enqueue'); if (Number(result) === -3) throw new BridgeDrainError();