import assert from "node:assert/strict" import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from "node:crypto" import { VRF_PRODUCTION_REQUIRED_CATALOGS, type VrfProductionRequest, type VrfProductionSnapshot } from "./vrf-production-admission.js" import { claimStoredVrfProductionTicket, inspectStoredVrfProductionTicket, prepareVrfProductionTicket, type StoredVrfProductionTicketInput, type VrfTicketCrypto, type VrfTicketSql, type VrfTicketClaimConnections } from "./vrf-production-ticket-store.js" import { VRF_PRODUCTION_RAW_PATHS, type VrfProductionRawClient } from "./vrf-production-read.js" /** Actual SQL acceptance helper: caller supplies an isolated migrated PostgreSQL * database and real transaction implementation. Import is inert; no production * database, RouterOS client, environment or app configuration is opened here. */ export async function runVrfProductionTicketSqlAcceptance(input: { sql: VrfTicketSql; claimConnections: VrfTicketClaimConnections; transaction(work: (sql: VrfTicketSql) => Promise): Promise }): Promise<{ passed: true; cases: number }> { const key = randomBytes(32), secret = randomBytes(32), sourceProof = "a".repeat(64) const codec: VrfTicketCrypto = { async encrypt(value) { const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", key, iv); const data = Buffer.concat([cipher.update(value), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), data]).toString("base64") }, async decrypt(value) { const data = Buffer.from(value, "base64"), cipher = createDecipheriv("aes-256-gcm", key, data.subarray(0, 12)); cipher.setAuthTag(data.subarray(12, 28)); return Buffer.concat([cipher.update(data.subarray(28)), cipher.final()]).toString() }, } const connectionId = randomUUID(), owner = `vrf-ticket-${randomUUID()}` const server = (await input.sql.query("INSERT INTO servers(name,host,enabled) VALUES($1,'192.0.2.254',true) RETURNING id", [owner])).rows[0] const serverId = Number(server.id) await input.sql.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation) VALUES($1,$2,$2,'{}','{}','test')", [connectionId, owner]) const plans: string[] = [] let cases = 0 try { const fixture = async () => { const planId = randomUUID(), request: VrfProductionRequest = { action: "patch", id: "*1", fields: { name: "customers" } } plans.push(planId) const evidence = { target: { scope: "servers", serverIds: [serverId] }, steps: [{ kind: "ros", step: { serverId, resource: "vrf", action: "update", id: "*1", fields: request.fields } }] } await input.sql.query(`INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at) VALUES($1,$2,'ros.vrf.update',2,1,'test','{}',$3::jsonb,'draft',clock_timestamp()+interval '5 minutes')`, [planId, connectionId, JSON.stringify({ sealed: await codec.encrypt(JSON.stringify(evidence)) })]) const catalogs: VrfProductionSnapshot["catalogs"] = Object.fromEntries(VRF_PRODUCTION_REQUIRED_CATALOGS.map(resource => [resource, []])) catalogs.ip_settings = [{}]; catalogs.ipv6_settings = [{}] catalogs.vrf = [{ ".id": "*1", name: "production", interfaces: "ether1", disabled: "false" }, { ".id": "*2", name: "main", interfaces: "all", builtin: "true" }] catalogs.interface_inventory = [{ ".id": "*10", name: "ether1", type: "ether" }] catalogs.ethernet = [{ ".id": "*20", name: "ether1", comment: "raw-private-fixture" }] const context = { binding: { serverId, sourceProof, actorId: owner, planId }, connectionId, actionId: "ros.vrf.update" as const, actionVersion: 2 } let authorized = true, sourceCurrent = true const guards = { async assertAuthority() { assert.ok(authorized, "revoked") }, async assertCurrentSource() { assert.ok(sourceCurrent, "source changed") } } const client: VrfProductionRawClient = { async get(path: string): Promise { const resource = Object.keys(VRF_PRODUCTION_RAW_PATHS).find(key => VRF_PRODUCTION_RAW_PATHS[key] === path)!; return structuredClone(catalogs[resource]) as T } } const prepared = await prepareVrfProductionTicket({ context, request, secret, crypto: codec, ...guards, transaction: input.transaction, adapter: { async resolve() { return { serverId, sourceProof, enabled: true, client } } } }) assert.equal(prepared.executionAvailable, false) assert.equal(JSON.stringify(prepared).includes("raw-private-fixture"), false) const stored = (await input.sql.query("SELECT * FROM vrf_production_tickets WHERE ticket_id=$1", [prepared.ticketId])).rows[0] assert.equal(stored.state, "issued"); assert.equal(stored.ciphertext.includes("raw-private-fixture"), false) const claim: StoredVrfProductionTicketInput = { context, request, secret, crypto: codec, ...guards, sql: input.sql, claimConnections: input.claimConnections, ticketId: prepared.ticketId, snapshot: { projection: "raw-native-v1", serverId, sourceProof, catalogs } } return { claim, stored, prepared, revoke() { authorized = false }, changeSource() { sourceCurrent = false } } } const concurrent = await fixture() const results = await Promise.allSettled([claimStoredVrfProductionTicket(concurrent.claim), claimStoredVrfProductionTicket(concurrent.claim)]) assert.equal(results.filter(result => result.status === "fulfilled").length, 1) await assert.rejects(claimStoredVrfProductionTicket(concurrent.claim)); cases++ const badDigest = await fixture() await input.sql.query("UPDATE vrf_production_tickets SET digest=$2 WHERE ticket_id=$1", [badDigest.prepared.ticketId, "b".repeat(64)]) await assert.rejects(claimStoredVrfProductionTicket(badDigest.claim), /HMAC\/digest/); cases++ const expired = await fixture() await input.sql.query("UPDATE vrf_production_tickets SET issued_at=clock_timestamp()-interval '10 minutes',expires_at=clock_timestamp()-interval '9 minutes' WHERE ticket_id=$1", [expired.prepared.ticketId]) await assert.rejects(claimStoredVrfProductionTicket(expired.claim)); cases++ const revoked = await fixture(); revoked.revoke() await assert.rejects(claimStoredVrfProductionTicket(revoked.claim)); cases++ const changed = await fixture(); changed.changeSource() await assert.rejects(claimStoredVrfProductionTicket(changed.claim)); cases++ const ownerChanged = await fixture() await assert.rejects(claimStoredVrfProductionTicket({ ...ownerChanged.claim, context: { ...ownerChanged.claim.context, binding: { ...ownerChanged.claim.context.binding, actorId: "other-owner" } } })); cases++ const actionChanged = await fixture() await input.sql.query("UPDATE mcp_plans SET operation_version=3 WHERE id=$1", [actionChanged.claim.context.binding.planId]) await assert.rejects(claimStoredVrfProductionTicket(actionChanged.claim)); cases++ const lostAck = await fixture() const uncertainConnections: VrfTicketClaimConnections = { async connect() { const connection = await input.claimConnections.connect(); return { async query(text, values) { const result = await connection.query(text, values); if (text === "COMMIT") throw new Error("lost COMMIT ACK"); return result }, release(destroy) { connection.release(destroy) } } } } await assert.rejects(claimStoredVrfProductionTicket({ ...lostAck.claim, claimConnections: uncertainConnections }), /outcome unknown/) assert.equal((await input.sql.query("SELECT state FROM vrf_production_tickets WHERE ticket_id=$1", [lostAck.prepared.ticketId])).rows[0].state, "claimed") await assert.rejects(claimStoredVrfProductionTicket(lostAck.claim)); cases++ const revokeAfter = await fixture() const revokingConnections: VrfTicketClaimConnections = { async connect() { const connection = await input.claimConnections.connect(); return { async query(text, values) { const result = await connection.query(text, values); if (text === "COMMIT") revokeAfter.revoke(); return result }, release(destroy) { connection.release(destroy) } } } } await assert.rejects(claimStoredVrfProductionTicket({ ...revokeAfter.claim, claimConnections: revokingConnections })) assert.equal((await input.sql.query("SELECT state FROM vrf_production_tickets WHERE ticket_id=$1", [revokeAfter.prepared.ticketId])).rows[0].state, "claimed"); cases++ const hmac = await fixture() await assert.rejects(inspectStoredVrfProductionTicket({ ...hmac.claim, secret: randomBytes(32) }), /signature changed/); cases++ const callerRollback = await fixture() await assert.rejects(input.transaction(async callerTransaction => { await claimStoredVrfProductionTicket({ ...callerRollback.claim, sql: callerTransaction }) throw new Error("caller downstream failure") }), /caller downstream failure/) assert.equal((await input.sql.query("SELECT state FROM vrf_production_tickets WHERE ticket_id=$1", [callerRollback.prepared.ticketId])).rows[0].state, "claimed") await assert.rejects(claimStoredVrfProductionTicket(callerRollback.claim)); cases++ return { passed: true, cases } } finally { await input.sql.query("DELETE FROM vrf_production_tickets WHERE connection_id=$1", [connectionId]) await input.sql.query("DELETE FROM mcp_plans WHERE id=ANY($1::uuid[])", [plans]) await input.sql.query("DELETE FROM mcp_connections WHERE id=$1", [connectionId]) await input.sql.query("DELETE FROM servers WHERE id=$1", [serverId]) } }