import assert from "node:assert/strict" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import type { ActionContext } from "./action-types.js" import type { ConnectionRow } from "./store.js" import type { ServerRow } from "../servers/repository/servers-repository.js" import { createIpsecServerInitAdapter, ipsecServerInitActionSchema } from "./ipsec-server-init-actions.js" import { redact } from "./security.js" const operation = "network.ipsec.server.init", sourceProof = "a".repeat(64), beforeProof = "b".repeat(64), afterProof = "c".repeat(64) const principal = { connectionId: randomUUID(), credentialId: randomUUID(), credentialExpiresAt: new Date(Date.now() + 600000).toISOString() } const connection = { id: principal.connectionId, owner_id: "fixture-owner", owner_permissions: ["mm:network:write"], generation: "fixture-generation", owner_valid_until: new Date(Date.now() + 600000), policy: { mode: "autonomous", status: "active", expiresAt: principal.credentialExpiresAt, permissions: ["mm:network:write"], scope: { serverIds: [1], operationIds: [operation], allowGlobal: false } } } as ConnectionRow const context = { principal, connection } as ActionContext const request = { serverId: 1, request: { serverEndpoint: "vpn.example.test", poolCidr: "10.77.0.0/24", dns: "192.0.2.53", caDaysValid: 3650, serverDaysValid: 900, clientDaysValid: 180, createNatRule: true } } assert.equal(ipsecServerInitActionSchema.safeParse(request).success, true) for (const key of ["psk", "passphrase", "privateKey", "export", "unknown"]) assert.equal(ipsecServerInitActionSchema.safeParse({ ...request, request: { ...request.request, [key]: "NEVER_RAW" } }).success, false) const oldQuery = pool.query, oldConnect = pool.connect pool.query = (() => { throw Error("Real SQL forbidden") }) as never; pool.connect = (() => { throw Error("Real SQL forbidden") }) as never try { const sealed = new Map() let current = structuredClone(connection), proof = beforeProof, endpoint = sourceProof, writes = 0, history = true let stored: Record[] = [], inject: (() => void) | undefined const adapter = createIpsecServerInitAdapter({ connection: async () => current, router: async () => ({ server: { id: 1 } as ServerRow, client: {} as never }), sourceProof: async () => endpoint, read: async (_server, authorize) => { await authorize?.(); return { source: sourceProof, proof, catalogs: {}, protections: [{ object_ref: { kind: "certificate", id: "*protected" } }] } }, seal: async value => { const key = `sealed:${randomUUID()}`; sealed.set(key, value); return key }, open: async value => sealed.get(value)!, query: async () => stored, verifiedAccess: async () => {}, checkpoint: async () => {}, plan: (() => ({ commands: [{ action: "create", path: "/certificate", fields: {} }], companions: [{ kind: "ipsec_peer", id: "*p" }], target: { kind: "ipsec_server", id: "1" } })) as never, init: (async (_server: unknown, body: Record, expected: string, authorize: () => Promise, options: { receiptId: string; checkpoint: (value: unknown) => Promise }) => { assert.equal(expected, beforeProof); assert.deepEqual(body, { ...request.request, serverId: 1 }) await authorize(); inject?.(); await authorize(); writes++; proof = afterProof await options.checkpoint({ receiptId: options.receiptId, completedCommands: 1, commandCount: 1, afterProof }) return { ok: true, verified: true, receiptId: options.receiptId, serverId: 1, commandCount: 1, completedCommands: 1, confirmedWrites: 1, afterProof, historyRecorded: history, revisionRecorded: history, automaticReplay: false, forwardingVerified: false, summary: { raw: "NEVER_RAW_SUMMARY" } } }) as never, }) const prepare = async () => { const evidence = await adapter.prepare(request, context) assert.equal(evidence.requiresHuman, true); assert.equal(evidence.mutationCost, 2) assert(evidence.objects.some(row => row.id === "*p")); assert(evidence.objects.some(row => row.id === "*protected")) assert(!JSON.stringify(evidence).includes("NEVER_RAW")) const step = evidence.steps[0]; if (step.kind !== "service") throw Error("service expected") return step.input } const reset = () => { proof = beforeProof; current = structuredClone(connection); endpoint = sourceProof; inject = undefined; history = true; stored = [] } let input = await prepare(), receipt = await adapter.service.execute(input) assert.equal(writes, 1); assert(!JSON.stringify(receipt).includes("NEVER_RAW")); assert.equal(await adapter.service.verify!(input, receipt), true) stored = [{ connection_id: principal.connectionId, state: "verified", intended_state: redact({ kind: "service", service: operation, input }), result: receipt }] assert.equal((await adapter.service.reconcile!(input, async () => {})).matchesDesiredState, true) for (const field of ["historyRecorded", "revisionRecorded", "verified", "receiptId", "commandCount", "afterProof", "serverId"]) { stored[0].result = { ...receipt as object, [field]: "changed" }; assert.equal((await adapter.service.reconcile!(input, async () => {})).matchesDesiredState, false) } reset(); input = await prepare(); history = false; receipt = await adapter.service.execute(input); assert.equal(await adapter.service.verify!(input, receipt), false) for (const mutate of [() => { proof = afterProof }, () => { endpoint = "d".repeat(64) }, () => { current.policy.status = "paused" }, () => { current.owner_permissions = [] }, () => { current.generation = "changed" }, () => { current.policy.scope.serverIds = [] }, () => { current.policy.scope.operationIds = [] }]) { reset(); input = await prepare(); const start = writes; mutate(); await assert.rejects(adapter.service.execute(input)); assert.equal(writes, start) } reset(); input = await prepare(); inject = () => { current.policy.status = "paused" }; const start = writes; await assert.rejects(adapter.service.execute(input)); assert.equal(writes, start) reset(); input = await prepare(); const aborted = new AbortController(); aborted.abort(); await assert.rejects(adapter.prepare(request, { ...context, signal: aborted.signal })) console.log("IPsec init adapter: all REST fields, mandatory approval, sealed request, source/grant/owner cancellation, checkpoint/history and receipt reconciliation, no model summary or private inputs") } finally { pool.query = oldQuery; pool.connect = oldConnect }