124 lines
15 KiB
TypeScript
124 lines
15 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_INTERFACE_KEY_PURPOSE } from "./wireguard-interface-update-actions.js"
|
|
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
|
|
|
|
/** Dedicated SQL/loopback fixture; caller owns serial PostgreSQL acceptance. */
|
|
export async function acceptWireguardInterfaceUpdate(actor: AuthUser) {
|
|
const privateKey = Buffer.alloc(32, 71).toString("base64"), replacement = Buffer.alloc(32, 72).toString("base64")
|
|
type Rows = Record<string, Record<string, string>[]>
|
|
const initial: Rows = Object.fromEntries(wireguardInterfaceDependencyPaths.map(path => [path, []]))
|
|
initial["/interface/wireguard"] = [{ ".id": "*a", name: "wg-update", disabled: "false", mtu: "1420", "listen-port": "13231", "public-key": wireguardPublicKey(privateKey), "private-key": privateKey, opaque: "NEVER_NATIVE_OPAQUE" }]
|
|
initial["/interface/wireguard/peers"] = [{ ".id": "*b", interface: "wg-update", disabled: "false", "public-key": wireguardPublicKey(replacement), "allowed-address": "192.0.2.2/32", rx: "0" }]
|
|
initial["/interface"] = [{ ".id": "*a", name: "wg-update", type: "wg" }]
|
|
initial["/interface/wireguard"].push({ ".id": "*f", name: "wg-foreign", disabled: "true", mtu: "1420", opaque: "NEVER_FOREIGN_CONFIGURATION" })
|
|
initial["/interface"].push({ ".id": "*f", name: "wg-foreign", type: "wg", opaque: "NEVER_FOREIGN_GENERIC" })
|
|
initial["/ip/address"] = [{ ".id": "*c", interface: "wg-update", address: "192.0.2.1/24", disabled: "false", dynamic: "false" }, { ".id": "*d", interface: "wg-update", address: "198.51.100.1/24", disabled: "false", dynamic: "false", comment: "secondary" }]
|
|
initial["/ipv6/address"] = []
|
|
let rows = structuredClone(initial), commands: string[] = [], mode = "normal", reads = 0, afterWrite: (() => Promise<unknown>) | undefined
|
|
const reset = () => { rows = structuredClone(initial); commands = []; mode = "normal"; afterWrite = undefined }
|
|
const router = createServer((req, res) => {
|
|
res.setHeader("content-type", "application/json")
|
|
const path = decodeURIComponent((req.url ?? "").slice(5))
|
|
if (req.method === "GET") {
|
|
reads++
|
|
if (mode === "provider-error") { res.statusCode = 500; res.end('{"message":"NEVER_PROVIDER_SECRET"}'); return }
|
|
if (!Object.hasOwn(rows, path)) { res.statusCode = 404; res.end("{}"); return }
|
|
rows["/interface/wireguard/peers"][0].rx = String(reads)
|
|
res.end(JSON.stringify(rows[path])); return
|
|
}
|
|
const base = ["/interface/wireguard", "/ip/address", "/ipv6/address"].find(base => path === base || path.startsWith(base + "/"))
|
|
if (!base || !["PUT", "PATCH", "DELETE"].includes(req.method ?? "")) { res.statusCode = 400; res.end("{}"); return }
|
|
let raw = ""
|
|
req.on("data", chunk => { raw += chunk }); req.on("end", async () => {
|
|
const body = raw ? JSON.parse(raw) as Record<string, string> : {}, id = path.slice(base.length + 1)
|
|
commands.push(req.method + " " + path)
|
|
if (mode !== "ignored") {
|
|
if (req.method === "DELETE") rows[base] = rows[base].filter(row => row[".id"] !== id)
|
|
else if (req.method === "PUT") rows[base].push({ ".id": "*e", dynamic: "false", ...body })
|
|
else {
|
|
const selected = rows[base].find(row => row[".id"] === id)!, oldName = selected.name
|
|
Object.assign(selected, body)
|
|
if (body["private-key"]) selected["public-key"] = wireguardPublicKey(body["private-key"])
|
|
if (body.name && base === "/interface/wireguard") { rows["/interface"][0].name = body.name; for (const row of [...rows["/interface/wireguard/peers"], ...rows["/ip/address"], ...rows["/ipv6/address"]]) if (row.interface === oldName) row.interface = body.name }
|
|
}
|
|
}
|
|
if (mode === "collateral") rows["/interface/wireguard"][0].opaque = "NEVER_COLLATERAL"
|
|
if (mode === "generic-collateral") rows["/interface"][1].opaque = "NEVER_GENERIC_COLLATERAL"
|
|
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 = 136, 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 update remains live; never replay") }
|
|
let connectionId: string | undefined
|
|
try {
|
|
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES(136,'wg-interface-update','127.0.0.1',$1,false,'NEVER_UPDATE_ENDPOINT_PASSWORD')", [(router.address() as { port: number }).port])
|
|
await pool.query("INSERT INTO app_users(id,login,name) VALUES('wg-update-user','wg-update-user','Update fixture')")
|
|
await rest.register(wireguardRoutes, { prefix: "/api" })
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "WireGuard update", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [136], operationIds: ["network.wireguard.interfaces.update", "ros.wireguard.update", "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_INTERFACE_KEY_PURPOSE, replacement)
|
|
const full = { serverId: 136, interfaceId: "*a", patch: { name: "wg-renamed", listenPort: 23456, mtu: 1380, comment: "updated", disabled: true, privateKeyRef } }
|
|
const prepare = async (input: unknown = full) => { const plan = await invokeMcpTool(principal, "mm_wireguard_interface_edit_plan", input) as { planId: string; state: string; changes: { mutationCost: number } }; assert.equal(plan.state, "awaiting-approval"); for (const value of [privateKey, replacement, "NEVER_"]) assert.ok(!JSON.stringify(plan).includes(value)); return plan }
|
|
const beforeReads = reads
|
|
for (const input of [{ ...full, serverId: 1 }, { ...full, patch: { privateKey: replacement } }, { ...full, patch: { name: "\u0000bad" } }, { ...full, patch: {} }]) await assert.rejects(prepare(input))
|
|
assert.equal(reads, beforeReads)
|
|
for (const ref of [await secret("wrong-purpose", replacement), await secret(WIREGUARD_INTERFACE_KEY_PURPOSE, replacement, null), await secret(WIREGUARD_INTERFACE_KEY_PURPOSE, replacement, 136, "wg-update-user")]) { await assert.rejects(prepare({ ...full, patch: { privateKeyRef: ref } })); assert.equal(commands.length, 0) }
|
|
for (const [path, row] of [["/interface/vlan", { interface: "wg-update" }], ["/routing/filter/rule", { rule: 'set gw "wg-update";' }], ["/routing/ospf/interface-template", { networks: "192.0.2.0/24" }]] as [string, Record<string, string>][]) { reset(); rows[path].push({ ".id": "*f", ...row }); 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_peer", id: "*b", serverId: 136, protection: "deny" }, actor.id])
|
|
try { await assert.rejects(prepare()); assert.equal((await rest.inject({ method: "PATCH", url: "/api/wireguard/interfaces/136/*a", payload: { disabled: true } })).statusCode, 409); assert.equal(commands.length, 0) } finally { await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection]) }
|
|
for (const fault of ["normal", "ignored", "collateral", "generic-collateral", "lost"]) {
|
|
reset(); const plan = await prepare(); 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", fault)
|
|
assert.equal(commands.length, 1); assert.equal((await applyPlan(principal, plan.planId, key)).id, operation.id)
|
|
const reconciled = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { automaticRetry: boolean; results: { matchesDesiredState: boolean; matchesOriginalState: boolean }[] }
|
|
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, 1)
|
|
if (fault === "normal") {
|
|
const saved = (await pool.query("SELECT state,intended_state FROM mcp_operation_steps WHERE operation_id=$1 AND step_index=0", [operation.id])).rows[0]
|
|
for (const changed of [{ state: "applied", intended: saved.intended_state }, { state: "verified", intended: { ...saved.intended_state, service: "network.wireguard.interfaces.create" } }, { state: "verified", intended: { ...saved.intended_state, input: { ...saved.intended_state.input, receiptId: randomUUID() } } }, { state: "verified", intended: { ...saved.intended_state, input: { ...saved.intended_state.input, ownerId: "foreign-owner" } } }]) {
|
|
await pool.query("UPDATE mcp_operation_steps SET state=$2,intended_state=$3::jsonb WHERE operation_id=$1 AND step_index=0", [operation.id, changed.state, JSON.stringify(changed.intended)])
|
|
const untrusted = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { results: { matchesDesiredState: boolean }[] }; assert.equal(untrusted.results[0].matchesDesiredState, false); assert.equal(commands.length, 1)
|
|
}
|
|
await pool.query("UPDATE mcp_operation_steps SET state=$2,intended_state=$3::jsonb WHERE operation_id=$1 AND step_index=0", [operation.id, saved.state, JSON.stringify(saved.intended_state)])
|
|
}
|
|
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_DRIFT"; assert.equal(await wait((await applyPlan(principal, stale.planId, randomUUID())).id), "rejected"); assert.equal(commands.length, 0)
|
|
reset(); const metadata = await prepare(); await approvePlan(metadata.planId, actor, true); await pool.query("UPDATE servers SET name='updated metadata',comment='display-only',updated_at=now() WHERE id=136"); assert.equal(await wait((await applyPlan(principal, metadata.planId, randomUUID())).id), "applied"); assert.equal(commands.length, 1)
|
|
reset(); const epoch = await prepare(); await approvePlan(epoch.planId, actor, true); await pool.query("UPDATE servers SET port=port+1 WHERE id=136"); await pool.query("UPDATE servers SET port=port-1 WHERE id=136"); assert.equal(await wait((await applyPlan(principal, epoch.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(privateKey)]); 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(replacement)])
|
|
reset(); const paused = await prepare({ serverId: 136, interfaceId: "*a", patch: { address: "2001:db8::1/64" } }); 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 address of ["", "2001:db8::1/64", "192.0.2.3/24", "198.51.100.1/24"]) {
|
|
reset(); const plan = await prepare({ serverId: 136, interfaceId: "*a", patch: { address } }); await approvePlan(plan.planId, actor, true); assert.equal(await wait((await applyPlan(principal, plan.planId, randomUUID())).id), "applied"); assert.equal(rows["/ip/address"].find(row => row[".id"] === "*d")?.comment, "secondary")
|
|
}
|
|
reset(); const native = await invokeMcpTool(principal, "mm_wireguard_update_plan", { serverId: 136, id: "*a", fields: { "listen-port": 23456, mtu: 1380, disabled: true, comment: "native" } }) as { planId: string }; await approvePlan(native.planId, actor, true); assert.equal(await wait((await applyPlan(principal, native.planId, randomUUID())).id), "applied"); 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: "PATCH", url: "/api/wireguard/interfaces/136/*a", payload: { comment: "changed" } })).body.includes("NEVER_"))
|
|
reset(); const response = await rest.inject({ method: "PATCH", url: "/api/wireguard/interfaces/136/*a", payload: { name: "rest-renamed", privateKey: replacement, disabled: true, listenPort: 34567, mtu: 1380, comment: "rest" } }); assert.equal(response.statusCode, 200, response.body); assert.equal(commands.length, 1); assert.equal(rows["/interface/wireguard"][0]["public-key"], wireguardPublicKey(replacement))
|
|
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 OR result::text LIKE $3)", [connectionId, "%" + privateKey + "%", "%" + replacement + "%"])).rows[0].n, 0)
|
|
console.log("✓ WireGuard interface update shared REST/MCP: full fields/key refs, rename children, primary/secondary address semantics, native alias, permissions/protections/source epoch, readback/lost/partial/revoke/no replay, exact verified checkpoint, private diagnostics")
|
|
} 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 app_users WHERE id='wg-update-user'"); await pool.query("DELETE FROM servers WHERE id=136")
|
|
}
|
|
}
|