Files
MikrotikManager/backend/src/modules/mcp/wireguard-peer-update-acceptance.ts
T

217 lines
17 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 { wireguardPeerUpdateSchema, wireguardPeerNativeUpdate } from "../../services/wireguard-peer-update.js"
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
export async function acceptWireguardPeerUpdate(actor: AuthUser) {
const publicKey = Buffer.alloc(32, 11).toString("base64"), otherKey = Buffer.alloc(32, 12).toString("base64"), newKey = Buffer.alloc(32, 13).toString("base64")
const privateKey = Buffer.alloc(32, 14).toString("base64"), psk = Buffer.alloc(32, 15).toString("base64")
const baseInterfaces = [{ ".id": "*a1", name: "wg-update", disabled: "false", "private-key": privateKey, "listen-port": "13231", mtu: "1420", comment: "" }]
const basePeers: Record<string, string>[] = [{ ".id": "*b1", interface: "wg-update", "public-key": publicKey, "preshared-key": psk, "allowed-address": "192.0.2.2/32", disabled: "false", comment: "before", opaque: "NEVER_UPDATE_OPAQUE" }, { ".id": "*b2", interface: "wg-update", "public-key": otherKey, "allowed-address": "192.0.2.3/32", disabled: "false", comment: "other", rx: "0" }]
let interfaces = structuredClone(baseInterfaces), peers = structuredClone(basePeers), mode = "normal", patches = 0, reads = 0
let duringRead: (() => Promise<unknown>) | undefined
let duringAuxRead: (() => Promise<unknown>) | undefined, auxReads = 0
const router = createServer((req, res) => {
res.setHeader("content-type", "application/json")
if (req.method === "POST" && req.url?.startsWith("/rest/interface/wireguard/peers/")) {
let body = ""
req.on("data", chunk => { body += chunk }); req.on("end", async () => {
auxReads++
if (duringAuxRead) {
const hook = duringAuxRead; duringAuxRead = undefined
try { await hook() } catch { res.statusCode = 503; res.end("{}"); return }
}
const data = JSON.parse(body)
if (req.url?.endsWith("/get")) {
if (mode === "unset-get-unknown") { res.end('{"ret":"NEVER_UNKNOWN_KEEPALIVE"}'); return }
const value = peers.find(row => row[".id"] === data[".id"])?.[data["value-name"]]
res.end(JSON.stringify(value === undefined ? [] : { ret: value })); return
}
if (req.url?.endsWith("/print")) {
const negative = data[".query"]?.includes("#!")
if (mode === "unset-partial") { res.end("[]"); return }
if (mode === "unset-overlap") { res.end(JSON.stringify(peers.map(row => ({ ".id": row[".id"] })))); return }
if (mode === "unset-foreign") { res.end('[{".id":"*fff"}]'); return }
res.end(JSON.stringify(peers.filter(row => (row["persistent-keepalive"] !== undefined) !== negative).map(row => ({ ".id": row[".id"] })))); return
}
res.statusCode = 400; res.end("{}")
}); return
}
if (req.method === "GET") {
reads++
const respond = () => res.end(JSON.stringify(req.url === "/rest/interface/wireguard" ? interfaces : req.url === "/rest/interface/wireguard/peers" ? peers : []))
if (duringRead) { const hook = duringRead; duringRead = undefined; void hook().then(respond, () => { res.statusCode = 503; res.end("{}") }); return }
if (mode === "provider-error") { res.statusCode = 400; res.end('{"message":"NEVER_UPDATE_PROVIDER_PASSWORD"}'); return }
respond(); return
}
if (req.method === "PATCH" && req.url === "/rest/interface/wireguard/peers/*b1") {
let body = ""
req.on("data", chunk => { body += chunk }); req.on("end", () => {
patches++
const data = JSON.parse(body) as Record<string, string>
if (mode !== "ignored") {
Object.assign(peers[0], data)
if (data.disabled !== undefined) peers[0].disabled = data.disabled === "true" ? "yes" : "no"
if (data["persistent-keepalive"] === "60") peers[0]["persistent-keepalive"] = "1m"
if (data["persistent-keepalive"] === "0") delete peers[0]["persistent-keepalive"]
for (const key of ["comment", "name", "endpoint-address", "client-address", "client-dns", "client-endpoint"]) if (data[key] === "") delete peers[0][key]
}
if (mode === "collateral") peers[1].comment = "foreign changed"
if (mode === "lost") { req.socket.destroy(); return }
res.end("{}")
}); return
}
res.statusCode = 400; res.end("{}")
})
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
const rest = Fastify(); rest.setValidatorCompiler(validatorCompiler); rest.setSerializerCompiler(serializerCompiler)
let connectionId: string | undefined
const reset = () => { mode = "normal"; interfaces = structuredClone(baseInterfaces); peers = structuredClone(basePeers) }
const wait = async (id: string) => {
for (let attempt = 0; attempt < 250; attempt++) {
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")
}
try {
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES(108,'wg-peer-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 peer update", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [108], operationIds: ["network.wireguard.peers.update", "ros.wireguard_peer.update", "operations.reconcile", "operations.recover"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 100 } }), actor)
connectionId = access.connection.id
const principal = await authenticateMcpToken(access.token)
const prepare = async (patch: Record<string, unknown> = { comment: "after" }, native = false) => {
const plan = await invokeMcpTool(principal, native ? "mm_wireguard_peer_update_plan" : "mm_wireguard_peer_edit_plan", native ? { serverId: 108, id: "*b1", fields: patch } : { serverId: 108, peerId: "*b1", patch }) as { planId: string; state: string }
assert.equal(plan.state, "awaiting-approval")
for (const value of [privateKey, psk, "NEVER_"]) assert.ok(!JSON.stringify(plan).includes(value))
return plan
}
const beforeInvalid = reads
for (const patch of [{}, { privateKey }, { endpointPort: 65536 }, { allowedAddresses: ["bad"] }, { allowedAddresses: ["192.0.2.1/24", "192.0.2.0/24"] }, { publicKey: "bad" }]) {
assert.equal(wireguardPeerUpdateSchema.safeParse(patch).success, false)
await assert.rejects(prepare(patch))
assert.equal((await rest.inject({ method: "PATCH", url: "/api/wireguard/peers/108/*b1", payload: patch })).statusCode, 400)
}
await assert.rejects(invokeMcpTool(principal, "mm_wireguard_peer_edit_plan", { serverId: 1, peerId: "*b1", patch: { comment: "after" } }))
await assert.rejects(prepare({ interface: "another" }, true))
assert.equal(reads, beforeInvalid)
for (const fault of ["unset-get-unknown", "unset-partial", "unset-overlap", "unset-foreign"]) {
mode = fault
const before = patches
await assert.rejects(prepare(), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE")
assert.equal(patches, before)
}
reset()
assert.equal(wireguardPeerNativeUpdate({ "persistent-keepalive": "1m", "endpoint-port": "123", disabled: "false" }).persistentKeepalive, 60)
assert.throws(() => wireguardPeerNativeUpdate({ "persistent-keepalive": "unknown" }))
const legacy = await prepare({ comment: "after" }, true); await approvePlan(legacy.planId, actor, true)
await pool.query("UPDATE mcp_plans SET operation_version=1 WHERE id=$1", [legacy.planId])
await assert.rejects(applyPlan(principal, legacy.planId, randomUUID()), (error: { code?: string }) => error.code === "PLAN_EXPIRED")
assert.equal(patches, 0)
await assert.rejects(prepare({ publicKey: otherKey }))
const bindingId = randomUUID()
await pool.query("INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,peer_public_key) VALUES($1,'wg-update-user',108,'wg-update',$2)", [bindingId, publicKey])
const boundPlan = await prepare({ comment: "allowed for bound peer" }); await approvePlan(boundPlan.planId, actor, true)
assert.equal(await wait((await applyPlan(principal, boundPlan.planId, randomUUID())).id), "applied")
await assert.rejects(prepare({ publicKey: newKey }), /привязкой/)
assert.equal((await rest.inject({ method: "PATCH", url: "/api/wireguard/peers/108/*b1", payload: { publicKey: newKey } })).statusCode, 409)
await pool.query("DELETE FROM user_interface_bindings WHERE id=$1", [bindingId])
reset()
const beforeProtection = patches
const protectionId = randomUUID()
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'integration')", [protectionId, JSON.stringify({ kind: "wireguard", id: "*a1", serverId: 108, protection: "deny" })])
await assert.rejects(prepare()); await assert.rejects(prepare({ comment: "after" }, true))
assert.equal((await rest.inject({ method: "PATCH", url: "/api/wireguard/peers/108/*b1", payload: { comment: "after" } })).statusCode, 409)
assert.equal(patches, beforeProtection)
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId])
peers[0].comment = "MM traffic-flow collector"
await assert.rejects(prepare(), /NetFlow/); await assert.rejects(prepare({ comment: "after" }, true), /NetFlow/)
reset()
const lateBindingPlan = await prepare(); await approvePlan(lateBindingPlan.planId, actor, true)
await pool.query("INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,peer_public_key) VALUES($1,'wg-update-user',108,'wg-update',$2)", [bindingId, publicKey])
const beforeLateBinding = patches
assert.equal(await wait((await applyPlan(principal, lateBindingPlan.planId, randomUUID())).id), "rejected")
assert.equal(patches, beforeLateBinding)
await pool.query("DELETE FROM user_interface_bindings WHERE id=$1", [bindingId])
const counters = await prepare(); await approvePlan(counters.planId, actor, true)
peers[1].rx = "9000"
assert.equal(await wait((await applyPlan(principal, counters.planId, randomUUID())).id), "applied")
reset()
for (const fault of ["normal", "ignored", "collateral", "lost"]) {
reset()
const plan = await prepare({ comment: "after" }, fault === "normal"); await approvePlan(plan.planId, actor, true)
mode = fault
const before: number = patches, key = randomUUID(), operation = await applyPlan(principal, plan.planId, key)
const expected = fault === "normal" ? "applied" : fault === "lost" ? "unknown" : "partial"
assert.equal(await wait(operation.id), expected); assert.equal(patches, before + 1)
assert.equal((await applyPlan(principal, plan.planId, key)).id, operation.id); assert.equal(patches, before + 1)
const reconciliation = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { state: string; automaticRetry: boolean; results: { matchesDesiredState: boolean; matchesOriginalState: boolean }[] }
assert.equal(reconciliation.state, expected); assert.equal(reconciliation.automaticRetry, false)
assert.equal(reconciliation.results[0].matchesDesiredState, fault === "normal" || fault === "lost")
assert.equal(reconciliation.results[0].matchesOriginalState, fault === "ignored")
assert.equal(patches, before + 1)
await assert.rejects(invokeMcpTool(principal, "mm_operation_recovery_plan", { operationId: operation.id }), (error: { code?: string }) => error.code === "UNSUPPORTED_CAPABILITY")
}
reset()
const drift = await prepare(); await approvePlan(drift.planId, actor, true)
peers[1]["preshared-key"] = "NEVER_LATE_PSK"
const beforeDrift = patches
assert.equal(await wait((await applyPlan(principal, drift.planId, randomUUID())).id), "rejected"); assert.equal(patches, beforeDrift)
reset()
const aba = await prepare(); await approvePlan(aba.planId, actor, true)
await pool.query("UPDATE servers SET verify_ssl=NOT verify_ssl WHERE id=108"); await pool.query("UPDATE servers SET verify_ssl=NOT verify_ssl WHERE id=108")
assert.equal(await wait((await applyPlan(principal, aba.planId, randomUUID())).id), "rejected"); assert.equal(patches, beforeDrift)
const pausedRead = reads
duringRead = () => setConnectionStatus(access.connection.id, "paused", actor)
await assert.rejects(prepare()); assert.equal(reads, pausedRead + 1)
await setConnectionStatus(access.connection.id, "active", actor)
reset()
const beforeAuxPause = auxReads, beforeAuxPauseGets = reads
duringAuxRead = () => setConnectionStatus(access.connection.id, "paused", actor)
await assert.rejects(prepare()); assert.equal(auxReads, beforeAuxPause + 1); assert.equal(reads, beforeAuxPauseGets + 2)
await setConnectionStatus(access.connection.id, "active", actor)
const auxCancelled = new AbortController(), beforeAuxCancel = auxReads
duringAuxRead = async () => auxCancelled.abort()
await assert.rejects(invokeMcpTool(principal, "mm_wireguard_peer_edit_plan", { serverId: 108, peerId: "*b1", patch: { comment: "after" } }, auxCancelled.signal), (error: { code?: string }) => error.code === "READ_CANCELLED")
assert.equal(auxReads, beforeAuxCancel + 1)
const cancelled = new AbortController(), cancelledRead = reads
duringRead = async () => cancelled.abort()
await assert.rejects(invokeMcpTool(principal, "mm_wireguard_peer_edit_plan", { serverId: 108, peerId: "*b1", patch: { comment: "after" } }, cancelled.signal), (error: { code?: string }) => error.code === "READ_CANCELLED")
assert.equal(reads, cancelledRead + 1)
reset(); mode = "provider-error"
await assert.rejects(prepare(), (error: Error) => !error.message.includes("NEVER_"))
const provider = await rest.inject({ method: "PATCH", url: "/api/wireguard/peers/108/*b1", payload: { comment: "after" } })
assert.equal(provider.statusCode, 502); assert.ok(!provider.body.includes("NEVER_"))
reset()
const fullPatch = { publicKey: newKey, allowedAddresses: ["2001:db8::abcd/64", "192.0.2.89/24"], endpointAddress: "vpn.example.invalid", endpointPort: 13232, persistentKeepalive: 60, comment: "", name: "updated-peer", disabled: true, clientAddress: "198.51.100.2/32", clientDns: "192.0.2.53", clientEndpoint: "client.example.invalid" }
const beforeRest = patches, restResult = await rest.inject({ method: "PATCH", url: "/api/wireguard/peers/108/*b1", payload: fullPatch })
assert.equal(restResult.statusCode, 200, restResult.body); assert.equal(restResult.json().verified, true); assert.equal(restResult.json().revisionRecorded, true)
assert.equal(restResult.json().afterProof, undefined); assert.equal(patches, beforeRest + 1)
assert.equal(peers[0]["public-key"], newKey); assert.equal(peers[0]["persistent-keepalive"], "1m"); assert.equal(peers[0].disabled, "yes")
assert.equal(peers[0]["allowed-address"], "192.0.2.0/24,2001:db8::/64"); assert.equal(peers[0].comment, undefined)
assert.equal(peers[0]["preshared-key"], psk); assert.deepEqual(peers[1], basePeers[1]); assert.deepEqual(interfaces, baseInterfaces)
const clear = await prepare({ persistentKeepalive: 0, endpointAddress: "", endpointPort: 0 }); await approvePlan(clear.planId, actor, true)
assert.equal(await wait((await applyPlan(principal, clear.planId, randomUUID())).id), "applied")
assert.equal(peers[0]["persistent-keepalive"], undefined)
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, "%" + psk + "%", "%" + privateKey + "%"])).rows[0].n, 0)
console.log("✓ WireGuard peer PATCH shares REST/MCP/native service: strict fields, bound identity/NetFlow/protections, private source proof, aliases/version fence, canonical read-back, preserved opaque/foreign peers, partial/lost/idempotency and read-only reconciliation; one PATCH and no forwarding claim")
} finally {
await rest.close(); await new Promise<void>(resolve => router.close(() => resolve()))
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
await pool.query("DELETE FROM user_interface_bindings WHERE user_id='wg-update-user'")
await pool.query("DELETE FROM app_users WHERE id='wg-update-user'")
await pool.query("DELETE FROM servers WHERE id=108")
}
}