214 lines
20 KiB
TypeScript
214 lines
20 KiB
TypeScript
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 Fastify from "fastify"
|
|
import { serializerCompiler, validatorCompiler } from "@fastify/type-provider-zod"
|
|
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
|
import { pool } from "../../db/index.js"
|
|
import type { AuthUser } from "../../lib/permissions.js"
|
|
import wireguardRoutes from "../../routes/wireguard.js"
|
|
import { wireguardInterfaceDependencyPaths } from "../../services/wireguard-interface-delete.js"
|
|
import { wireguardPublicKey } from "../../services/wireguard-interface-create.js"
|
|
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
|
|
import { encryptSecret } from "./security.js"
|
|
import { WIREGUARD_PEER_KEY_PURPOSE } from "./wireguard-interface-create-actions.js"
|
|
import { wireguardPeerCreatePlanSchema } from "./wireguard-peer-create-actions.js"
|
|
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
|
|
|
|
type Rows = Record<string, Record<string, string>[]>
|
|
/** Run only from the PostgreSQL acceptance harness; never uses a real router. */
|
|
export async function acceptWireguardPeerCreation(actor: AuthUser) {
|
|
const privateKey = Buffer.alloc(32, 61).toString("base64"), generatedKey = Buffer.alloc(32, 62).toString("base64"), publicKey = wireguardPublicKey(privateKey)
|
|
const initial: Rows = Object.fromEntries(wireguardInterfaceDependencyPaths.map(path => [path, []]))
|
|
initial["/interface/wireguard"] = [{ ".id": "*a", name: "wg-parent", disabled: "false", "public-key": wireguardPublicKey(generatedKey), "private-key": "NEVER_PARENT_PRIVATE", opaque: "NEVER_PARENT_OPAQUE" }]
|
|
initial["/interface/wireguard/peers"] = [{ ".id": "*f", interface: "wg-parent", "public-key": wireguardPublicKey(Buffer.alloc(32, 63).toString("base64")), disabled: "false", opaque: "NEVER_FOREIGN_PEER", rx: "0" }]
|
|
initial["/interface"] = [{ ".id": "*a", name: "wg-parent", type: "wg" }]
|
|
initial["/ip/address"] = [{ ".id": "*ip", address: "192.0.2.1/24", interface: "wg-parent", disabled: "false", dynamic: "false" }]
|
|
initial["/ipv6/address"] = [{ ".id": "*v6", address: "2001:db8:112::1/64", interface: "wg-parent", disabled: "false", dynamic: "false", advertise: "false" }]
|
|
initial["/routing/ospf/interface-template"] = [{ ".id": "*ospf", interfaces: "wg-parent", networks: "192.0.2.0/24,2001:db8:112::/64" }]
|
|
initial["/ip/vrf"] = [{ ".id": "*vrf", name: "owned", interfaces: "wg-parent" }]
|
|
initial["/ip/firewall/filter"] = [{ ".id": "*fw", "in-interface": "wg-parent", action: "accept" }]
|
|
let rows = structuredClone(initial), mode = "normal", reads = 0, commands: string[] = [], afterWrite: (() => Promise<unknown>) | undefined
|
|
const reset = () => { rows = structuredClone(initial); mode = "normal"; commands = []; afterWrite = undefined }
|
|
const router = createServer((req, res) => {
|
|
res.setHeader("content-type", "application/json")
|
|
const path = decodeURIComponent((req.url ?? "").slice(5)), base = "/interface/wireguard/peers"
|
|
if (req.method === "GET") {
|
|
reads++
|
|
if (mode === "provider-error" || mode === "dependency-error" && path === "/ip/address") { res.statusCode = 400; res.end('{"message":"NEVER_PROVIDER_SECRET"}'); return }
|
|
if (!Object.hasOwn(rows, path)) { res.statusCode = 404; res.end("{}"); return }
|
|
rows[base][0].rx = String(reads)
|
|
res.end(JSON.stringify(rows[path])); return
|
|
}
|
|
if (!["PUT", "PATCH"].includes(req.method ?? "") || !(path === base || path === base + "/*c")) { res.statusCode = 400; res.end("{}"); return }
|
|
let raw = ""
|
|
req.on("data", chunk => { raw += chunk }); req.on("end", async () => {
|
|
const body = JSON.parse(raw) as Record<string, string>
|
|
commands.push(req.method + " " + path)
|
|
if (mode !== "ignored") {
|
|
if (req.method === "PUT") {
|
|
const row: Record<string, string> = { ".id": "*c", ...body, opaque: "NEVER_NEW_NATIVE_DEFAULT" }
|
|
if (row["private-key"] === "auto") row["private-key"] = generatedKey
|
|
rows[base].push(row)
|
|
} else Object.assign(rows[base].find(row => row[".id"] === "*c")!, body)
|
|
}
|
|
if (mode === "collateral") rows["/ip/address"][0].comment = "NEVER_COLLATERAL"
|
|
if (mode === "parent-drift") rows["/interface/wireguard"][0].opaque = "NEVER_CHANGED_PARENT"
|
|
if (mode === "staged-collateral" && commands.length === 2) rows[base][1].opaque = "NEVER_CHANGED_STAGED"
|
|
if (afterWrite) { const hook = afterWrite; afterWrite = undefined; await hook() }
|
|
if (mode === "lost") { req.socket.destroy(); return }
|
|
res.end("{}")
|
|
})
|
|
})
|
|
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
|
const rest = Fastify(); rest.setValidatorCompiler(validatorCompiler); rest.setSerializerCompiler(serializerCompiler)
|
|
const secretIds: string[] = []
|
|
const secret = async (purpose: string, value: string, serverId: number | null = 112, owner = actor.id) => {
|
|
const id = randomUUID(); secretIds.push(id)
|
|
await pool.query("INSERT INTO mcp_secrets(id,purpose,server_id,ciphertext,created_by) VALUES($1,$2,$3,$4,$5)", [id, purpose, serverId, await encryptSecret(value), owner]); return id
|
|
}
|
|
const wait = async (id: string) => {
|
|
for (let index = 0; index < 3000; index++) { const state = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [id])).rows[0].state; if (!["pending", "running"].includes(state)) return state; await delay(25) }
|
|
throw Error("WireGuard peer creation remains live; never replay")
|
|
}
|
|
let connectionId: string | undefined
|
|
try {
|
|
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES(112,'wg-peer-create','127.0.0.1',$1,false,'NEVER_PEER_ENDPOINT_PASSWORD')", [(router.address() as { port: number }).port])
|
|
await pool.query("INSERT INTO app_users(id,login,name) VALUES('wg-peer-create-user','wg-peer-create-user','Peer fixture')")
|
|
await pool.query("INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key) VALUES('wg-peer-create-binding','wg-peer-create-user',112,'wg-parent','wg',$1)", [initial["/interface/wireguard/peers"][0]["public-key"]])
|
|
await rest.register(wireguardRoutes, { prefix: "/api" })
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "WireGuard peer creation", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [112], operationIds: ["network.wireguard.peers.create", "ros.wireguard_peer.create", "operations.reconcile", "operations.recover"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 100 } }), actor)
|
|
connectionId = access.connection.id
|
|
const principal = await authenticateMcpToken(access.token), privateKeyRef = await secret(WIREGUARD_PEER_KEY_PURPOSE, privateKey)
|
|
const full = { serverId: 112, interfaceName: "wg-parent", publicKey, allowedAddresses: ["192.0.2.2/32", "2001:db8:112::2/128"], endpointAddress: "vpn.example.org", endpointPort: 24321, persistentKeepalive: 25, comment: "owned peer", name: "owned-peer", privateKeyRef, clientAddress: "192.0.2.2,2001:db8:112::2", clientDns: "1.1.1.1", clientEndpoint: "client.example.org" }
|
|
const prepare = async (input: unknown = full) => {
|
|
const plan = await invokeMcpTool(principal, "mm_wireguard_peer_add_plan", input) as { planId: string; state: string; changes: { mutationCost: number } }
|
|
assert.equal(plan.state, "awaiting-approval")
|
|
assert.ok(!JSON.stringify(plan).includes(privateKey)); assert.ok(!JSON.stringify(plan).includes("NEVER_"))
|
|
return plan
|
|
}
|
|
const beforeInvalid = reads
|
|
for (const input of [{ ...full, serverId: 1 }, { ...full, privateKey }, { ...full, privateKeyMode: "none" }, { ...full, allowedAddresses: ["invalid"] }]) await assert.rejects(prepare(input))
|
|
assert.equal(wireguardPeerCreatePlanSchema.safeParse({ ...full, privateKey }).success, false); assert.equal(reads, beforeInvalid)
|
|
for (const ref of [await secret("wrong-purpose", privateKey), await secret(WIREGUARD_PEER_KEY_PURPOSE, privateKey, null), await secret(WIREGUARD_PEER_KEY_PURPOSE, privateKey, 112, "wg-peer-create-user")]) { await assert.rejects(prepare({ ...full, privateKeyRef: ref })); assert.equal(commands.length, 0) }
|
|
for (const change of [() => { rows["/interface/wireguard"][0].comment = "MikrotikManager traffic-flow overlay" }, () => { rows["/interface"][0][".id"] = "*mismatch" }, () => { rows["/interface/wireguard/peers"][0]["public-key"] = publicKey }]) { reset(); change(); await assert.rejects(prepare()); assert.equal(commands.length, 0) }
|
|
reset()
|
|
const protection = randomUUID()
|
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [protection, { kind: "wireguard", id: "*a", serverId: 112, protection: "deny" }, actor.id])
|
|
try { await assert.rejects(prepare()); assert.equal((await rest.inject({ method: "POST", url: "/api/wireguard/peers", payload: { ...full, privateKeyRef: undefined } })).statusCode, 409); assert.equal(commands.length, 0) } finally { await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection]) }
|
|
reset()
|
|
const native = await invokeMcpTool(principal, "mm_wireguard_peer_create_plan", { serverId: 112, fields: { interface: "*a", "public-key": publicKey, "allowed-address": "192.0.2.2/32,2001:db8:112::2/128", "persistent-keepalive": "25s", disabled: false } }) as { planId: string; state: string; changes: { steps: { kind: string; service?: string }[]; mutationCost: number } }
|
|
assert.equal(native.state, "awaiting-approval"); assert.equal(native.changes.mutationCost, 3)
|
|
assert.equal(native.changes.steps[0].kind, "service"); assert.equal(native.changes.steps[0].service, "network.wireguard.peers.create")
|
|
await assert.rejects(applyPlan(principal, native.planId, randomUUID()))
|
|
await approvePlan(native.planId, actor, true)
|
|
assert.equal(await wait((await applyPlan(principal, native.planId, randomUUID())).id), "applied")
|
|
assert.equal(commands.length, 2); assert.equal(rows["/interface/wireguard/peers"][1]["persistent-keepalive"], "25")
|
|
reset()
|
|
const dependencyFailure = await prepare()
|
|
await approvePlan(dependencyFailure.planId, actor, true)
|
|
mode = "dependency-error"
|
|
const diagnosticLines: string[] = []
|
|
const previousError = console.error
|
|
console.error = (...args: unknown[]) => {
|
|
if (typeof args[0] === "string" && args[0].includes('"event":"mcp.wireguard.peer-create-source-failed"')) diagnosticLines.push(args[0])
|
|
else previousError(...args)
|
|
}
|
|
try {
|
|
const operation = await applyPlan(principal, dependencyFailure.planId, randomUUID())
|
|
assert.equal(await wait(operation.id), "rejected")
|
|
const { rows: [terminal] } = await pool.query("SELECT error_code,result FROM mcp_operations WHERE id=$1", [operation.id])
|
|
assert.equal(terminal.error_code, "STATE_UNAVAILABLE")
|
|
assert.doesNotMatch(JSON.stringify(terminal), /NEVER_PROVIDER_SECRET/)
|
|
assert.equal(commands.length, 0)
|
|
assert.equal(diagnosticLines.length, 1)
|
|
assert.deepEqual(JSON.parse(diagnosticLines[0]), {
|
|
event: "mcp.wireguard.peer-create-source-failed", phase: "current",
|
|
read: { catalogue: "/ip/address", attempt: 1, category: "http-refusal", httpStatus: 400 },
|
|
})
|
|
reset()
|
|
diagnosticLines.length = 0
|
|
const readBackFailure = await prepare()
|
|
await approvePlan(readBackFailure.planId, actor, true)
|
|
afterWrite = async () => { mode = "dependency-error" }
|
|
const key = randomUUID()
|
|
const uncertain = await applyPlan(principal, readBackFailure.planId, key)
|
|
assert.equal(await wait(uncertain.id), "unknown")
|
|
const { rows: [unverified] } = await pool.query("SELECT error_code,result FROM mcp_operations WHERE id=$1", [uncertain.id])
|
|
assert.equal(unverified.error_code, "MUTATION_OUTCOME_UNKNOWN")
|
|
assert.doesNotMatch(JSON.stringify(unverified), /NEVER_PROVIDER_SECRET/)
|
|
assert.deepEqual(commands, ["PUT /interface/wireguard/peers"])
|
|
assert.equal(rows["/interface/wireguard/peers"][1].disabled, "true")
|
|
assert.equal((await applyPlan(principal, readBackFailure.planId, key)).id, uncertain.id)
|
|
assert.equal(commands.length, 1)
|
|
assert.deepEqual(diagnosticLines.map(line => JSON.parse(line)), [{
|
|
event: "mcp.wireguard.peer-create-source-failed", phase: "apply-executor",
|
|
read: { catalogue: "/ip/address", attempt: 1, category: "http-refusal", httpStatus: 400, stage: "read-back" },
|
|
}])
|
|
} finally { console.error = previousError }
|
|
for (const fault of ["normal", "ignored", "collateral", "parent-drift", "lost", "staged-collateral"]) {
|
|
reset(); const plan = await prepare(); assert.equal(plan.changes.mutationCost, 3); await approvePlan(plan.planId, actor, true); mode = fault
|
|
const key = randomUUID(), operation = await applyPlan(principal, plan.planId, key)
|
|
assert.equal(await wait(operation.id), fault === "normal" ? "applied" : fault === "lost" ? "unknown" : "partial", JSON.stringify({ fault, ...(await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [operation.id])).rows[0] }))
|
|
assert.equal(commands.length, ["normal", "staged-collateral"].includes(fault) ? 2 : 1)
|
|
assert.equal((await applyPlan(principal, plan.planId, key)).id, operation.id)
|
|
const count: number = commands.length
|
|
type Reconciled = { automaticRetry: boolean; results: { matchesDesiredState: boolean; matchesOriginalState: boolean; verifiedFinalCheckpointAvailable: boolean }[] }
|
|
const reconcile = () => invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as Promise<Reconciled>
|
|
const reconciled = await reconcile()
|
|
assert.equal(reconciled.automaticRetry, false); assert.equal(reconciled.results[0].matchesDesiredState, fault === "normal"); assert.equal(reconciled.results[0].matchesOriginalState, fault === "ignored"); assert.equal(commands.length, count)
|
|
if (fault === "normal") {
|
|
assert.equal(rows["/interface/wireguard/peers"][1].disabled, "false"); assert.equal(rows["/interface/wireguard/peers"][1]["private-key"], privateKey)
|
|
const step = (await pool.query("SELECT intended_state,result FROM mcp_operation_steps WHERE operation_id=$1", [operation.id])).rows[0]
|
|
const variants = [
|
|
{ state: "sent", intended: step.intended_state, result: step.result },
|
|
{ state: "verified", intended: { ...step.intended_state, kind: "ros" }, result: step.result },
|
|
{ state: "verified", intended: { ...step.intended_state, service: "network.wireguard.interfaces.create" }, result: step.result },
|
|
...["credentialId", "connectionId"].map(field => ({ state: "verified", intended: { ...step.intended_state, input: { ...step.intended_state.input, principal: { ...step.intended_state.input.principal, [field]: randomUUID() } } }, result: step.result })),
|
|
...["ownerId", "expectedProof", "expectedReferenceProof", "requestProof", "receiptId", "proofRevision"].map(field => ({ state: "verified", intended: { ...step.intended_state, input: { ...step.intended_state.input, [field]: field === "proofRevision" ? 2 : randomUUID() } }, result: step.result })),
|
|
{ state: "verified", intended: { ...step.intended_state, input: { ...step.intended_state.input, request: { ...step.intended_state.input.request, name: "other" } } }, result: step.result },
|
|
{ state: "verified", intended: step.intended_state, result: null },
|
|
{ state: "verified", intended: step.intended_state, result: { ...step.result, peerId: "*foreign" } },
|
|
]
|
|
for (const variant of variants) {
|
|
await pool.query("UPDATE mcp_operation_steps SET state=$2,intended_state=$3::jsonb,result=$4::jsonb WHERE operation_id=$1", [operation.id, variant.state, JSON.stringify(variant.intended), JSON.stringify(variant.result)])
|
|
assert.equal((await reconcile()).results[0].matchesDesiredState, false)
|
|
}
|
|
await pool.query("UPDATE mcp_operation_steps SET state='verified',intended_state=$2::jsonb,result=$3::jsonb WHERE operation_id=$1", [operation.id, JSON.stringify(step.intended_state), JSON.stringify(step.result)])
|
|
assert.equal((await reconcile()).results[0].matchesDesiredState, true); assert.equal(commands.length, count)
|
|
}
|
|
await assert.rejects(invokeMcpTool(principal, "mm_operation_recovery_plan", { operationId: operation.id }), (error: { code?: string }) => error.code === "UNSUPPORTED_CAPABILITY")
|
|
}
|
|
reset(); const stale = await prepare(); await approvePlan(stale.planId, actor, true); rows["/interface/wireguard"][0].opaque = "NEVER_LATE_PARENT_DRIFT"
|
|
assert.equal(await wait((await applyPlan(principal, stale.planId, randomUUID())).id), "rejected"); assert.equal(commands.length, 0)
|
|
reset(); const rotated = await prepare(); await approvePlan(rotated.planId, actor, true); await pool.query("UPDATE mcp_secrets SET ciphertext=$2 WHERE id=$1", [privateKeyRef, await encryptSecret(generatedKey)])
|
|
assert.equal(await wait((await applyPlan(principal, rotated.planId, randomUUID())).id), "rejected"); assert.equal(commands.length, 0)
|
|
await pool.query("UPDATE mcp_secrets SET ciphertext=$2 WHERE id=$1", [privateKeyRef, await encryptSecret(privateKey)])
|
|
reset(); const paused = await prepare(); await approvePlan(paused.planId, actor, true); afterWrite = () => setConnectionStatus(connectionId!, "paused", actor)
|
|
assert.equal(await wait((await applyPlan(principal, paused.planId, randomUUID())).id), "unknown"); assert.equal(commands.length, 1)
|
|
await setConnectionStatus(connectionId, "active", actor)
|
|
for (const privateKeyMode of ["auto", "none", undefined]) {
|
|
reset(); const plan = await prepare({ ...full, privateKeyRef: undefined, privateKeyMode, disabled: true }); await approvePlan(plan.planId, actor, true)
|
|
const operation = await applyPlan(principal, plan.planId, randomUUID())
|
|
assert.equal(await wait(operation.id), "applied", JSON.stringify((await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [operation.id])).rows[0])); assert.equal(commands.length, 1)
|
|
}
|
|
reset(); mode = "provider-error"; await assert.rejects(prepare(), (error: Error) => !error.message.includes("NEVER_"))
|
|
assert.ok(!(await rest.inject({ method: "POST", url: "/api/wireguard/peers", payload: { ...full, privateKeyRef: undefined, privateKey } })).body.includes("NEVER_"))
|
|
reset()
|
|
const response = await rest.inject({ method: "POST", url: "/api/wireguard/peers", payload: { ...full, privateKeyRef: undefined, privateKey } })
|
|
assert.equal(response.statusCode, 201, response.body); assert.deepEqual(response.json(), { ok: true }); assert.equal(commands.length, 2)
|
|
assert.equal(rows["/interface/wireguard/peers"][1]["client-address"], full.clientAddress)
|
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_requests WHERE connection_id=$1 AND (result::text LIKE '%NEVER_%' OR result::text LIKE $2)", [connectionId, "%" + privateKey + "%"])).rows[0].n, 0)
|
|
assert.ok((await pool.query("SELECT count(*)::int AS n FROM mcp_audit WHERE action='configuration.intent' AND payload->>'serverId'='112'")).rows[0].n >= commands.length)
|
|
console.log("✓ WireGuard peer create REST/MCP: all fields, IPv4/IPv6, key reference/modes, supported existing parent users/address/OSPF/VRF/firewall, exact checkpoints, per-stage proofs, lost/partial/revoke/drift/idempotency/privacy")
|
|
} finally {
|
|
await rest.close(); await new Promise<void>(resolve => router.close(() => resolve()))
|
|
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
|
|
await pool.query("DELETE FROM mcp_secrets WHERE id=ANY($1::uuid[])", [secretIds])
|
|
await pool.query("DELETE FROM user_interface_bindings WHERE id='wg-peer-create-binding'")
|
|
await pool.query("DELETE FROM app_users WHERE id='wg-peer-create-user'")
|
|
await pool.query("DELETE FROM servers WHERE id=112")
|
|
}
|
|
}
|