Files
MikrotikManager/backend/src/modules/mcp/wireguard-interface-create-acceptance.ts
T
Denozordec d255694cda
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m41s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / updater-image (push) Successful in 1m17s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
fix(mcp): исправить проверку зависимостей туннеля на больших таблицах маршрутов
2026-11-22 17:51:05 +07:00

169 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 { 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, WIREGUARD_PEER_KEY_PURPOSE, wireguardInterfaceCreatePlanSchema } from "./wireguard-interface-create-actions.js"
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
type Rows = Record<string, Record<string, string>[]>
export async function acceptWireguardInterfaceCreation(actor: AuthUser) {
const privateKey = Buffer.alloc(32, 51).toString("base64"), peerPrivateKey = Buffer.alloc(32, 52).toString("base64"), generatedKey = Buffer.alloc(32, 53).toString("base64")
const initial: Rows = Object.fromEntries(wireguardInterfaceDependencyPaths.map(path => [path, []]))
initial["/interface/wireguard"] = [{ ".id": "*af", name: "wg-foreign", disabled: "true", "public-key": wireguardPublicKey(generatedKey), "private-key": "NEVER_FOREIGN_PRIVATE" }]
initial["/interface/wireguard/peers"] = [{ ".id": "*pf", interface: "wg-foreign", "public-key": "foreign", opaque: "NEVER_FOREIGN_OPAQUE", rx: "0" }]
initial["/interface"] = [{ ".id": "*af", name: "wg-foreign", type: "wg" }]
initial["/ip/address"] = [{ ".id": "*vf", address: "203.0.113.2/24", interface: "ether1", dynamic: "false", disabled: "false" }]
initial["/ipv6/address"] = []
initial["/ip/route"] = Array.from({ length: 12_608 }, (_, index) => ({
".id": `*r${index.toString(16)}`, dynamic: "true", bgp: "true", gateway: "192.0.2.1", "immediate-gw": "192.0.2.1%ether1",
}))
let rows = structuredClone(initial), mode = "normal", reads = 0, commands: string[] = [], counter = 0
let afterWrite: (() => Promise<unknown>) | undefined
const reset = () => { rows = structuredClone(initial); mode = "normal"; commands = []; counter = 0; afterWrite = undefined }
const router = createServer((req, res) => {
res.setHeader("content-type", "application/json")
const [pathname, query] = (req.url ?? "").slice(5).split("?")
const path = decodeURIComponent(pathname)
const selectedRows = () => rows[path].filter(row => !query || (row.dynamic === "true") === query.startsWith("dynamic=true"))
if (req.method === "GET") {
reads++
if (mode === "provider-error") { res.statusCode = 400; 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(selectedRows())); return
}
const base = ["/interface/wireguard/peers", "/interface/wireguard", "/ip/address", "/ipv6/address"].find(base => path === base || path.startsWith(base + "/"))
if (!base || !["PUT", "PATCH"].includes(req.method ?? "")) { 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 id = "*c" + ++counter, row: Record<string, string> = { ".id": id, ...body }
if (base === "/interface/wireguard") { row["private-key"] ??= generatedKey; row["public-key"] = wireguardPublicKey(row["private-key"]); rows["/interface"].push({ ".id": id, name: row.name, type: "wg" }) }
if (base === "/ip/address" || base === "/ipv6/address") row.dynamic = "false"
if (row["private-key"] === "auto") row["private-key"] = generatedKey
rows[base].push(row)
} else Object.assign(rows[base].find(row => row[".id"] === path.slice(base.length + 1))!, body)
}
if (mode === "collateral") rows["/ip/address"][0].comment = "NEVER_COLLATERAL"
if (mode === "staged-collateral" && commands.length === 2) rows["/interface/wireguard"].find(row => row.name === "wg-created")!.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 = 111, 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 creation remains live; never replay")
}
let connectionId: string | undefined
try {
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES(111,'wg-interface-create','127.0.0.1',$1,false,'NEVER_CREATE_ENDPOINT_PASSWORD')", [(router.address() as { port: number }).port])
await pool.query("INSERT INTO app_users(id,login,name) VALUES('wg-create-user','wg-create-user','Create fixture')")
await rest.register(wireguardRoutes, { prefix: "/api" })
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "WireGuard creation", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [111], operationIds: ["network.wireguard.interfaces.create", "operations.reconcile", "operations.recover"], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 100 } }), actor)
connectionId = access.connection.id
const principal = await authenticateMcpToken(access.token)
const privateKeyRef = await secret(WIREGUARD_INTERFACE_KEY_PURPOSE, privateKey), peerKeyRef = await secret(WIREGUARD_PEER_KEY_PURPOSE, peerPrivateKey)
const full = { serverId: 111, name: "wg-created", listenPort: 14321, mtu: 1380, comment: "owned interface", privateKeyRef, address: "2001:db8:251::1/64", peer: { publicKey: wireguardPublicKey(peerPrivateKey), allowedAddresses: ["192.0.2.2/32", "2001:db8:251::2/128"], endpointAddress: "vpn.example.org", endpointPort: 24321, persistentKeepalive: 25, comment: "owned peer", name: "owned-peer", privateKeyRef: peerKeyRef, clientAddress: "192.0.2.2", clientDns: "1.1.1.1", clientEndpoint: "client.example.org" } }
const prepare = async (input: unknown = full) => {
const plan = await invokeMcpTool(principal, "mm_wireguard_interface_create_plan", input) as { planId: string; state: string; changes: { mutationCost: number } }
assert.equal(plan.state, "awaiting-approval")
for (const value of [privateKey, peerPrivateKey, "NEVER_"]) assert.ok(!JSON.stringify(plan).includes(value))
return plan
}
const beforeInvalid = reads
for (const input of [{ ...full, serverId: 1 }, { ...full, privateKey }, { ...full, name: "\u0000bad" }, { ...full, peer: { ...full.peer, privateKey } }]) await assert.rejects(prepare(input))
assert.equal(wireguardInterfaceCreatePlanSchema.safeParse({ ...full, privateKey }).success, false)
assert.equal(reads, beforeInvalid)
for (const ref of [await secret("wrong-purpose", privateKey), await secret(WIREGUARD_INTERFACE_KEY_PURPOSE, privateKey, null), await secret(WIREGUARD_INTERFACE_KEY_PURPOSE, privateKey, 111, "wg-create-user")]) { await assert.rejects(prepare({ ...full, privateKeyRef: ref })); assert.equal(commands.length, 0) }
for (const [path, row] of [["/interface/vlan", { interface: full.name }], ["/routing/filter/rule", { rule: 'set gw "wg-created";' }], ["/routing/ospf/interface-template", { networks: "2001:db8:251::/64" }], ["/ip/vrf", { name: "other", interfaces: "all" }]] as [string, Record<string, string>][]) { reset(); rows[path].push({ ".id": "*ref", ...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", id: "*af", serverId: 111, protection: "deny" }, actor.id])
try { await assert.rejects(prepare()); const response = await rest.inject({ method: "POST", url: "/api/wireguard/interfaces", payload: { serverId: 111, name: "wg-created" } }); assert.equal(response.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", "lost", "staged-collateral"]) {
reset(); const plan = await prepare(); assert.equal(plan.changes.mutationCost, 7); await approvePlan(plan.planId, actor, true); mode = fault
const 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, JSON.stringify({ fault, ...(await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [operation.id])).rows[0] }))
assert.equal(commands.length, fault === "normal" ? 6 : fault === "staged-collateral" ? 2 : 1)
assert.equal((await applyPlan(principal, plan.planId, key)).id, operation.id)
const count: number = commands.length
const reconciled = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { automaticRetry: boolean; results: { matchesDesiredState: boolean; matchesOriginalState: boolean; matchesExpectedPrefixState: boolean; verifiedPrefixCommands: number | null }[] }
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") {
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.peers.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, principal: { ...saved.intended_state.input.principal, credentialId: randomUUID() } } } },
{ state: "verified", intended: { ...saved.intended_state, input: { ...saved.intended_state.input, ownerId: "foreign-owner" } } },
{ state: "verified", intended: { ...saved.intended_state, input: { ...saved.intended_state.input, requestProof: "0".repeat(64) } } },
]) {
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, "An unverified or foreign checkpoint cannot prove creation")
assert.equal(commands.length, count, "Checkpoint rejection must remain read-only")
}
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)])
const trusted = await invokeMcpTool(principal, "mm_operation_reconcile", { operationId: operation.id }) as { results: { matchesDesiredState: boolean }[] }
assert.equal(trusted.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")
if (fault === "normal") { assert.equal(rows["/interface/wireguard"].find(row => row.name === full.name)?.disabled, "false"); assert.equal(rows["/ipv6/address"][0].advertise, "false"); assert.equal(rows["/interface/wireguard/peers"].length, 2) }
}
reset(); const stale = await prepare(); await approvePlan(stale.planId, actor, true); rows["/interface/wireguard/peers"][0].opaque = "NEVER_LATE_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 address of ["192.0.2.1/24", "2001:db8:252::1/64"]) {
reset(); const plan = await prepare({ serverId: 111, name: "wg-created", address, disabled: true, peer: { publicKey: full.peer.publicKey, allowedAddresses: full.peer.allowedAddresses, disabled: true, privateKeyMode: "auto" } }); await approvePlan(plan.planId, actor, true)
assert.equal(await wait((await applyPlan(principal, plan.planId, randomUUID())).id), "applied"); assert.equal(commands.length, 4)
}
reset(); mode = "provider-error"; await assert.rejects(prepare(), (error: Error) => !error.message.includes("NEVER_"))
assert.ok(!(await rest.inject({ method: "POST", url: "/api/wireguard/interfaces", payload: { serverId: 111, name: "wg-created" } })).body.includes("NEVER_"))
reset()
const response = await rest.inject({ method: "POST", url: "/api/wireguard/interfaces", payload: { ...full, privateKeyRef: undefined, privateKey, peer: { ...full.peer, privateKeyRef: undefined, privateKey: peerPrivateKey } } })
assert.equal(response.statusCode, 201, response.body); assert.equal(response.json().name, full.name); assert.equal(response.json().privateKey, privateKey); assert.equal(commands.length, 6)
reset()
const namedResponse = await rest.inject({ method: "POST", url: "/api/wireguard/interfaces", payload: { serverId: 111, name: 'WG тест "edge" [x]' } })
assert.equal(namedResponse.statusCode, 201, namedResponse.body); assert.equal(namedResponse.json().name, 'WG тест "edge" [x]'); assert.equal(commands.length, 2)
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 + "%", "%" + peerPrivateKey + "%"])).rows[0].n, 0)
const intents = await pool.query("SELECT count(*)::int AS n FROM mcp_audit WHERE action='configuration.intent' AND payload->>'serverId'='111'")
assert.ok(intents.rows[0].n >= commands.length)
console.log("✓ WireGuard create shared REST/MCP: full optional address/peer/key fields, secret purpose/owner/server/rotation, disabled preparation and activation, whole-source/protection/selector checks, prefix/read-back/opaque preservation, lost/partial/revoke/no replay, IPv4/IPv6 and private REST DTO")
} 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-create-user'")
await pool.query("DELETE FROM servers WHERE id=111")
}
}