192 lines
18 KiB
TypeScript
192 lines
18 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createServer } from "node:http"
|
|
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
|
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
|
import { pool } from "../../db/index.js"
|
|
import type { AuthUser } from "../../lib/permissions.js"
|
|
import { managedComment } from "../../managed-markers.js"
|
|
import { compileManagedFilterRules } from "../../services/filter-rules-write-model.js"
|
|
import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js"
|
|
import { invokeMcpTool } from "./runtime.js"
|
|
import { readRouteCommunityContext } from "./routing-community-context.js"
|
|
|
|
/** Disposable SQL/HTTP fixtures only. No RouterOS or production requests. */
|
|
export async function acceptRouteCommunityContextCompatibilityMcp(actor: AuthUser, { legacyOnly = false } = {}) {
|
|
const sid = 139, reserveId = 140
|
|
let disabledInput = "unrelated", disabledOutput = "", disabledNlri = "", disabledSelect = "", inherited = false, missingParent = false, cyclicParent = false
|
|
let disabledFlag: string | undefined = "true", disabledGetter: string | undefined, selectedDisabled = false, currentDisabled = false
|
|
let version = "7.21.1 (stable)", resourceFailure = false, instanceReads = 0, writes = 0, pings = 0, traces = 0, reserveReads = 0
|
|
let fixtureTable = "main"
|
|
let reserveAddressUnavailable = false, reserveCatalogMalformed = false, reserveJsonMalformed = false, reserveStatus = 200, mutateReserveSource = false, disabledOpaque = "baseline"
|
|
const body = compileManagedFilterRules([{ community: "65000:10", action: "route", gateway: "192.0.2.1", outIface: "", description: "" }])
|
|
const selected = () => ({ ".id": "*c", name: "selected", disabled: String(selectedDisabled), instance: "default", vrf: "main", "routing-table": "main", afi: "ip", "input.filter": "bgp-in", "output.filter-chain": "", templates: "" })
|
|
const rows = (path: string, reserve: boolean): Record<string, unknown>[] => ({
|
|
"/routing/table": [{ ".id": "*t", name: "main", fib: "true" }, { ".id": "*t2", name: "tenant", fib: "true" }],
|
|
"/ip/vrf": [{ ".id": "*v2", name: "tenant", interfaces: fixtureTable === "tenant" ? "wan,reserve-wan" : "none", disabled: "false" }, { ".id": "*v", name: "main", interfaces: "all", disabled: "false" }],
|
|
"/routing/bgp/connection": [selected(), { ".id": "*d", name: "disabled-unrelated", ...(disabledFlag === undefined ? {} : { disabled: disabledFlag }), instance: "deleted-instance", opaque: disabledOpaque, templates: inherited ? "parent" : "", ...(!inherited ? { "input.filter": disabledInput, "output.filter-chain": disabledOutput, "input.filter-nlri": disabledNlri, "output.filter-select": disabledSelect } : {}) }],
|
|
"/routing/bgp/template": inherited && !missingParent ? [{ ".id": "*p", name: "parent", disabled: "false", templates: cyclicParent ? "parent" : "", "input.filter": disabledInput, "output.filter-chain": disabledOutput, "input.filter-nlri": disabledNlri, "output.filter-select": disabledSelect }] : [],
|
|
"/routing/bgp/instance": [{ ".id": "*i", name: "default", disabled: "false", vrf: "main", "routing-table": "main" }],
|
|
"/routing/filter/rule": [{ ".id": "*f", chain: "bgp-in", disabled: "false", comment: managedComment("compatibility"), rule: body }],
|
|
"/ip/route": [1, 2].map(index => ({ ".id": "*r" + index, "dst-address": "192.0.2." + index + "/32", "routing-table": fixtureTable, disabled: String(index === 1 && currentDisabled), comment: managedComment("recursive") })),
|
|
"/interface": ["wan", "hop", "target", "reserve-wan"].map((name, index) => ({ ".id": "*if" + index, name, disabled: "false" })),
|
|
"/ip/address": reserve && reserveAddressUnavailable ? [] : ["wan", "hop", "target", "reserve-wan"].map((name, index) => ({ ".id": "*a" + index, interface: name, address: (reserve ? "198.51.100." : "192.0.2.") + (index + 1) + "/32", disabled: "false" })),
|
|
} as Record<string, Record<string, unknown>[]>)[path] ?? []
|
|
const router = createServer(async (req, res) => {
|
|
res.setHeader("content-type", "application/json")
|
|
const reserve = req.headers.authorization === "Basic " + Buffer.from("reserve:fixture").toString("base64")
|
|
if (reserve) reserveReads++
|
|
let raw = ""; for await (const chunk of req) raw += chunk
|
|
const args = raw ? JSON.parse(raw) : {}, path = (req.url ?? "").replace(/^\/rest/, "")
|
|
if (reserve && reserveStatus !== 200) { res.statusCode = reserveStatus; res.end("NEVER_RESERVE_AUTH_PROVIDER_BODY"); return }
|
|
if (reserve && reserveJsonMalformed) { res.end("{NEVER_RESERVE_MALFORMED_JSON"); return }
|
|
if (mutateReserveSource && reserve) { mutateReserveSource = false; await pool.query("UPDATE servers SET password='changed-fixture' WHERE id=$1", [reserveId]) }
|
|
if (path === "/system/resource") { if (resourceFailure) res.statusCode = 404; res.end(JSON.stringify(resourceFailure ? { message: "unavailable" } : { version })); return }
|
|
if (path === "/routing/bgp/instance") instanceReads++
|
|
if (req.method === "GET") { res.end(JSON.stringify(reserve && reserveCatalogMalformed ? { unexpected: "catalog" } : rows(path, reserve))); return }
|
|
if (req.method === "POST" && path.endsWith("/get")) {
|
|
const row = rows(path.slice(0, -4), reserve).find(row => row[".id"] === args[".id"])
|
|
const value = args[".id"] === "*d" && args["value-name"] === "disabled" && disabledFlag === undefined ? disabledGetter : row?.[args["value-name"]]
|
|
res.end(JSON.stringify(value === undefined ? [] : { ret: value })); return
|
|
}
|
|
if (req.method === "POST" && path === "/tool/ping") { pings++; res.end(JSON.stringify([{ sent: "3", received: "3", "packet-loss": "0", "avg-rtt": "1ms" }])); return }
|
|
if (req.method === "POST" && path === "/tool/traceroute") { traces++; res.end(JSON.stringify(["192.0.2.2", "192.0.2.3"].map(address => ({ address, sent: "1", loss: "0" })))); return }
|
|
writes++; res.statusCode = 405; res.end("{}")
|
|
})
|
|
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
|
let connectionId: string | undefined
|
|
try {
|
|
const port = (router.address() as { port: number }).port
|
|
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,username,password) VALUES($1,'context-compatibility','127.0.0.1',$3,false,'primary','fixture'),($2,'context-reserve','127.0.0.1',$3,false,'reserve','fixture')", [sid, reserveId, port])
|
|
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Context compatibility", mode: "observer", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:read"], scope: { serverIds: [sid, reserveId], operationIds: ["routing.analyze", "routing.path.verify"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), actor)
|
|
connectionId = access.connection.id
|
|
const principal = await authenticateMcpToken(access.token)
|
|
const primary = { id: "a", jumpHostId: sid, exitNodeId: sid, wanInterface: "wan", downstreamInterface: "hop", gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r1" }, controlProbe: { targetInterface: "target", expectedHops: [{ serverId: sid, interface: "hop" }, { serverId: sid, interface: "target" }] } }
|
|
const base = routeAiProfileSchema.parse({ name: "compatibility", serverId: sid, community: "65000:10", family: "ipv4", candidates: [primary, { ...primary, id: "b", jumpHostId: reserveId, exitNodeId: reserveId, wanInterface: "reserve-wan", gateway: "192.0.2.2", gatewayRef: { resource: "ipv4_route", id: "*r2" }, controlProbe: { targetInterface: "target", expectedHops: [{ serverId: reserveId, interface: "hop" }, { serverId: reserveId, interface: "target" }] } }] })
|
|
const read = (selectedCandidateId?: string) => readRouteCommunityContext(base, { selectedCandidateId })
|
|
if (legacyOnly) {
|
|
version = "7.19.3 (stable)"
|
|
const writer = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Legacy BGP writer", mode: "approval",
|
|
expiresAt: new Date(Date.now() + 600000).toISOString(), permissions: ["mm:network:write", "mm:network:read", "mm:filters:write"],
|
|
scope: { serverIds: [sid, reserveId], operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify", "routing.profiles.save"], allowGlobal: false },
|
|
}), actor)
|
|
try {
|
|
const writerPrincipal = await authenticateMcpToken(writer.token)
|
|
const analysis = await invokeMcpTool(writerPrincipal, "mm_route_optimizer_analyze", { profile: base }) as {
|
|
executionAvailable: boolean; executionReason: string
|
|
}
|
|
assert.equal(analysis.executionAvailable, false)
|
|
assert.equal(analysis.executionReason, "LEGACY_BGP_READ_ONLY")
|
|
const nativeBefore = { pings, traces, writes, instanceReads }
|
|
await assert.rejects(invokeMcpTool(writerPrincipal, "mm_route_optimizer_plan", { profile: base, candidateId: "b" }),
|
|
{ code: "UNSUPPORTED_CAPABILITY", message: "LEGACY_BGP_READ_ONLY" })
|
|
const enableController = (profile: typeof base) => invokeMcpTool(writerPrincipal, "mm_route_profile_save_plan",
|
|
{ profile, enabled: true, expiresAt: new Date(Date.now() + 300000).toISOString() })
|
|
const legacyRefusal = { code: "UNSUPPORTED_CAPABILITY", message: "LEGACY_BGP_READ_ONLY" }
|
|
await assert.rejects(enableController(base), legacyRefusal)
|
|
const scoped = routeAiProfileSchema.parse({ ...base, table: "tenant", probeVrf: "tenant",
|
|
bgpContext: { connectionId: "*c", instance: "default", inputChain: "bgp-in", vrf: "tenant" },
|
|
candidates: base.candidates.map(candidate => ({ ...candidate, gateway: candidate.gateway + "@tenant",
|
|
controlProbe: { ...candidate.controlProbe, sourceAddress: candidate.id === "a" ? "192.0.2.1" : "192.0.2.4" } })) })
|
|
fixtureTable = "tenant"
|
|
await assert.rejects(invokeMcpTool(writerPrincipal, "mm_route_optimizer_plan", { profile: scoped, candidateId: "b" }),
|
|
{ code: "UNSUPPORTED_CAPABILITY", message: "LEGACY_BGP_READ_ONLY" })
|
|
await assert.rejects(enableController(scoped), legacyRefusal)
|
|
assert.deepEqual({ pings, traces, writes, instanceReads }, nativeBefore)
|
|
for (const table of ["mcp_plans", "mcp_operations"] as const) {
|
|
assert.equal((await pool.query(`SELECT 1 FROM ${table} WHERE connection_id=$1`, [writer.connection.id])).rowCount, 0)
|
|
}
|
|
console.log("Legacy BGP MCP: analysis works and the write-enabled planner refuses before plan, probe or native write")
|
|
} finally { await setConnectionStatus(writer.connection.id, "paused", actor) }
|
|
return
|
|
}
|
|
const initial = await read("a")
|
|
assert.equal(initial.before.executionAvailable, true); assert.equal(initial.before.currentCandidateId, "a")
|
|
assert.deepEqual(initial.before.disabledConnectionIds, ["*d"])
|
|
assert.ok(initial.before.candidateDiagnostics.every(row => row.status === "available"))
|
|
disabledOpaque = "drift"
|
|
assert.notEqual((await read()).before.dependencyProof, initial.before.dependencyProof, "ignored disabled rows remain sealed dependencies")
|
|
disabledOpaque = "baseline"; disabledInput = "bgp-in"
|
|
assert.equal((await read()).before.executionAvailable, false, "disabled peer input reference prevents a private write")
|
|
disabledInput = "unrelated"; disabledOutput = "bgp-in"
|
|
assert.equal((await read()).before.executionAvailable, false, "disabled peer output reference prevents a private write")
|
|
disabledOutput = ""; disabledNlri = "bgp-in"
|
|
assert.equal((await read()).before.executionAvailable, false, "disabled peer NLRI reference prevents a private write")
|
|
disabledNlri = ""; disabledSelect = "bgp-in"
|
|
assert.equal((await read()).before.executionAvailable, false, "disabled peer select reference prevents a private write")
|
|
disabledSelect = ""; inherited = true
|
|
assert.equal((await read()).before.executionAvailable, true)
|
|
disabledInput = "bgp-in"
|
|
assert.equal((await read()).before.executionAvailable, false, "inherited dormant input chain remains shared")
|
|
disabledInput = "unrelated"; disabledOutput = "bgp-in"
|
|
assert.equal((await read()).before.executionAvailable, false, "inherited dormant output chain remains shared")
|
|
disabledOutput = ""; missingParent = true
|
|
await assert.rejects(read(), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE")
|
|
missingParent = false; cyclicParent = true
|
|
await assert.rejects(read(), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE")
|
|
cyclicParent = false; inherited = false; disabledFlag = undefined
|
|
await assert.rejects(read(), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE", "unknown disabled is never skipped")
|
|
disabledGetter = "true"
|
|
assert.equal((await read()).before.executionAvailable, true, "omitted disabled requires a positively observed effective true")
|
|
disabledGetter = undefined
|
|
disabledFlag = "true"; selectedDisabled = true
|
|
assert.equal((await read()).before.contextVerified, false, "disabled selected binding cannot verify context")
|
|
selectedDisabled = false; reserveAddressUnavailable = true
|
|
const unavailable = await read("a")
|
|
assert.equal(unavailable.before.executionAvailable, true)
|
|
assert.equal(unavailable.before.currentCandidateId, "a")
|
|
assert.equal(unavailable.before.candidateDiagnostics[1].status, "candidate-unavailable")
|
|
assert.equal(unavailable.probeEndpoints.has("b"), false)
|
|
await assert.rejects(read("b"), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE")
|
|
const failedProbe = await invokeMcpTool(principal, "mm_route_path_verify", { profile: base, candidateId: "b" }) as { status: string }
|
|
assert.equal(failedProbe.status, "unknown"); assert.equal(pings, 0, "unavailable candidate cannot send probes")
|
|
const primaryProbe = await invokeMcpTool(principal, "mm_route_path_verify", { profile: base, candidateId: "a" }) as { status: string }
|
|
assert.equal(primaryProbe.status, "passed")
|
|
reserveAddressUnavailable = false; currentDisabled = true
|
|
const away = await read("b")
|
|
assert.equal(away.before.currentCandidateId, "a", "configured failed path identity survives readiness loss")
|
|
assert.equal(away.before.executionAvailable, true); assert.equal(away.before.candidateDiagnostics[0].status, "candidate-unavailable")
|
|
currentDisabled = false
|
|
await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [reserveId])
|
|
const beforeDisabledReads = reserveReads, disabledSource = await read("a")
|
|
assert.equal(disabledSource.before.candidateDiagnostics[1].status, "candidate-unavailable"); assert.equal(reserveReads, beforeDisabledReads)
|
|
await assert.rejects(read("b"))
|
|
await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [reserveId])
|
|
await assert.rejects(disabledSource.fence(), (error: { code?: string }) => error.code === "STATE_CONFLICT", "unavailable source epoch is fenced")
|
|
reserveCatalogMalformed = true
|
|
await assert.rejects(read("a"), (error: { code?: string }) => error.code === "INVALID_NATIVE_RESPONSE", "malformed catalog is not silently skipped")
|
|
reserveCatalogMalformed = false
|
|
const beforeInvalidPings = pings
|
|
for (const status of [401, 403]) {
|
|
reserveStatus = status
|
|
await assert.rejects(read("a"), (error: Error & { code?: string }) => error.code === "SOURCE_AUTH_FAILED" && !error.message.includes("NEVER_"), "reserve authentication failure invalidates the entire context")
|
|
const probe = await invokeMcpTool(principal, "mm_route_path_verify", { profile: base, candidateId: "a" }) as { status: string; reason: string }
|
|
assert.equal(probe.status, "unknown"); assert.equal(probe.reason, "SOURCE_AUTH_FAILED")
|
|
}
|
|
reserveStatus = 200; reserveJsonMalformed = true
|
|
await assert.rejects(read("a"), (error: Error & { code?: string }) => error.code === "INVALID_NATIVE_RESPONSE" && !error.message.includes("NEVER_"), "malformed reserve JSON invalidates the entire context")
|
|
const malformedProbe = await invokeMcpTool(principal, "mm_route_path_verify", { profile: base, candidateId: "a" }) as { status: string; reason: string }
|
|
assert.equal(malformedProbe.status, "unknown"); assert.equal(malformedProbe.reason, "INVALID_NATIVE_RESPONSE")
|
|
assert.equal(pings, beforeInvalidPings, "fatal reserve source failures cannot send even primary probes")
|
|
reserveJsonMalformed = false; mutateReserveSource = true
|
|
await assert.rejects(read("a"), (error: { code?: string }) => error.code === "STATE_CONFLICT", "late source drift remains fatal")
|
|
await pool.query("UPDATE servers SET password='fixture' WHERE id=$1", [reserveId])
|
|
version = "7.19.3 (stable)"; const beforeLegacyInstanceReads = instanceReads
|
|
const legacy = await read("a")
|
|
assert.equal(legacy.before.bgpContextMode, "legacy-read-only"); assert.equal(legacy.before.contextVerified, true)
|
|
assert.equal(legacy.before.instance, null); assert.equal(legacy.before.executionReason, "LEGACY_BGP_READ_ONLY")
|
|
assert.equal(legacy.before.scopedExecutionAvailable, false); assert.equal(instanceReads, beforeLegacyInstanceReads)
|
|
const named = routeAiProfileSchema.parse({ ...base, bgpContext: { connectionId: "*c", instance: "default", inputChain: "bgp-in" } })
|
|
assert.equal((await readRouteCommunityContext(named)).before.contextVerified, false, "legacy never invents the requested named instance")
|
|
version = "unknown"
|
|
assert.equal((await read()).before.bgpContextMode, "explicit-instance", "unknown version requires a proven actual instance graph")
|
|
resourceFailure = true
|
|
await assert.rejects(read(), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE", "404 never detects legacy")
|
|
assert.equal(writes, 0)
|
|
console.log("✓ Route context compatibility: disabled unrelated BGP references/inheritance/raw seals, per-candidate readiness with current identity, unavailable endpoint fencing/no probes, selected-candidate requirement, source drift/malformed catalog rejection, positively detected legacy read-only mode without invented instances or writes")
|
|
} finally {
|
|
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
|
|
await pool.query("DELETE FROM servers WHERE id=ANY($1::bigint[])", [[sid, reserveId]])
|
|
router.closeAllConnections(); await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
|
}
|
|
}
|