257 lines
18 KiB
TypeScript
257 lines
18 KiB
TypeScript
import { inspectVrfProductionAdmission, sealVrfProductionAdmission, type VrfProductionAdmission, type VrfProductionBinding, type VrfProductionRequest, type VrfProductionSnapshot } from "./vrf-production-admission.js"
|
|
import { readVrfProductionSnapshot, type VrfProductionReadAdapter } from "./vrf-production-read.js"
|
|
import { assertVrfActionContext, assertVrfAliasEvidence, vrfPublicAuthority, type VrfActionContext } from "./vrf-production-action-binding.js"
|
|
import type { ChangeEvidence } from "../modules/mcp/action-types.js"
|
|
|
|
export interface VrfTicketSql {
|
|
query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[]; command?: string }>
|
|
}
|
|
export interface VrfTicketClaimConnection extends VrfTicketSql { release(destroy?: boolean): void }
|
|
/** Test injection must return a fresh unshared, nontransactional connection.
|
|
* Production always owns a pool checkout; a caller transaction is never used. */
|
|
export interface VrfTicketClaimConnections { connect(): Promise<VrfTicketClaimConnection> }
|
|
const ownedProductionConnections: VrfTicketClaimConnections = {
|
|
async connect() { return (await import("../db/index.js")).pool.connect() },
|
|
}
|
|
export class VrfProductionClaimOutcomeUnknown extends Error {
|
|
readonly requiresDurableOperationQuarantine = true
|
|
constructor(readonly ticketId: string) { super("VRF production ticket refused: claim outcome unknown; quarantine the operation, no retry or execution permitted") }
|
|
}
|
|
export interface VrfTicketCrypto { encrypt(value: string): Promise<string>; decrypt(value: string): Promise<string> }
|
|
const privateCrypto: VrfTicketCrypto = {
|
|
async encrypt(value) { return (await import("../modules/mcp/security.js")).encryptSecret(value) },
|
|
async decrypt(value) { return (await import("../modules/mcp/security.js")).decryptSecret(value) },
|
|
}
|
|
export interface VrfTicketContext extends VrfActionContext {
|
|
binding: VrfProductionBinding
|
|
connectionId: string
|
|
}
|
|
interface Guards {
|
|
/** Trusted fresh credential/permission/policy/plan check, never caller JSON. */
|
|
assertAuthority(): Promise<unknown>
|
|
/** Fresh trusted source-v3 endpoint/epoch/enabled check against context. */
|
|
assertCurrentSource(): Promise<unknown>
|
|
}
|
|
interface Shared extends Guards {
|
|
context: VrfTicketContext
|
|
request: VrfProductionRequest
|
|
secret: Uint8Array
|
|
crypto?: VrfTicketCrypto
|
|
now?: () => number
|
|
/** Server-owned currently running operation, never a tool/plan input. */
|
|
execution?: { operationId: string; stepIndex: number }
|
|
}
|
|
const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i
|
|
const proof = /^[a-f0-9]{64}$/
|
|
function must(value: unknown, reason: string): asserts value {
|
|
if (!value) throw new Error(`VRF production ticket refused: ${reason}`)
|
|
}
|
|
function validate(context: VrfTicketContext, request: VrfProductionRequest): void {
|
|
must(context && uuid.test(context.connectionId) && uuid.test(context.binding.planId) && Number.isSafeInteger(context.binding.serverId) && context.binding.serverId > 0 && proof.test(context.binding.sourceProof) && context.binding.actorId.length > 0, "invalid binding")
|
|
assertVrfActionContext(context, request)
|
|
}
|
|
function pinned<T extends Shared>(input: T): T {
|
|
must(input.secret instanceof Uint8Array && input.secret.byteLength >= 32 && input.secret.byteLength <= 4096 && typeof input.assertAuthority === "function" && typeof input.assertCurrentSource === "function", "missing trusted guards/sealing key")
|
|
if (input.execution) must(uuid.test(input.execution.operationId) && Number.isSafeInteger(input.execution.stepIndex) && input.execution.stepIndex >= 0, "invalid execution identity")
|
|
return { ...input, context: structuredClone(input.context), request: structuredClone(input.request), secret: Uint8Array.from(input.secret), ...(input.execution ? { execution: structuredClone(input.execution) } : {}) }
|
|
}
|
|
async function fence(input: Guards): Promise<void> {
|
|
await input.assertAuthority(); await input.assertCurrentSource(); await input.assertAuthority()
|
|
}
|
|
function canonical(value: unknown, depth = 0): string {
|
|
must(depth <= 24, "nested plan evidence")
|
|
if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return JSON.stringify(value)
|
|
if (Array.isArray(value)) return `[${value.map(child => canonical(child, depth + 1)).join(",")}]`
|
|
must(value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype, "invalid plan evidence")
|
|
return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => `${JSON.stringify(key)}:${canonical(child, depth + 1)}`).join(",")}}`
|
|
}
|
|
function envelopeValue(value: unknown): string {
|
|
must(value && typeof value === "object" && !Array.isArray(value) && typeof (value as { sealed?: unknown }).sealed === "string", "missing encrypted plan evidence")
|
|
return (value as { sealed: string }).sealed
|
|
}
|
|
function record(value: unknown, reason: string): Record<string, unknown> {
|
|
must(value && typeof value === "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype, reason)
|
|
return value as Record<string, unknown>
|
|
}
|
|
function timestampMs(value: unknown): number {
|
|
must(value instanceof Date || typeof value === "string" && value.length > 0 && value.length <= 64, "invalid stored timestamp")
|
|
const result = value instanceof Date ? value.getTime() : Date.parse(value)
|
|
must(Number.isSafeInteger(result) && result >= 0, "invalid stored timestamp")
|
|
return result
|
|
}
|
|
|
|
/** Verify the real plan's owner/action/version and its encrypted single VRF
|
|
* step. An arbitrary caller-supplied plan UUID or ownership assertion is not
|
|
* sufficient. Preparation invokes this inside the caller's plan transaction. */
|
|
async function authoritativePlan(sql: VrfTicketSql, input: Shared, lock: boolean): Promise<{ expiresAtMs: number }> {
|
|
const c = input.context
|
|
const authority = vrfPublicAuthority(c)
|
|
const { rows } = await sql.query(`SELECT p.id,p.connection_id,p.operation_id,p.operation_version,p.state,p.expires_at,p.evidence,c.owner_id
|
|
FROM mcp_plans p JOIN mcp_connections c ON c.id=p.connection_id JOIN servers s ON s.id=$3
|
|
WHERE p.id=$1 AND p.connection_id=$2 AND c.owner_id=$4 AND p.operation_id=$5 AND p.operation_version=$6
|
|
AND (($7::uuid IS NULL AND p.state IN ('draft','awaiting-approval','approved')) OR
|
|
($7::uuid IS NOT NULL AND p.state='executing' AND p.approved_by IS NOT NULL AND EXISTS (
|
|
SELECT 1 FROM mcp_operations o JOIN mcp_operation_steps st ON st.operation_id=o.id
|
|
WHERE o.id=$7 AND o.plan_id=p.id AND o.connection_id=p.connection_id AND o.state='running'
|
|
AND st.step_index=$8 AND st.state='intent' AND st.server_id=s.id)))
|
|
AND p.expires_at>clock_timestamp() AND s.enabled=true
|
|
${lock ? "FOR UPDATE OF p,c" : ""}`, [c.binding.planId, c.connectionId, c.binding.serverId, c.binding.actorId, authority.id, authority.version, input.execution?.operationId ?? null, input.execution?.stepIndex ?? null])
|
|
await fence(input)
|
|
must(rows.length === 1, "unknown/revoked/expired authoritative plan")
|
|
const plan = rows[0], codec = input.crypto ?? privateCrypto
|
|
const plaintext = await codec.decrypt(envelopeValue(plan.evidence))
|
|
await fence(input)
|
|
must(plaintext.length <= 2 * 1024 * 1024, "oversized plan evidence")
|
|
const evidence = record(JSON.parse(plaintext) as unknown, "invalid encrypted plan evidence")
|
|
if (input.execution) must(evidence.vrfProductionAdmission === true, "executing plan lacks VRF production admission")
|
|
const target = record(evidence.target, "plan scope/step ambiguity")
|
|
must(target.scope === "servers" && Array.isArray(target.serverIds) && target.serverIds.length === 1 && target.serverIds[0] === c.binding.serverId && Array.isArray(evidence.steps) && evidence.steps.length === 1, "plan scope/step ambiguity")
|
|
const step = record(evidence.steps[0], "plan is not exact VRF step")
|
|
const native = record(step.step, "plan is not exact VRF step")
|
|
must(step.kind === "ros" && native.resource === "vrf" && native.serverId === c.binding.serverId, "plan is not exact VRF step")
|
|
const request = { action: native.action === "update" ? "patch" : native.action, ...(native.id !== undefined ? { id: native.id } : {}), fields: native.fields, ...(native.placeBeforeId !== undefined ? { placeBeforeId: native.placeBeforeId } : {}) }
|
|
must(canonical(request) === canonical(input.request), "request differs from authoritative plan")
|
|
assertVrfAliasEvidence(c, input.request, evidence as unknown as Pick<ChangeEvidence, "snapshots" | "requiresHuman">)
|
|
return { expiresAtMs: timestampMs(plan.expires_at) }
|
|
}
|
|
|
|
export interface PrepareVrfProductionTicketInput extends Shared {
|
|
requiredCatalogs?: readonly string[]
|
|
/** Existing trusted plan transaction (including the actual plan INSERT if
|
|
* new). The caller owns BEGIN/COMMIT. Never create a synthetic plan here. */
|
|
transaction<T>(work: (sql: VrfTicketSql) => Promise<T>): Promise<T>
|
|
adapter?: VrfProductionReadAdapter
|
|
/** Production runtime matches its already encrypted original projections;
|
|
* raw preparation must not silently adopt a later dependency snapshot. */
|
|
assertPreparedSnapshot?(snapshot: VrfProductionSnapshot): Promise<void>
|
|
onAdmission?(admission: VrfProductionAdmission, snapshot: VrfProductionSnapshot): Promise<void>
|
|
}
|
|
/** Server-internal preparation primitive. No public tool is registered. The
|
|
* returned reference contains no sealed payload, raw configuration or grant. */
|
|
export async function prepareVrfProductionTicket(input: PrepareVrfProductionTicketInput): Promise<{ ticketId: string; expiresAt: string; executionAvailable: false }> {
|
|
input = pinned(input)
|
|
must(!input.execution, "execution cannot mint a preparation ticket")
|
|
validate(input.context, input.request)
|
|
await fence(input)
|
|
return input.transaction(async sql => {
|
|
const plan = await authoritativePlan(sql, input, true)
|
|
const snapshot = await readVrfProductionSnapshot({ serverId: input.context.binding.serverId, expectedSourceProof: input.context.binding.sourceProof, request: input.request, requiredCatalogs: input.requiredCatalogs, assertAuthority: () => fence(input), adapter: input.adapter })
|
|
await input.assertPreparedSnapshot?.(snapshot)
|
|
await fence(input)
|
|
const now = (input.now ?? Date.now)(), planExpiry = plan.expiresAtMs
|
|
const ttlMs = Math.min(300000, planExpiry - now)
|
|
const issued = sealVrfProductionAdmission({ snapshot, binding: input.context.binding, request: input.request, secret: input.secret, now, ttlMs })
|
|
await input.onAdmission?.(structuredClone(issued.admission), snapshot)
|
|
const envelope = JSON.stringify({ context: input.context, sealed: issued.sealed })
|
|
must(envelope.length <= 2 * 1024 * 1024, "oversized private envelope")
|
|
const ciphertext = await (input.crypto ?? privateCrypto).encrypt(envelope)
|
|
await fence(input)
|
|
const c = input.context
|
|
const authority = vrfPublicAuthority(c)
|
|
const { rows } = await sql.query(`INSERT INTO vrf_production_tickets(ticket_id,plan_id,connection_id,server_id,owner_id,action_id,action_version,source_proof,digest,ciphertext,issued_at,expires_at)
|
|
SELECT $1,p.id,p.connection_id,$4,$5,$6,$7,$8,$9,$10,$11,$12
|
|
FROM mcp_plans p JOIN mcp_connections c ON c.id=p.connection_id JOIN servers s ON s.id=$4
|
|
WHERE p.id=$2 AND p.connection_id=$3 AND c.owner_id=$5 AND p.operation_id=$13 AND p.operation_version=$14 AND s.enabled=true
|
|
AND p.state IN ('draft','awaiting-approval','approved') AND p.expires_at>=$12 AND $12>clock_timestamp()
|
|
RETURNING ticket_id`, [issued.admission.ticketId, c.binding.planId, c.connectionId, c.binding.serverId, c.binding.actorId, c.actionId, c.actionVersion, c.binding.sourceProof, issued.digest, ciphertext, new Date(issued.admission.issuedAt), new Date(issued.admission.expiresAt), authority.id, authority.version])
|
|
must(rows.length === 1, "plan changed before ticket issue")
|
|
await fence(input)
|
|
return { ticketId: issued.admission.ticketId, expiresAt: new Date(issued.admission.expiresAt).toISOString(), executionAvailable: false as const }
|
|
})
|
|
}
|
|
|
|
export interface StoredVrfProductionTicketInput extends Shared {
|
|
/** Read-only inspection handle. Never used for claim writes. */
|
|
sql: VrfTicketSql
|
|
/** Absent in production: use a fresh owned connection from the real pool. */
|
|
claimConnections?: VrfTicketClaimConnections
|
|
ticketId: string
|
|
/** Trusted fresh readVrfProductionSnapshot result, never caller JSON. */
|
|
snapshot: VrfProductionSnapshot
|
|
}
|
|
export async function inspectStoredVrfProductionTicket(input: StoredVrfProductionTicketInput): Promise<ReturnType<typeof inspectVrfProductionAdmission> & { privateSealed?: string }> {
|
|
input = pinned(input)
|
|
validate(input.context, input.request); must(uuid.test(input.ticketId), "invalid ticket ID")
|
|
await fence(input)
|
|
await authoritativePlan(input.sql, input, false)
|
|
const c = input.context
|
|
const { rows } = await input.sql.query(`SELECT ciphertext,digest,issued_at,expires_at FROM vrf_production_tickets
|
|
WHERE ticket_id=$1 AND plan_id=$2 AND connection_id=$3 AND server_id=$4 AND owner_id=$5 AND action_id=$6 AND action_version=$7
|
|
AND source_proof=$8 AND state='issued' AND expires_at>clock_timestamp()`, [input.ticketId, c.binding.planId, c.connectionId, c.binding.serverId, c.binding.actorId, c.actionId, c.actionVersion, c.binding.sourceProof])
|
|
await fence(input)
|
|
must(rows.length === 1, "unknown/claimed/expired ticket")
|
|
const row = rows[0]
|
|
must(typeof row.ciphertext === "string" && row.ciphertext.length <= 4 * 1024 * 1024, "oversized/missing ciphertext")
|
|
const plaintext = await (input.crypto ?? privateCrypto).decrypt(row.ciphertext)
|
|
await fence(input)
|
|
must(plaintext.length <= 2 * 1024 * 1024, "oversized private envelope")
|
|
const envelope = record(JSON.parse(plaintext) as unknown, "invalid private envelope")
|
|
must(canonical(envelope.context) === canonical(c), "encrypted action/owner binding changed")
|
|
must(typeof envelope.sealed === "string", "missing signed private envelope")
|
|
const inspected = inspectVrfProductionAdmission({ sealed: envelope.sealed, snapshot: input.snapshot, binding: c.binding, request: input.request, secret: input.secret, now: (input.now ?? Date.now)() })
|
|
must(inspected.admission.ticketId === input.ticketId && inspected.digest === row.digest && inspected.admission.issuedAt === timestampMs(row.issued_at) && inspected.admission.expiresAt === timestampMs(row.expires_at), "stored ticket HMAC/digest/lifetime mismatch")
|
|
return { ...inspected, ...(input.execution ? { privateSealed: envelope.sealed } : {}) }
|
|
}
|
|
|
|
/** A successful claim is a spent review/proof attempt, never a mutation grant.
|
|
* There is no reset, delete, upsert or retry path. On lost ACK after committed
|
|
* CAS, or revocation detected afterwards, the durable row remains claimed. */
|
|
export async function claimStoredVrfProductionTicket(input: StoredVrfProductionTicketInput): Promise<ReturnType<typeof inspectVrfProductionAdmission> & { executionAvailable: false; privateSealed?: string }> {
|
|
input = pinned(input)
|
|
const inspected = await inspectStoredVrfProductionTicket(input)
|
|
await fence(input)
|
|
const c = input.context
|
|
const authority = vrfPublicAuthority(c)
|
|
let connection: VrfTicketClaimConnection
|
|
try { connection = await (input.claimConnections ?? ownedProductionConnections).connect() }
|
|
catch {
|
|
try { await fence(input) } catch { /* no claim/result */ }
|
|
throw new VrfProductionClaimOutcomeUnknown(input.ticketId)
|
|
}
|
|
let beginDispatched = false, transactionStarted = false, updateDispatched = false, updateCompleted = false, commitDispatched = false, committed = false, destroy = false
|
|
try {
|
|
await fence(input)
|
|
beginDispatched = true
|
|
await connection.query("BEGIN")
|
|
transactionStarted = true
|
|
updateDispatched = true
|
|
const result = await connection.query(`UPDATE vrf_production_tickets t SET state='claimed',claimed_at=clock_timestamp()
|
|
FROM mcp_plans p,mcp_connections c,servers s
|
|
WHERE t.ticket_id=$1 AND t.digest=$2 AND t.state='issued' AND t.expires_at>clock_timestamp()
|
|
AND t.plan_id=$3 AND t.connection_id=$4 AND t.server_id=$5 AND t.owner_id=$6 AND t.action_id=$7 AND t.action_version=$8 AND t.source_proof=$9
|
|
AND p.id=t.plan_id AND p.connection_id=t.connection_id AND p.operation_id=$12 AND p.operation_version=$13
|
|
AND (($10::uuid IS NULL AND p.state IN ('draft','awaiting-approval','approved')) OR
|
|
($10::uuid IS NOT NULL AND p.state='executing' AND p.approved_by IS NOT NULL AND EXISTS (
|
|
SELECT 1 FROM mcp_operations o JOIN mcp_operation_steps st ON st.operation_id=o.id
|
|
WHERE o.id=$10 AND o.plan_id=p.id AND o.connection_id=p.connection_id AND o.state='running'
|
|
AND st.step_index=$11 AND st.state='intent' AND st.server_id=s.id)))
|
|
AND p.expires_at>clock_timestamp()
|
|
AND c.id=t.connection_id AND c.owner_id=t.owner_id AND s.id=t.server_id AND s.enabled=true RETURNING t.ticket_id`, [input.ticketId, inspected.digest, c.binding.planId, c.connectionId, c.binding.serverId, c.binding.actorId, c.actionId, c.actionVersion, c.binding.sourceProof, input.execution?.operationId ?? null, input.execution?.stepIndex ?? null, authority.id, authority.version])
|
|
updateCompleted = true
|
|
must(result.rows.length === 1, "unknown/replayed/revoked claim")
|
|
commitDispatched = true
|
|
const commit = await connection.query("COMMIT")
|
|
if (input.execution) must(commit.command === "COMMIT", "execution claim COMMIT not acknowledged")
|
|
committed = true
|
|
// Post-claim failure intentionally happens after COMMIT; revocation must
|
|
// never roll a successfully claimed ticket back into the issued state.
|
|
await fence(input)
|
|
return { ...inspected, executionAvailable: false }
|
|
} catch (error) {
|
|
if ((beginDispatched && !transactionStarted || commitDispatched || updateDispatched && !updateCompleted) && !committed) {
|
|
destroy = true
|
|
// Never send ROLLBACK or replay UPDATE after an uncertain COMMIT. The
|
|
// future executor must quarantine its durable operation intent here.
|
|
// If the DB never committed, this service cannot assert a spent bit.
|
|
try { await fence(input) } catch { /* no result or execution */ }
|
|
throw new VrfProductionClaimOutcomeUnknown(input.ticketId)
|
|
}
|
|
if (transactionStarted && !committed) {
|
|
try { await connection.query("ROLLBACK") } catch { destroy = true }
|
|
}
|
|
throw error
|
|
} finally {
|
|
connection.release(destroy)
|
|
}
|
|
}
|