192 lines
15 KiB
TypeScript
192 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 { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
|
|
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
|
|
|
|
export async function acceptWireguardPeerDeletion(actor: AuthUser) {
|
|
const privateKey = Buffer.alloc(32, 7).toString("base64"), psk = Buffer.alloc(32, 8).toString("base64")
|
|
const publicKey = Buffer.alloc(32, 1).toString("base64"), otherKey = Buffer.alloc(32, 2).toString("base64")
|
|
const baseInterfaces = [{ ".id": "*a1", name: "wg-proof", comment: "", "private-key": privateKey, "listen-port": "13231", mtu: "1420", disabled: "false", opaque: "NEVER_WG_OPAQUE" }]
|
|
const basePeers: Record<string, string>[] = [{ ".id": "*b1", interface: "wg-proof", "public-key": publicKey, "preshared-key": psk, "allowed-address": "10.1.0.2/32", disabled: "false", comment: "selected" }, { ".id": "*b2", interface: "wg-proof", "public-key": otherKey, "allowed-address": "10.1.0.3/32", disabled: "false", comment: "preserve", rx: "0" }]
|
|
let interfaces = structuredClone(baseInterfaces), peers = structuredClone(basePeers), mode = "normal", deletes = 0, reads = 0
|
|
let duringRead: (() => Promise<unknown>) | undefined
|
|
const router = createServer((req, res) => {
|
|
res.setHeader("content-type", "application/json")
|
|
if (req.method === "GET") {
|
|
reads++
|
|
if (duringRead) {
|
|
const hook = duringRead; duringRead = undefined
|
|
void hook().then(() => res.end(JSON.stringify(req.url === "/rest/interface/wireguard" ? interfaces : peers)), () => { res.statusCode = 503; res.end("{}") })
|
|
return
|
|
}
|
|
if (mode === "provider-error") { res.statusCode = 400; res.end('{"message":"NEVER_WG_PROVIDER_PASSWORD"}'); return }
|
|
res.end(JSON.stringify(req.url === "/rest/interface/wireguard" ? interfaces : req.url === "/rest/interface/wireguard/peers" ? peers : [])); return
|
|
}
|
|
if (req.method === "DELETE" && req.url?.startsWith("/rest/interface/wireguard/peers/")) {
|
|
deletes++
|
|
const id = decodeURIComponent(req.url.split("/").at(-1)!)
|
|
if (mode !== "ignored") peers = peers.filter(row => row[".id"] !== id)
|
|
if (mode === "collateral") peers[0].comment = "unexpected-change"
|
|
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 originalFlow = (await pool.query("SELECT host_public_key,peers_json FROM traffic_flow_settings WHERE id=1")).rows[0]
|
|
const reset = () => { mode = "normal"; interfaces = structuredClone(baseInterfaces); peers = structuredClone(basePeers) }
|
|
const wait = async (id: string) => {
|
|
for (let n = 0; n < 250; n++) {
|
|
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 operation remains live; never replay")
|
|
}
|
|
try {
|
|
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES(105,'wg-peer-proof','127.0.0.1',$1,false,'NEVER_WG_ENDPOINT_PASSWORD')", [(router.address() as { port: number }).port])
|
|
await pool.query("INSERT INTO app_users(id,login,name) VALUES('wg-peer-proof-user','wg-peer-proof-user','WG peer binding fixture')")
|
|
await rest.register(wireguardRoutes, { prefix: "/api" })
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "WireGuard peer deletion", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write", "mm:network:read"], scope: { serverIds: [105], operationIds: ["network.wireguard.peers.delete", "ros.wireguard_peer.delete", "operations.reconcile"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 100 } }), actor)
|
|
connectionId = access.connection.id
|
|
const principal = await authenticateMcpToken(access.token)
|
|
const prepare = async (native = false) => {
|
|
const plan = await invokeMcpTool(principal, native ? "mm_wireguard_peer_delete_plan" : "mm_wireguard_peer_remove_plan", native ? { serverId: 105, id: "*b1" } : { serverId: 105, peerId: "*b1" }) as { planId: string; state: string }
|
|
assert.equal(plan.state, "awaiting-approval")
|
|
const preview = JSON.stringify(plan)
|
|
for (const value of [privateKey, psk, "NEVER_"]) assert.ok(!preview.includes(value))
|
|
return plan
|
|
}
|
|
const beforeHidden = reads
|
|
await assert.rejects(invokeMcpTool(principal, "mm_wireguard_peer_remove_plan", { serverId: 1, peerId: "*b1" }))
|
|
await assert.rejects(invokeMcpTool(principal, "mm_wireguard_peer_remove_plan", { serverId: 105, peerId: "../bad" }))
|
|
assert.equal(reads, beforeHidden)
|
|
interfaces[0].name = "wg-flow"; peers.forEach(row => { row.interface = "wg-flow" })
|
|
await prepare() // An ordinary interface name alone is not an ownership marker.
|
|
interfaces[0].comment = "MikrotikManager traffic-flow overlay"; peers[0].comment = "MM traffic-flow collector"
|
|
const beforeManaged = deletes
|
|
await assert.rejects(prepare(), /NetFlow/); await assert.rejects(prepare(true), /NetFlow/)
|
|
assert.equal((await rest.inject({ method: "DELETE", url: "/api/wireguard/peers/105/*b1" })).statusCode, 409)
|
|
assert.equal(deletes, beforeManaged); reset()
|
|
if (!originalFlow) await pool.query("INSERT INTO traffic_flow_settings(id) VALUES(1)")
|
|
try {
|
|
await pool.query("UPDATE traffic_flow_settings SET host_public_key=$1,peers_json=$2::jsonb WHERE id=1", [publicKey, JSON.stringify([{ serverId: 105 }])])
|
|
const beforeRegistered = deletes
|
|
await assert.rejects(prepare(), /NetFlow/); await assert.rejects(prepare(true), /NetFlow/)
|
|
assert.equal((await rest.inject({ method: "DELETE", url: "/api/wireguard/peers/105/*b1" })).statusCode, 409)
|
|
assert.equal(deletes, beforeRegistered)
|
|
await pool.query("UPDATE traffic_flow_settings SET peers_json=$1::jsonb WHERE id=1", [JSON.stringify([{ serverId: 106 }])])
|
|
await prepare() // A different server's registration grants no ownership here.
|
|
await pool.query("UPDATE traffic_flow_settings SET peers_json='{}'::jsonb WHERE id=1")
|
|
await assert.rejects(prepare(), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE")
|
|
} finally {
|
|
if (originalFlow) await pool.query("UPDATE traffic_flow_settings SET host_public_key=$1,peers_json=$2::jsonb WHERE id=1", [originalFlow.host_public_key, JSON.stringify(originalFlow.peers_json)])
|
|
else await pool.query("DELETE FROM traffic_flow_settings WHERE id=1")
|
|
}
|
|
const legacy = await prepare(true)
|
|
await approvePlan(legacy.planId, actor, true)
|
|
await pool.query("UPDATE mcp_plans SET operation_version=1 WHERE id=$1", [legacy.planId])
|
|
const beforeLegacy = deletes
|
|
await assert.rejects(applyPlan(principal, legacy.planId, randomUUID()), (error: { code?: string }) => error.code === "PLAN_EXPIRED")
|
|
assert.equal(deletes, beforeLegacy)
|
|
const beforePause = reads
|
|
duringRead = () => setConnectionStatus(access.connection.id, "paused", actor)
|
|
await assert.rejects(prepare()); assert.equal(reads, beforePause + 1)
|
|
await setConnectionStatus(access.connection.id, "active", actor)
|
|
for (const key of [publicKey, "", " "]) {
|
|
const binding = randomUUID()
|
|
await pool.query("INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,peer_public_key) VALUES($1,'wg-peer-proof-user',105,'wg-proof',$2)", [binding, key])
|
|
const before = deletes
|
|
await assert.rejects(prepare(), /привязкой/); await assert.rejects(prepare(true), /привязкой/)
|
|
assert.equal((await rest.inject({ method: "DELETE", url: "/api/wireguard/peers/105/*b1" })).statusCode, 409)
|
|
assert.equal(deletes, before)
|
|
await pool.query("DELETE FROM user_interface_bindings WHERE id=$1", [binding])
|
|
}
|
|
const protection = randomUUID()
|
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'integration')", [protection, JSON.stringify({ kind: "wireguard", id: "*a1", serverId: 105, protection: "deny" })])
|
|
const beforeProtected = deletes
|
|
await assert.rejects(prepare()); await assert.rejects(prepare(true))
|
|
assert.equal((await rest.inject({ method: "DELETE", url: "/api/wireguard/peers/105/*b1" })).statusCode, 409)
|
|
assert.equal(deletes, beforeProtected)
|
|
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection])
|
|
let lostOperationId = ""
|
|
for (const fault of ["normal", "ignored", "collateral", "lost"]) {
|
|
reset()
|
|
const plan = await prepare(fault === "normal")
|
|
await approvePlan(plan.planId, actor, true)
|
|
mode = fault
|
|
const before = deletes, key = randomUUID(), operation = await applyPlan(principal, plan.planId, key)
|
|
assert.equal(await wait(operation.id), fault === "normal" ? "applied" : fault === "lost" ? "unknown" : "partial")
|
|
assert.equal(deletes, before + 1)
|
|
assert.equal((await applyPlan(principal, plan.planId, key)).id, operation.id); assert.equal(deletes, 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.automaticRetry, false); assert.equal(reconciliation.results.length, 1)
|
|
assert.equal(reconciliation.results[0].matchesDesiredState, fault === "normal" || fault === "lost")
|
|
assert.equal(reconciliation.results[0].matchesOriginalState, fault === "ignored")
|
|
assert.equal(reconciliation.state, fault === "normal" ? "applied" : fault === "lost" ? "unknown" : "partial")
|
|
assert.equal(deletes, before + 1, "Reconciliation must never reissue DELETE or infer an acknowledgement")
|
|
if (fault === "lost") lostOperationId = operation.id
|
|
if (fault === "normal") { assert.deepEqual(peers, [basePeers[1]]); assert.deepEqual(interfaces, baseInterfaces) }
|
|
}
|
|
const beforeReconcilePause = reads, deletesBeforeReconcilePause = deletes
|
|
duringRead = () => setConnectionStatus(access.connection.id, "paused", actor)
|
|
await assert.rejects(invokeMcpTool(principal, "mm_operation_reconcile", { operationId: lostOperationId }))
|
|
assert.equal(reads, beforeReconcilePause + 1); assert.equal(deletes, deletesBeforeReconcilePause)
|
|
await setConnectionStatus(access.connection.id, "active", actor)
|
|
const cancelled = new AbortController(), beforeCancelledRead = reads
|
|
duringRead = async () => cancelled.abort()
|
|
await assert.rejects(invokeMcpTool(principal, "mm_operation_reconcile", { operationId: lostOperationId }, cancelled.signal), (error: { code?: string }) => error.code === "READ_CANCELLED")
|
|
assert.equal(reads, beforeCancelledRead + 1); assert.equal(deletes, deletesBeforeReconcilePause)
|
|
reset()
|
|
const stale = await prepare(); await approvePlan(stale.planId, actor, true)
|
|
peers[1].rx = "9000" // Runtime counters alone do not invalidate configuration.
|
|
const beforeCounter = deletes, counterOp = await applyPlan(principal, stale.planId, randomUUID())
|
|
assert.equal(await wait(counterOp.id), "applied"); assert.equal(deletes, beforeCounter + 1)
|
|
reset()
|
|
const lateBinding = await prepare(); await approvePlan(lateBinding.planId, actor, true)
|
|
const bindingId = randomUUID()
|
|
await pool.query("INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,peer_public_key) VALUES($1,'wg-peer-proof-user',105,'wg-proof',$2)", [bindingId, publicKey])
|
|
const beforeBinding = deletes, bindingOp = await applyPlan(principal, lateBinding.planId, randomUUID())
|
|
assert.equal(await wait(bindingOp.id), "rejected"); assert.equal(deletes, beforeBinding)
|
|
await pool.query("DELETE FROM user_interface_bindings WHERE id=$1", [bindingId])
|
|
reset()
|
|
const secretDrift = await prepare(); await approvePlan(secretDrift.planId, actor, true)
|
|
peers[1]["preshared-key"] = Buffer.alloc(32, 9).toString("base64")
|
|
const beforeDrift = deletes, driftOp = await applyPlan(principal, secretDrift.planId, randomUUID())
|
|
assert.equal(await wait(driftOp.id), "rejected"); assert.equal(deletes, 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=105"); await pool.query("UPDATE servers SET verify_ssl=NOT verify_ssl WHERE id=105")
|
|
const beforeAba = deletes, abaOp = await applyPlan(principal, aba.planId, randomUUID())
|
|
assert.equal(await wait(abaOp.id), "rejected"); assert.equal(deletes, beforeAba)
|
|
reset(); mode = "provider-error"
|
|
await assert.rejects(prepare(), (error: Error) => !error.message.includes("NEVER_"))
|
|
const failedRest = await rest.inject({ method: "DELETE", url: "/api/wireguard/peers/105/*b1" })
|
|
assert.equal(failedRest.statusCode, 502); assert.ok(!failedRest.body.includes("NEVER_"))
|
|
reset()
|
|
const restBefore = deletes, success = await rest.inject({ method: "DELETE", url: "/api/wireguard/peers/105/*b1" })
|
|
assert.equal(success.statusCode, 200); assert.equal(success.json().verified, true); assert.equal(deletes, restBefore + 1)
|
|
assert.deepEqual(peers, [basePeers[1]]); assert.deepEqual(interfaces, baseInterfaces)
|
|
const recorded = JSON.stringify((await pool.query("SELECT result FROM mcp_requests WHERE connection_id=$1", [connectionId])).rows)
|
|
for (const value of [privateKey, psk, "NEVER_"]) assert.ok(!recorded.includes(value))
|
|
console.log("✓ Shared WireGuard peer deletion REST/MCP/native alias: bindings/whole interface/parent protection, private opaque proof, counter tolerance, secret/endpoint ABA drift, exact one DELETE, ignored/collateral partial, lost unknown, revision receipt, privacy and no replay")
|
|
} finally {
|
|
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
|
|
await pool.query("DELETE FROM mcp_protections WHERE object_ref->>'serverId'='105'")
|
|
await pool.query("DELETE FROM app_users WHERE id='wg-peer-proof-user'")
|
|
await pool.query("DELETE FROM servers WHERE id=105")
|
|
await rest.close(); router.closeAllConnections()
|
|
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
|
}
|
|
}
|