Files
MikrotikManager/backend/src/modules/mcp/ipv6-nd-write-acceptance.ts
T

302 lines
16 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 { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { ZodError } from "zod"
import { pool } from "../../db/index.js"
import type { AuthUser } from "../../lib/permissions.js"
import { applyPlan, approvePlan, invokeMcpTool } from "./runtime.js"
import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js"
type NativeRow = Record<string, string>
type OperationState = { state: string; verification: string; error_code: string | null }
/** Runs on a disposable PostgreSQL database and models RouterOS using loopback HTTP. */
export async function acceptIpv6NdWriteMcp(actor: AuthUser, listsOnly = false) {
const ndPath = "/ipv6/nd"
const prefixPath = "/ipv6/nd/prefix"
const settingsPath = "/ipv6/nd/settings"
const routeDistanceKey = "router-advertisement-route-distance"
const ignoredOptionsKey = "router-advertisement-ignored-options"
const prefixId = "*A5"
const optionalRaId = "*A6"
const ra = { ".id": "*A1", interface: "all", default: "true", "advertise-dns": "no", disabled: "false", pref64: "64:ff9b::/96" }
const settings: NativeRow = { [routeDistanceKey]: "120", [ignoredOptionsKey]: "dns,mtu" }
const unrelated = { ".id": "*A2", interface: "ether2", prefix: "2001:db8:20::/64", "valid-lifetime": "1d", "preferred-lifetime": "30m", dynamic: "false", disabled: "false" }
const ethernet = [
{ ".id": "*E1", name: "ether1", type: "ether", disabled: "false" },
{ ".id": "*E2", name: "ether2", type: "ether", disabled: "false" },
]
const catalogs: Record<string, NativeRow[]> = {
[ndPath]: [ra],
[prefixPath]: [structuredClone(unrelated)],
"/interface": ethernet,
"/interface/ethernet": ethernet,
"/interface/bridge": [],
"/interface/bridge/port": [],
"/interface/bridge/vlan": [],
"/interface/vlan": [],
"/interface/gre": [],
"/interface/wireguard": [],
"/interface/vxlan": [],
"/interface/list": [],
"/interface/list/member": [],
"/ip/address": [],
"/ipv6/address": [],
"/ip/vrf": [],
}
const writes: { method: string; path: string; fields: NativeRow }[] = []
const router = createServer(async (req, res) => {
try {
const url = new URL(req.url ?? "", "http://127.0.0.1")
const path = decodeURIComponent(url.pathname.replace(/^\/rest/, ""))
res.setHeader("content-type", "application/json")
if (req.method === "GET" && path === settingsPath) {
res.end(JSON.stringify(settings))
return
}
if (req.method === "GET" && Object.hasOwn(catalogs, path)) {
res.end(JSON.stringify(catalogs[path]))
return
}
const parent = [settingsPath, prefixPath, ndPath].find(menu => path === menu || path.startsWith(menu + "/"))
if (!parent) { res.writeHead(404).end("{}"); return }
const method = req.method ?? ""
const rows = catalogs[parent] ?? []
const index = rows.findIndex(row => row[".id"] === path.slice(parent.length + 1))
const setting = method === "POST" && path === settingsPath + "/set"
const creating = method === "PUT" && path === parent && parent !== settingsPath
const updating = method === "PATCH" && index !== -1
const deleting = method === "DELETE" && index !== -1
if (!setting && !creating && !updating && !deleting) { res.writeHead(405).end("{}"); return }
let body = ""
for await (const chunk of req) body += chunk
const fields: NativeRow = body ? JSON.parse(body) : {}
writes.push({ method, path, fields })
if (setting) {
Object.assign(settings, fields)
res.end("[]")
return
}
if (creating) {
const row = { ".id": parent === prefixPath ? prefixId : optionalRaId, dynamic: "false", disabled: "false", ...fields }
rows.push(row)
res.writeHead(201).end(JSON.stringify(row))
return
}
if (updating) {
Object.assign(rows[index], fields)
res.end(JSON.stringify(rows[index]))
return
}
rows.splice(index, 1)
res.writeHead(204).end()
} catch {
res.writeHead(500).end("{}")
}
})
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
let serverId: number | undefined
let connectionId: string | undefined
const protection = randomUUID()
const waitForOperation = async (id: string) => {
const deadline = Date.now() + 45_000
while (Date.now() < deadline) {
const { rows: [row] } = await pool.query<OperationState>("SELECT state,verification,error_code FROM mcp_operations WHERE id=$1", [id])
if (row && !["pending", "running"].includes(row.state)) return row
await delay(25)
}
throw new Error("IPv6 ND operation remains live")
}
try {
const port = (router.address() as { port: number }).port
const { rows: [server] } = await pool.query<{ id: number }>("INSERT INTO servers(name,host,port,use_ssl,password) VALUES('ipv6-nd-write','127.0.0.1',$1,false,'fixture-only') RETURNING id", [port])
serverId = Number(server.id)
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({
name: "IPv6 ND native writes", mode: "approval", expiresAt: new Date(Date.now() + 1_800_000).toISOString(),
permissions: ["mm:network:read", "mm:network:write"],
scope: {
serverIds: [serverId],
operationIds: ["ros.ipv6_nd.create", "ros.ipv6_nd.update", "ros.ipv6_nd.delete", "ros.ipv6_nd_prefix.create", "ros.ipv6_nd_prefix.update", "ros.ipv6_nd_prefix.delete", "network.ipv6.nd.settings.get", "ros.ipv6_nd_settings.update", "operations.recover"],
allowGlobal: false,
},
limits: { callsPerMinute: 120, mutationsPerHour: 100 },
}), actor)
connectionId = access.connection.id
const principal = await authenticateMcpToken(access.token)
const prepare = (tool: string, input: Record<string, unknown>) => invokeMcpTool(principal, tool, { serverId, ...input }) as Promise<{ planId: string }>
const dispatch = async (planId: string) => {
const operation = await applyPlan(principal, planId, randomUUID())
return { id: operation.id, ...await waitForOperation(operation.id) }
}
const apply = async (planId: string) => {
await approvePlan(planId, actor, true)
const operation = await dispatch(planId)
assert.equal(operation.state, "applied", JSON.stringify(operation))
assert.equal(operation.verification, "passed", JSON.stringify(operation))
return operation
}
const run = async (tool: string, input: Record<string, unknown>) => apply((await prepare(tool, input)).planId)
const recover = async (operationId: string) => {
const inverse = await invokeMcpTool(principal, "mm_operation_recovery_plan", { operationId }) as { planId: string }
return apply(inverse.planId)
}
if (listsOnly) {
const empty = { dns: "", pref64: "" }
const configured = { dns: "2001:db8::53,2001:db8::54", pref64: "2001:db8:64::/96,2001:db8:65::/64" }
const rule: NativeRow = { ".id": optionalRaId, interface: "ether1", disabled: "true", "advertise-dns": "no", ...empty }
const initial = structuredClone(rule)
const defaultBefore = structuredClone(ra)
catalogs[ndPath].push(rule)
const tool = "mm_ipv6_nd_update_plan", id = optionalRaId
const populated = await run(tool, { id, fields: configured })
assert.deepEqual(rule, { ...initial, ...configured })
const cleared = await run(tool, { id, fields: empty })
assert.deepEqual(rule, initial)
const restored = await recover(cleared.id)
assert.deepEqual(rule, { ...initial, ...configured })
assert.deepEqual(ra, defaultBefore)
for (const key of ["dns", "pref64"] as const) {
delete rule[key]
await assert.rejects(prepare(tool, { id, fields: { [key]: configured[key] } }), { code: "STATE_UNAVAILABLE" })
await assert.rejects(prepare(tool, { id, fields: { [key]: "" } }), { code: "STATE_UNAVAILABLE" })
rule[key] = configured[key]
}
assert.deepEqual(writes, [configured, empty, configured].map(fields => ({ method: "PATCH", path: `${ndPath}/${id}`, fields })))
for (const operation of [populated, cleared, restored]) {
const { rows } = await pool.query(
`SELECT s.state, c.before_sealed IS NOT NULL AS before_saved, c.after_sealed IS NOT NULL AS after_saved
FROM mcp_operation_steps s LEFT JOIN mcp_operation_checkpoints c USING (operation_id,step_index)
WHERE s.operation_id=$1`, [operation.id],
)
assert.deepEqual(rows, [{ state: "verified", before_saved: true, after_saved: true }])
}
console.log("✓ IPv6 ND DNS/PREF64 SQL/HTTP: explicit empty values, one verified step per approved PATCH or inverse, absent baselines rejected")
return
}
const readSettings = async () => {
const result = await invokeMcpTool(principal, "mm_ipv6_nd_settings_get", { serverId }) as { settings: { routeDistance: number; ignoredOptions: string[] } }
return { routeDistance: result.settings.routeDistance, ignoredOptions: result.settings.ignoredOptions }
}
await run("mm_ipv6_nd_prefix_create_plan", {
fields: { interface: "ether1", prefix: "2001:db8:10::/64", "valid-lifetime": "1d", "preferred-lifetime": "30m", autonomous: true },
})
const created = catalogs[prefixPath].find(row => row[".id"] === prefixId)
assert.ok(created)
assert.equal(created.prefix, "2001:db8:10::/64")
assert.equal(created["valid-lifetime"], "86400s")
assert.equal(created["preferred-lifetime"], "1800s")
const original = structuredClone(created)
for (const [tool, fields] of [
["mm_ipv6_nd_create_plan", { interface: "none" }],
["mm_ipv6_nd_prefix_create_plan", { interface: "all", prefix: "2001:db8:11::/64" }],
["mm_ipv6_nd_prefix_create_plan", { interface: "ether1", prefix: "2001:db8:11::/64", "6to4-interface": "all" }],
] as const) {
await assert.rejects(prepare(tool, { fields }), { code: "INVALID_INPUT" })
}
await assert.rejects(prepare("mm_ipv6_nd_prefix_update_plan", { id: prefixId, fields: { "preferred-lifetime": "2d" } }), { code: "INVALID_INPUT" })
await assert.rejects(prepare("mm_ipv6_nd_delete_plan", { id: ra[".id"] }), { code: "PROTECTED_OBJECT" })
assert.equal(writes.length, 1)
const lifetimes = { "valid-lifetime": "2d", "preferred-lifetime": "1h" }
const updated = await run("mm_ipv6_nd_prefix_update_plan", { id: prefixId, fields: lifetimes })
assert.equal(created["valid-lifetime"], "172800s")
assert.equal(created["preferred-lifetime"], "3600s")
await recover(updated.id)
assert.deepEqual(created, original)
const raInput = { id: ra[".id"], fields: { "advertise-dns": "self" } }
const writesBeforeProtection = writes.length
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)", [protection, JSON.stringify({ kind: "ethernet", id: "*E1", serverId, protection: "deny" }), actor.id])
try {
await assert.rejects(prepare("mm_ipv6_nd_update_plan", raInput), { code: "PROTECTED_OBJECT" })
assert.equal(writes.length, writesBeforeProtection)
} finally {
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protection])
}
const stale = await prepare("mm_ipv6_nd_prefix_update_plan", { id: prefixId, fields: lifetimes })
await approvePlan(stale.planId, actor, true)
const writesBeforeDrift = writes.length
ethernet[0][".id"] = "*E3"
try {
assert.equal((await dispatch(stale.planId)).state, "rejected")
assert.equal(writes.length, writesBeforeDrift)
assert.deepEqual(created, original)
} finally {
ethernet[0][".id"] = "*E1"
}
const sourceAddress = { ".id": "*D1", interface: "ether2", address: "192.0.2.5/24" }
catalogs["/ip/address"].push(sourceAddress)
created["6to4-interface"] = "ether2"
try {
const stale6to4 = await prepare("mm_ipv6_nd_prefix_update_plan", { id: prefixId, fields: lifetimes })
await approvePlan(stale6to4.planId, actor, true)
sourceAddress.address = "192.0.2.6/24"
assert.equal((await dispatch(stale6to4.planId)).state, "rejected")
assert.equal(writes.length, writesBeforeDrift)
} finally {
catalogs["/ip/address"].pop()
delete created["6to4-interface"]
}
await run("mm_ipv6_nd_update_plan", raInput)
assert.equal(ra["advertise-dns"], "self")
const beforeInvalidPref64 = writes.length
await assert.rejects(
prepare("mm_ipv6_nd_update_plan", { id: ra[".id"], fields: { pref64: "2001:db8:64::/65" } }),
error => error instanceof ZodError && error.issues.some(issue => issue.path.join(".") === "fields.pref64"),
)
assert.equal(writes.length, beforeInvalidPref64)
const previousRa = structuredClone(ra)
const pref64 = await run("mm_ipv6_nd_update_plan", { id: ra[".id"], fields: { pref64: "2001:0DB8:0064::/96,2001:0DB8:0065::/64" } })
assert.deepEqual(ra.pref64.split(",").sort(), ["2001:db8:64::/96", "2001:db8:65::/64"])
assert.equal(ra["advertise-dns"], "self")
await recover(pref64.id)
assert.deepEqual(ra, previousRa)
assert.deepEqual(await readSettings(), { routeDistance: 120, ignoredOptions: ["dns", "mtu"] })
const distance = await run("mm_ipv6_nd_settings_update_plan", { fields: { [routeDistanceKey]: 150 } })
assert.deepEqual(writes.at(-1)?.fields, { [routeDistanceKey]: "150" })
assert.deepEqual(await readSettings(), { routeDistance: 150, ignoredOptions: ["dns", "mtu"] })
await recover(distance.id)
assert.deepEqual(await readSettings(), { routeDistance: 120, ignoredOptions: ["dns", "mtu"] })
const clearOptions = await run("mm_ipv6_nd_settings_update_plan", { fields: { [ignoredOptionsKey]: "" } })
assert.deepEqual(writes.at(-1)?.fields, { [ignoredOptionsKey]: "" })
assert.deepEqual(await readSettings(), { routeDistance: 120, ignoredOptions: [] })
await recover(clearOptions.id)
assert.deepEqual(await readSettings(), { routeDistance: 120, ignoredOptions: ["dns", "mtu"] })
await run("mm_ipv6_nd_create_plan", { fields: { interface: "ether2", disabled: true, "ra-interval": "3m20s-10m", "ra-lifetime": "30m" } })
assert.equal(catalogs[ndPath].find(row => row[".id"] === optionalRaId)?.["ra-interval"], "200s-600s")
await run("mm_ipv6_nd_delete_plan", { id: optionalRaId })
assert.deepEqual(catalogs[ndPath], [ra])
await run("mm_ipv6_nd_prefix_delete_plan", { id: prefixId })
assert.deepEqual(catalogs[prefixPath], [unrelated])
assert.deepEqual(writes.map(({ method, path }) => ({ method, path })), [
{ method: "PUT", path: prefixPath },
{ method: "PATCH", path: `${prefixPath}/${prefixId}` },
{ method: "PATCH", path: `${prefixPath}/${prefixId}` },
{ method: "PATCH", path: `${ndPath}/${ra[".id"]}` },
{ method: "PATCH", path: `${ndPath}/${ra[".id"]}` },
{ method: "PATCH", path: `${ndPath}/${ra[".id"]}` },
...Array.from({ length: 4 }, () => ({ method: "POST", path: `${settingsPath}/set` })),
{ method: "PUT", path: ndPath },
{ method: "DELETE", path: `${ndPath}/${optionalRaId}` },
{ method: "DELETE", path: `${prefixPath}/${prefixId}` },
])
console.log("✓ IPv6 ND SQL/HTTP: verified prefix writes, RA DNS and PREF64, partial ND settings updates and inverse, interface protection and post-approval drift")
} finally {
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
if (serverId !== undefined) await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId])
router.closeAllConnections()
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
}
}