import assert from "node:assert/strict" import { randomUUID } from "node:crypto" import { createServer } from "node:http" import { setTimeout as delay } from "node:timers/promises" import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp" import { pool } from "../../db/index.js" import type { AuthUser } from "../../lib/permissions.js" import { ipsecPeerDeletePaths } from "../../services/ipsec-peer-delete.js" import { approvePlan, applyPlan, invokeMcpTool } from "./runtime.js" import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js" import { hookConfigurationAudits } from "../../test/fixtures/configuration-audit-commit.js" /** Owned temporary PostgreSQL + loopback HTTP acceptance. The fixture models * native ACK/defaults and explicit scalar rename projections. It is not CHR * acceptance or a claim about forwarding or real RouterOS rename behavior. */ export async function acceptIpsecNativeWrite(actor: AuthUser) { const serverId = 187, peerPath = "/ip/ipsec/peer", identityPath = "/ip/ipsec/identity", profilePath = "/ip/ipsec/profile", certPath = "/certificate" const base: Record[]> = Object.fromEntries(ipsecPeerDeletePaths.map(path => [path, []])) base[profilePath] = [{ ".id": "*d1", name: "default", default: "true", dynamic: "false", "dh-group": "modp2048", opaque: "NEVER_PROFILE_OPAQUE" }] base[peerPath] = [{ ".id": "*p1", name: "existing-peer", profile: "default", address: "192.0.2.1", "exchange-mode": "ike2", passive: "false", disabled: "true", certificate: "fixture-ca", opaque: "NEVER_PEER_OPAQUE" }] base[identityPath] = [{ ".id": "*i1", peer: "existing-peer", certificate: "fixture-ca", "remote-certificate": "*c1", disabled: "true", secret: "NEVER_IDENTITY_SECRET", opaque: "NEVER_IDENTITY_OPAQUE" }] base["/ip/ipsec/policy"] = [{ ".id": "*s1", peer: "existing-peer", dynamic: "false", template: "false", opaque: "NEVER_POLICY_OPAQUE" }] base[certPath] = [{ ".id": "*c1", name: "fixture-ca", trusted: "false", "private-key": "NEVER_CERTIFICATE_KEY", opaque: "NEVER_CERT_OPAQUE" }, { ".id": "*c2", name: "fixture-child", ca: "fixture-ca", trusted: "false", opaque: "NEVER_CHILD_OPAQUE" }] let catalogs = structuredClone(base), mode = "normal", reads = 0, puts = 0, patches = 0, nextId = 0 let connectionId: string | undefined, afterIntent: (() => void) | undefined const query = pool.query.bind(pool), commands: Array<{ method: string; path: string; body: Record }> = [] const reset = () => { catalogs = structuredClone(base); mode = "normal"; afterIntent = undefined } const router = createServer(async (req, res) => { const path = decodeURIComponent((req.url ?? "").replace(/^\/rest/, "")) res.setHeader("content-type", "application/json") if (req.method === "GET") { reads++; res.end(JSON.stringify(catalogs[path] ?? [])); return } if (!(req.method === "PUT" && path === peerPath) && !(req.method === "PATCH" && path === `${certPath}/*c1`)) { res.statusCode = 405; res.end("{}"); return } let text = ""; for await (const chunk of req) text += chunk const body = JSON.parse(text) as Record commands.push({ method: req.method!, path, body }) let assigned: string | undefined if (req.method === "PUT") { puts++; assigned = `*new${++nextId}` if (mode !== "ignored") catalogs[peerPath]!.push({ ".id": assigned, ...body, profile: body.profile === "*d1" ? "default" : body.profile ?? "default", "exchange-mode": body["exchange-mode"] ?? "main", passive: body.passive ?? "false", disabled: body.disabled ?? "false", "native-extra-default": "observed-only-after-ack" }) } else { patches++ if (mode !== "ignored") { const oldName = catalogs[certPath]![0]!.name! Object.assign(catalogs[certPath]![0]!, body) if (body.name && mode !== "rename-no-refs") { for (const row of catalogs[certPath]!) if (row.ca === oldName) row.ca = body.name for (const parent of [identityPath, peerPath]) for (const row of catalogs[parent]!) for (const field of ["certificate", "remote-certificate"]) if (row[field] === oldName) row[field] = body.name } } } if (mode === "collateral") catalogs[identityPath]![0]!["new-foreign-field"] = "NEVER_FOREIGN_OPAQUE" if (mode === "lost") { req.socket.destroy(); return } res.end(JSON.stringify(assigned ? { ".id": assigned } : {})) }) await new Promise(resolve => router.listen(0, "127.0.0.1", resolve)) const wait = async (id: string) => { for (const deadline = Date.now() + 140000; Date.now() < deadline;) { const row = (await query("SELECT state,verification,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0] if (!["pending", "running"].includes(row.state)) return row await delay(25) } throw Error("Native IPsec remains active; never replay") } try { assert.equal(Number((await query("SELECT count(*)::text AS n FROM servers WHERE id=$1", [serverId])).rows[0].n), 0) await query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES($1,'ipsec-native-write','127.0.0.1',$2,false,'NEVER_ENDPOINT')", [serverId, (router.address() as { port: number }).port]) const operations = ["ros.ipsec_peer.create", "ros.certificate.update", "operations.reconcile"] const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Native IPsec acceptance", mode: "autonomous", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:read", "mm:network:write", "mm:certificates:write"], scope: { serverIds: [serverId], operationIds: operations, allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 1000 } }), actor) connectionId = access.connection.id const principal = await authenticateMcpToken(access.token) const prepare = (kind: "peer" | "certificate", fields?: Record) => invokeMcpTool(principal, kind === "peer" ? "mm_ipsec_peer_create_plan" : "mm_certificate_update_plan", { serverId, ...(kind === "certificate" ? { id: "*c1" } : {}), fields: fields ?? (kind === "peer" ? { name: "new-peer", address: "192.0.2.9", disabled: true } : { trusted: true }) }) as Promise<{ planId: string; state: string }> const apply = async (plan: { planId: string }) => { await approvePlan(plan.planId, actor, true) const key = randomUUID(), operation = await applyPlan(principal, plan.planId, key) return { plan, key, operation, ...await wait(operation.id) } } const noReplay = async (result: Awaited>, total: number) => { await applyPlan(principal, result.plan.planId, result.key) assert.equal(puts + patches, total) } const notVerified = async (result: Awaited>) => { assert.notEqual(result.state, "applied"); assert.notEqual(result.verification, "passed") assert.equal((await query("SELECT count(*)::int AS n FROM mcp_operation_steps WHERE operation_id=$1 AND state='verified'", [result.operation.id])).rows[0].n, 0) const checked = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: result.operation.id }) as { results: Array<{ matchesDesiredState: boolean }> } assert.equal(checked.results[0]!.matchesDesiredState, false) } const unapproved = await prepare("peer") assert.equal(unapproved.state, "awaiting-approval") await assert.rejects(applyPlan(principal, unapproved.planId, randomUUID())); assert.equal(puts + patches, 0) let result = await apply(unapproved) assert.equal(result.state, "applied"); assert.equal(puts, 1) assert.equal(catalogs[peerPath]!.at(-1)!["native-extra-default"], "observed-only-after-ack") assert.deepEqual(catalogs[identityPath], base[identityPath]); assert.deepEqual(catalogs[certPath], base[certPath]) await noReplay(result, puts + patches) const receipt = (await query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [result.operation.id])).rows[0].result assert.equal(receipt.verified, true); assert.equal(receipt.forwardingVerified, false); assert.ok(!JSON.stringify(receipt).includes("NEVER_")) reset(); result = await apply(await prepare("certificate")); assert.equal(result.state, "applied") assert.deepEqual(commands.at(-1), { method: "PATCH", path: "/certificate/*c1", body: { trusted: "true" } }) assert.equal(catalogs[certPath]![0]!.opaque, "NEVER_CERT_OPAQUE") reset(); result = await apply(await prepare("certificate", { name: "renamed-ca", trusted: true })); assert.equal(result.state, "applied") assert.equal(catalogs[identityPath]![0]!.certificate, "renamed-ca"); assert.equal(catalogs[identityPath]![0]!["remote-certificate"], "*c1") assert.equal(catalogs[peerPath]![0]!.certificate, "renamed-ca"); assert.equal(catalogs[certPath]![1]!.ca, "renamed-ca") for (const kind of ["peer", "certificate"] as const) for (const fault of ["collateral", "lost", "ignored", ...(kind === "certificate" ? ["rename-no-refs"] : [])]) { reset(); const plan = await prepare(kind, kind === "certificate" ? { name: "renamed-ca", trusted: true } : undefined), before: number = puts + patches mode = fault; result = await apply(plan) assert.equal(result.state, fault === "lost" ? "unknown" : "partial", `${kind}/${fault}`) assert.equal(puts + patches, before + 1); await noReplay(result, before + 1); await notVerified(result) } reset(); const stale = await prepare("peer"), beforeStale = puts await approvePlan(stale.planId, actor, true); catalogs[profilePath]![0]!["dh-group"] = "modp3072" assert.equal((await wait((await applyPlan(principal, stale.planId, randomUUID())).id)).state, "rejected"); assert.equal(puts, beforeStale) reset(); const late = await prepare("peer"); await approvePlan(late.planId, actor, true) // Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query. const restoreAudits = hookConfigurationAudits({ afterIntentCommit: payload => { if (afterIntent && payload.method === "PUT") { const mutate = afterIntent; afterIntent = undefined; mutate() } } }) afterIntent = () => { catalogs[profilePath]![0]!["dh-group"] = "modp4096" } try { const before = puts, stopped = await wait((await applyPlan(principal, late.planId, randomUUID())).id) assert.notEqual(stopped.state, "applied"); assert.notEqual(stopped.verification, "passed"); assert.equal(afterIntent, undefined); assert.equal(puts, before) } finally { restoreAudits() } reset() const certOnly = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Certificates without network access", mode: "approval", expiresAt: new Date(Date.now() + 600000).toISOString(), permissions: ["mm:certificates:write"], scope: { serverIds: [serverId], operationIds: ["ros.certificate.update"], allowGlobal: false } }), actor) try { const before = reads await assert.rejects(invokeMcpTool(await authenticateMcpToken(certOnly.token), "mm_certificate_update_plan", { serverId, id: "*c1", fields: { trusted: true } })) assert.equal(reads, before, "missing network permission rejects before native GET") } finally { await setConnectionStatus(certOnly.connection.id, "paused", actor) } for (const [kind, id, operationKind] of [["ipsec_profile", "*d1", "peer"], ["ipsec_identity", "*i1", "peer"], ["ipsec_identity", "*i1", "certificate"]] as const) { reset(); const protection = randomUUID(), before: number = puts + patches await query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)", [protection, JSON.stringify({ kind, id, serverId, protection: "deny" }), actor.id]) try { await assert.rejects(prepare(operationKind)); assert.equal(puts + patches, before) } finally { await query("DELETE FROM mcp_protections WHERE id=$1", [protection]) } } for (const kind of ["peer", "certificate"] as const) { reset(); const sourceChanged = await prepare(kind) await approvePlan(sourceChanged.planId, actor, true) const beforeReads: number = reads, beforeWrites: number = puts + patches await query("UPDATE servers SET password='CHANGED_ENDPOINT_SECRET' WHERE id=$1", [serverId]) try { const stopped = await wait((await applyPlan(principal, sourceChanged.planId, randomUUID())).id) assert.equal(stopped.state, "rejected"); assert.equal(reads, beforeReads, "endpoint proof must reject before the first GET") assert.equal(puts + patches, beforeWrites) } finally { await query("UPDATE servers SET password='NEVER_ENDPOINT' WHERE id=$1", [serverId]) } } for (const kind of ["peer", "certificate"] as const) { reset(); const old = await prepare(kind), before: number = puts + patches await query("UPDATE mcp_plans SET operation_version=operation_version-1 WHERE id=$1", [old.planId]) await approvePlan(old.planId, actor, true); await assert.rejects(applyPlan(principal, old.planId, randomUUID()), error => (error as {code?:string}).code === "PLAN_EXPIRED"); assert.equal(puts + patches, before) } assert.ok(!JSON.stringify((await query("SELECT payload FROM mcp_audit WHERE connection_id=$1", [connectionId])).rows).includes("NEVER_")) console.log("Native IPsec SQL/loopback: peer ACK defaults, exact opaque conservation, certificate trust/linked rename, denied parent/identity, permission-before-GET, stale/late parent zero PUT, collateral/lost/no replay and old revisions fail closed; no CHR or forwarding claim") } finally { pool.query = query as typeof pool.query if (connectionId) await setConnectionStatus(connectionId, "paused", actor) await query("DELETE FROM mcp_protections WHERE object_ref->>'serverId'=$1", [String(serverId)]) await query("DELETE FROM servers WHERE id=$1", [serverId]) router.closeAllConnections(); await new Promise(resolve => router.close(() => resolve())) } }