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 { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp" import { pool } from "../../db/index.js" import type { AuthUser } from "../../lib/permissions.js" import { approvePlan, applyPlan, invokeMcpTool } from "./runtime.js" import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js" export async function acceptInterfaceRename(actor: AuthUser) { const serverId = 174 const initial: Record[]> = { "/interface": [ { ".id": "*7", name: "wg1", type: "wg", dynamic: "false" }, { ".id": "*8", name: "ether1", "default-name": "ether1", type: "ether" }, { ".id": "*9", name: "radio one", type: "wifi" }, { ".id": "*a", name: "dynamic1", type: "ppp", dynamic: "true" }, { ".id": "*b", name: "wg1-backup", type: "wg" }, ], "/ip/address": [{ ".id": "*15", interface: "wg1", "actual-interface": "wg1", address: "192.0.2.1/30" }], "/ipv6/address": [{ ".id": "*16", interface: "*7", address: "2001:db8::1/64" }], "/interface/bridge/port": [{ ".id": "*14", bridge: "bridge1", interface: "ether1" }], "/interface/wireguard/peers": [{ ".id": "*11", interface: "wg1", name: "other-site", "public-key": "fixture-public-key", "allowed-address": "192.0.2.2/32", "endpoint-port": "13235" }], "/ip/firewall/filter": [ { ".id": "*20", chain: "input", action: "accept", "in-interface": "wg1", protocol: "udp" }, { ".id": "*21", chain: "forward", action: "drop", "in-interface": "!wg1", "out-interface": "wg1-backup" }, ], "/ip/route": [{ ".id": "*22", static: "true", gateway: "192.0.2.2%wg1@main", "dst-address": "198.51.100.0/24" }, ...Array.from({ length: 12_608 }, (_, i) => ({ ".id": `*r${i.toString(16)}`, dynamic: "true", gateway: "192.0.2.2%ether1" }))], } let rows = structuredClone(initial), reads = 0, mode: "normal" | "stale" | "lost" = "normal" const writes: { path: string; fields: Record }[] = [] const router = createServer(async (req, res) => { const url = new URL(req.url ?? "/", "http://fixture.invalid"), path = url.pathname.slice(5) res.setHeader("content-type", "application/json") if (req.method === "GET") { let records = rows[path] ?? [] if (url.searchParams.get("static") === "true") records = records.filter(row => row.static === "true") const properties = url.searchParams.get(".proplist")?.split(",") if (properties) records = records.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key)))) if (path === "/ip/firewall/filter") records = records.map(row => ({ ...row, packets: String(++reads) })) res.end(JSON.stringify(records)); return } if (req.method !== "PATCH" || !/^\/interface\/\*[a-z0-9]+$/i.test(path)) { res.statusCode = 400; res.end("{}"); return } let body = ""; for await (const chunk of req) body += chunk const fields: Record = JSON.parse(body), target = rows["/interface"].find(row => path.endsWith("/" + row[".id"]))! const old = target.name writes.push({ path, fields }) Object.assign(target, fields) if (mode !== "stale") { for (const rowsForPath of Object.values(rows)) for (const row of rowsForPath) for (const key of ["interface", "actual-interface", "in-interface", "out-interface"]) { if (row[key] === old) row[key] = target.name if (row[key] === "!" + old) row[key] = "!" + target.name } for (const row of rows["/ip/route"]) if (row.gateway.endsWith(`%${old}@main`)) row.gateway = row.gateway.replace(`%${old}@main`, `%${target.name}@main`) } if (mode === "lost") { req.socket.destroy(); return } res.end(JSON.stringify(target)) }) await new Promise(resolve => router.listen(0, "127.0.0.1", resolve)) let connectionId: string | undefined const protection = randomUUID() try { await pool.query("INSERT INTO servers(id,name,host,port,use_ssl) VALUES($1,'interface-rename-fixture','127.0.0.1',$2,false)", [serverId, (router.address() as { port: number }).port]) const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "interface rename", mode: "approval", expiresAt: new Date(Date.now() + 1_800_000).toISOString(), permissions: ["mm:network:write"], scope: { serverIds: [serverId], operationIds: ["interfaces.rename"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), actor) connectionId = access.connection.id const principal = await authenticateMcpToken(access.token) const plan = async (iface: string, name: string) => (await invokeMcpTool(principal, "mm_interface_rename_plan", { serverId, interface: iface, name })) as { planId: string } const execute = async (iface: string, name: string) => { const { planId } = await plan(iface, name) await approvePlan(planId, actor, true) const { id } = await applyPlan(principal, planId, randomUUID()) for (let i = 0; i < 500; i++) { const result = (await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0] if (result && !["pending", "running"].includes(result.state)) return result await delay(20) } throw new Error("Interface rename remains live") } await assert.rejects(plan("dynamic1", "renamed"), { code: "PROTECTED_OBJECT" }) await assert.rejects(plan("*7", "ether1"), { code: "STATE_CONFLICT" }) assert.equal(writes.length, 0) await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)", [protection, JSON.stringify({ kind: "ip_filter", id: "*20", serverId, protection: "deny" }), actor.id]) await assert.rejects(plan("*7", "protected-test"), { code: "PROTECTED_OBJECT" }) await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection]) assert.equal((await execute("wg1", "wg-to-msk-gw01")).state, "applied") assert.deepEqual(writes[0], { path: "/interface/*7", fields: { name: "wg-to-msk-gw01" } }) assert.deepEqual(rows["/ip/firewall/filter"].map(row => row["in-interface"]), ["wg-to-msk-gw01", "!wg-to-msk-gw01"]) assert.equal(rows["/ip/firewall/filter"][1]["out-interface"], "wg1-backup") assert.equal(rows["/interface/wireguard/peers"][0].interface, "wg-to-msk-gw01") assert.equal(rows["/ipv6/address"][0].interface, "*7") assert.equal(rows["/ip/route"][0].gateway, "192.0.2.2%wg-to-msk-gw01@main") assert.equal((await execute("*8", "ether-wan")).state, "applied") assert.equal(rows["/interface/bridge/port"][0].interface, "ether-wan") assert.equal((await execute("radio one", "wifi guest")).state, "applied") assert.equal(writes.length, 3) mode = "stale" assert.equal((await execute("wg-to-msk-gw01", "wg-incomplete")).error_code, "VERIFICATION_FAILED") assert.equal(writes.length, 4) rows = structuredClone(initial); mode = "lost" assert.equal((await execute("wg1", "wg-unknown")).error_code, "MUTATION_OUTCOME_UNKNOWN") assert.equal(writes.length, 5) } finally { await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection]) if (connectionId) await setConnectionStatus(connectionId, "paused", actor) await pool.query("DELETE FROM servers WHERE id=$1", [serverId]) router.closeAllConnections() await new Promise((resolve, reject) => router.close(error => error ? reject(error) : resolve())) } }