Устаревший тест, не дефект продукта. Приёмки ARP и IPv6 ND оставляли свою
строку servers (только enabled=false), тогда как все соседние приёмки
удаляют фикстуру. После 88e82702 они создаются стабильно, и лишние строки
доходили до Legacy OSPF, который по задокументированному правилу требует
допуск ко всему каталогу (не более 10 серверов, все в scope). Соединение
приёмки OSPF ограничено серверами [1,2], поэтому каталог отклонялся.
Продуктовое правило не ослабляется: фикстуры удаляются в finally (FK на
servers каскадные; на них ничего позже не ссылается).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
168 lines
8.5 KiB
TypeScript
168 lines
8.5 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 { 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 acceptArpWriteMcp(actor: AuthUser) {
|
|
const arpPath = "/ip/arp"
|
|
const nativeId = "*A5"
|
|
const ethernet = [
|
|
{ ".id": "*E1", name: "ether1", type: "ether", disabled: "false" },
|
|
{ ".id": "*E2", name: "ether2", type: "ether", disabled: "false" },
|
|
]
|
|
const staticFlags = { dynamic: "false", dhcp: "false", disabled: "false", published: "false" }
|
|
const original: NativeRow[] = [
|
|
{ ...staticFlags, ".id": "*A1", address: "192.0.2.1", interface: "ether1", "mac-address": "02:00:00:00:00:01", dynamic: "true" },
|
|
{ ...staticFlags, ".id": "*A2", address: "192.0.2.2", interface: "ether1", "mac-address": "02:00:00:00:00:02", dhcp: "true" },
|
|
{ ...staticFlags, ".id": "*A3", address: "192.0.2.3", interface: "ether2", "mac-address": "02:00:00:00:00:03" },
|
|
]
|
|
const arpRows = structuredClone(original)
|
|
const catalogs: Record<string, NativeRow[]> = {
|
|
[arpPath]: arpRows,
|
|
"/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": [{ ".id": "*F1", name: "main", interfaces: "all" }],
|
|
}
|
|
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" && Object.hasOwn(catalogs, path)) {
|
|
res.end(JSON.stringify(catalogs[path]))
|
|
return
|
|
}
|
|
const method = req.method ?? ""
|
|
const index = path.startsWith(arpPath + "/") ? arpRows.findIndex(row => row[".id"] === path.slice(arpPath.length + 1)) : -1
|
|
const creating = method === "PUT" && path === arpPath
|
|
const updating = method === "PATCH" && index !== -1
|
|
const deleting = method === "DELETE" && index !== -1
|
|
if (!creating && !updating && !deleting) {
|
|
res.writeHead(404).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 (creating) {
|
|
const row = { ...staticFlags, ".id": nativeId, ...fields }
|
|
arpRows.push(row)
|
|
res.writeHead(201).end(JSON.stringify(row))
|
|
return
|
|
}
|
|
if (updating) {
|
|
Object.assign(arpRows[index], fields)
|
|
res.end(JSON.stringify(arpRows[index]))
|
|
return
|
|
}
|
|
arpRows.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 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("ARP operation remains live")
|
|
}
|
|
try {
|
|
const port = (router.address() as { port: number }).port
|
|
const { rows: [server] } = await pool.query<{ id: number }>("INSERT INTO servers(id,name,host,port,use_ssl,password) SELECT COALESCE(MAX(id),0)+1,'arp-write','127.0.0.1',$1::int,false,'fixture-only' FROM servers RETURNING id", [port])
|
|
serverId = Number(server.id)
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({
|
|
name: "Static ARP writes", mode: "approval", expiresAt: new Date(Date.now() + 1_800_000).toISOString(),
|
|
permissions: ["mm:network:read", "mm:network:write"],
|
|
scope: { serverIds: [serverId], operationIds: ["ros.ip_arp.create", "ros.ip_arp.update", "ros.ip_arp.delete", "operations.recover"], allowGlobal: false },
|
|
}), 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)
|
|
|
|
await assert.rejects(prepare("mm_ip_arp_update_plan", { id: "*A1", fields: { disabled: true } }), { code: "PROTECTED_OBJECT" })
|
|
await assert.rejects(prepare("mm_ip_arp_delete_plan", { id: "*A2" }), { code: "PROTECTED_OBJECT" })
|
|
assert.equal(writes.length, 0)
|
|
|
|
const fields = { address: "192.0.2.5", interface: "ether1", "mac-address": "02:00:00:00:00:AB", published: false, disabled: false }
|
|
const stale = await prepare("mm_ip_arp_create_plan", { fields })
|
|
await approvePlan(stale.planId, actor, true)
|
|
const foreign = { ...staticFlags, ".id": "*AF", address: fields.address, interface: fields.interface, "mac-address": "02:00:00:00:00:03" }
|
|
arpRows.push(foreign)
|
|
try {
|
|
assert.equal((await dispatch(stale.planId)).state, "rejected")
|
|
assert.equal(writes.length, 0)
|
|
assert.deepEqual(arpRows, [...original, foreign])
|
|
} finally {
|
|
arpRows.splice(arpRows.indexOf(foreign), 1)
|
|
}
|
|
|
|
await run("mm_ip_arp_create_plan", { fields })
|
|
const created = arpRows.find(row => row[".id"] === nativeId)
|
|
assert.deepEqual(created, { ...staticFlags, ".id": nativeId, address: fields.address, interface: fields.interface, "mac-address": "02:00:00:00:00:ab" })
|
|
|
|
const updated = await run("mm_ip_arp_update_plan", { id: nativeId, fields: { "mac-address": "02:00:00:00:00:BC", published: true } })
|
|
assert.equal(created?.["mac-address"], "02:00:00:00:00:bc")
|
|
assert.equal(created?.published, "true")
|
|
const inverse = await invokeMcpTool(principal, "mm_operation_recovery_plan", { operationId: updated.id }) as { planId: string }
|
|
await apply(inverse.planId)
|
|
assert.equal(created?.["mac-address"], "02:00:00:00:00:ab")
|
|
assert.equal(created?.published, "false")
|
|
await run("mm_ip_arp_delete_plan", { id: nativeId })
|
|
assert.deepEqual(arpRows, original)
|
|
assert.deepEqual(writes, [
|
|
{ method: "PUT", path: arpPath, fields: { ...fields, "mac-address": "02:00:00:00:00:ab", published: "false", disabled: "false" } },
|
|
{ method: "PATCH", path: `${arpPath}/${nativeId}`, fields: { "mac-address": "02:00:00:00:00:bc", published: "true" } },
|
|
{ method: "PATCH", path: `${arpPath}/${nativeId}`, fields: { "mac-address": "02:00:00:00:00:ab", published: "false" } },
|
|
{ method: "DELETE", path: `${arpPath}/${nativeId}`, fields: {} },
|
|
])
|
|
console.log("✓ ARP SQL/HTTP: verified static create/update/inverse/delete, normalized MAC, protected dynamic/DHCP records and post-approval address drift")
|
|
} finally {
|
|
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
|
|
if (serverId !== undefined) await pool.query("DELETE FROM servers WHERE id=$1", [serverId])
|
|
router.closeAllConnections()
|
|
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
|
}
|
|
}
|