Files
MikrotikManager/backend/src/modules/mcp/control-path-context-acceptance.ts
T

145 lines
13 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 { PARTITION_WRITER_ADVISORY_KEY } from "../../services/partition-write-transaction.js"
import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js"
import { invokeMcpTool } from "./runtime.js"
import { requireRecentPath } from "./path-verification.js"
import { readRouteCommunityContext } from "./routing-community-context.js"
/** Disposable SQL and loopback HTTP only; no CHR or native mutations. */
export async function verifyMcpControlPathContext(actor: AuthUser) {
const sid = 134
let requests = 0, bgpReads = 0, probes = 0, writes = 0, counter = 0, bgpPresent = false, listMember = false
let packetLoss = "0"
let opaque = "NEVER_CONTROL_PATH_NATIVE", afterTrace: (() => Promise<unknown>) | undefined, afterRead: (() => Promise<unknown>) | undefined
const body = compileManagedFilterRules([{ community: "65000:21", gateway: "192.0.2.1", outIface: "", action: "route", description: "" }])
const collections = (path: string): Record<string, unknown>[] => ({
"/routing/table": ["main", "diag", "policy-only"].map((name, index) => ({ ".id": "*t" + index, name, fib: "true", dynamic: name === "diag" ? "true" : "false" })),
"/ip/vrf": [{ ".id": "*vd", name: "diag", interfaces: listMember ? "WAN-LIST" : "wan", disabled: "false" }, { ".id": "*vm", name: "main", interfaces: "all", disabled: "false" }],
"/interface": ["wan", "hop", "target"].map((name, index) => ({ ".id": "*if" + index, name, disabled: "false", running: "true", "rx-byte": String(++counter), opaque })),
"/ip/address": ["wan", "hop", "target"].map((iface, index) => ({ ".id": "*a" + index, interface: iface, address: "192.0.2." + (index + 1) + "/32", disabled: "false", invalid: "false" })),
"/routing/bgp/connection": [{ ".id": "*c", name: "peer", instance: "default", vrf: "main", "routing-table": "policy-only", afi: "ip", "input.filter": "bgp-in", "output.filter-chain": "", templates: "", disabled: "false" }],
"/routing/bgp/template": [], "/routing/bgp/instance": [{ ".id": "*i", name: "default", vrf: "main", "routing-table": "main", disabled: "false" }],
"/routing/filter/rule": [{ ".id": "*f", chain: "bgp-in", disabled: "false", comment: managedComment("NEVER_CONTROL_PATH_COMMENT"), rule: body }],
"/ip/route": [{ ".id": "*r", "dst-address": "192.0.2.1/32", "routing-table": "main", disabled: "false", comment: managedComment("recursive") }],
} as Record<string, Record<string, unknown>[]>)[path] ?? []
const native = createServer(async (request, response) => {
requests++; response.setHeader("content-type", "application/json")
const path = (request.url ?? "").replace(/^\/rest/, "")
if (afterRead) { const hook = afterRead; afterRead = undefined; await hook() }
if (path.startsWith("/routing/bgp")) { bgpReads++; if (!bgpPresent) { response.statusCode = 404; response.end("{}"); return } }
if (request.method === "GET") { response.end(JSON.stringify(collections(path))); return }
let raw = ""; for await (const part of request) raw += part
const args = raw ? JSON.parse(raw) : {}
if (request.method === "POST" && path.endsWith("/get")) {
const value = collections(path.slice(0, -4)).find(row => row[".id"] === args[".id"])?.[args["value-name"]]
response.end(JSON.stringify(value === undefined ? [] : { ret: value })); return
}
if (request.method === "POST" && ["/tool/ping", "/tool/traceroute"].includes(path)) {
probes++; assert.equal(args.vrf, "diag"); assert.equal(args.interface, "wan"); assert.equal(args["src-address"], "192.0.2.1")
if (path === "/tool/ping") { assert.equal(args.count, "3"); response.end(JSON.stringify([{ sent: "3", received: "3", "packet-loss": packetLoss, "avg-rtt": "1ms" }])); return }
if (afterTrace) { const hook = afterTrace; afterTrace = undefined; await hook() }
response.end(JSON.stringify(["192.0.2.2", "192.0.2.3"].map(address => ({ address, sent: "1", loss: "0" })))); return
}
writes++; response.statusCode = 405; response.end("{}")
})
await new Promise<void>(resolve => native.listen(0, "127.0.0.1", resolve))
let connectionId: string | undefined
try {
assert.equal((await pool.query("SELECT count(*)::int AS count FROM servers WHERE id=$1", [sid])).rows[0].count, 0)
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES($1,'control-path-context','127.0.0.1',$2,false,'NEVER_CONTROL_PATH_LOGIN')", [sid, (native.address() as { port: number }).port])
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Control path purpose", mode: "observer", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:read"], scope: { serverIds: [sid], operationIds: ["routing.path.verify"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), actor)
connectionId = access.connection.id
const principal = await authenticateMcpToken(access.token)
const profile = routeAiProfileSchema.parse({ name: "diagnostic is not Community forwarding", serverId: sid, family: "ipv4", community: "65000:21", table: "policy-only", probeVrf: "diag", bgpContext: { connectionId: "*c", instance: "default", inputChain: "bgp-in", vrf: "main" }, candidates: [{ id: "a", jumpHostId: sid, exitNodeId: sid, wanInterface: "wan", downstreamInterface: "hop", gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r" }, controlProbe: { sourceAddress: "192.0.2.1", targetInterface: "target", targetAddress: "192.0.2.3", expectedHops: [{ serverId: sid, interface: "hop", address: "192.0.2.2" }, { serverId: sid, interface: "target", address: "192.0.2.3" }] } }] })
const check = () => invokeMcpTool(principal, "mm_route_path_verify", { profile, candidateId: "a", proofPurpose: "control-path" }) as Promise<{ id: string; status: string; reason?: string; proofPurpose: string; proofVersion: number; proofScope: string; returnPathVerified: boolean }>
const passed = await check()
assert.equal(passed.status, "passed"); assert.equal(passed.proofPurpose, "control-path"); assert.equal(passed.proofVersion, 2)
assert.equal(passed.proofScope, "observed-control-probes-only"); assert.equal(passed.returnPathVerified, false); assert.equal(bgpReads, 0); assert.equal(probes, 2)
const blocker = await pool.connect()
let pending: ReturnType<typeof check> | undefined
try {
await blocker.query("BEGIN")
await blocker.query("SELECT pg_advisory_xact_lock($1::bigint)", [PARTITION_WRITER_ADVISORY_KEY])
pending = check()
void pending.catch(() => {})
const deadline = Date.now() + 2500
let waiting = false
while (Date.now() < deadline) {
const { rows } = await blocker.query("SELECT 1 FROM pg_locks WHERE locktype='advisory' AND database=(SELECT oid FROM pg_database WHERE datname=current_database()) AND classid=0 AND objid=$1::oid AND objsubid=1 AND mode='ShareLock' AND NOT granted", [PARTITION_WRITER_ADVISORY_KEY])
if (rows.length) { waiting = true; break }
await new Promise(resolve => setTimeout(resolve, 20))
}
assert(waiting, "path proof publication must wait for the partition writer lock")
const { rows: [before] } = await blocker.query("SELECT count(*)::int AS count FROM mcp_path_checks WHERE connection_id=$1", [connectionId])
assert.equal(before.count, 1)
} finally {
try { await blocker.query("ROLLBACK") } finally { blocker.release() }
}
assert.equal((await pending)?.status, "passed")
const beforeMalformed = probes
packetLoss = "0NEVER_CONTROL_PATH_LOSS"
const malformed = await check()
packetLoss = "0"
assert.equal(malformed.status, "unknown")
assert.equal(malformed.reason, "PING_COUNTERS_INCONSISTENT")
assert.equal(probes, beforeMalformed + 1, "malformed ping must never reach traceroute")
const [storedMalformed] = (await pool.query("SELECT status,evidence FROM mcp_path_checks WHERE id=$1", [malformed.id])).rows
assert.equal(storedMalformed.status, "unknown")
assert.equal(storedMalformed.evidence.reason, malformed.reason)
assert.equal(typeof storedMalformed.evidence.proof, "string")
assert.ok(!JSON.stringify(storedMalformed.evidence).includes("NEVER_CONTROL_PATH_LOSS"))
const beforeAdopt = requests
await assert.rejects(requireRecentPath(profile, "a", connectionId), (error: { code?: string }) => error.code === "MEASUREMENT_UNKNOWN")
assert.equal(requests, beforeAdopt, "a control receipt is rejected before any native Community acquisition")
const saved = (await pool.query("SELECT evidence FROM mcp_path_checks WHERE id=$1", [passed.id])).rows[0].evidence
await pool.query("UPDATE mcp_path_checks SET evidence=evidence-'proofPurpose'-'proofVersion' WHERE id=$1", [passed.id])
await assert.rejects(requireRecentPath(profile, "a", connectionId), (error: { code?: string }) => error.code === "MEASUREMENT_UNKNOWN")
assert.equal(requests, beforeAdopt, "legacy evidence without a purpose is not upgraded")
await pool.query("UPDATE mcp_path_checks SET evidence=$2::jsonb WHERE id=$1", [passed.id, JSON.stringify({ ...saved, proofPurpose: "community" })])
bgpPresent = true
await assert.rejects(requireRecentPath(profile, "a", connectionId), (error: { code?: string }) => error.code === "MEASUREMENT_UNKNOWN", "relabeling the purpose cannot cross the HMAC domain")
const privateContext = await readRouteCommunityContext(profile)
assert.equal(privateContext.before.scopedExecutionAvailable, true); assert.equal(privateContext.before.executionAvailable, false)
assert.ok(privateContext.ownedTarget); assert.equal(privateContext.ownedTarget.desiredTargetProof(body), privateContext.before.targetRuleProof)
const desiredBody = compileManagedFilterRules([{ community: "65000:21", gateway: "192.0.2.9", outIface: "", action: "route", description: "" }])
const desiredProof = privateContext.ownedTarget.desiredTargetProof(desiredBody)
privateContext.ownedTarget.rawRow.comment = "mutated exposed clone"
assert.equal(privateContext.ownedTarget.desiredTargetProof(desiredBody), desiredProof, "the desired seal uses an immutable original row")
assert.ok(!JSON.stringify(privateContext.before).includes("NEVER_")); assert.ok(!("ownedTarget" in privateContext.before))
await pool.query("UPDATE mcp_path_checks SET evidence=$2::jsonb WHERE id=$1", [passed.id, JSON.stringify(saved)])
bgpPresent = false
const beforeDefault = probes
const defaultPurpose = await invokeMcpTool(principal, "mm_route_path_verify", { profile, candidateId: "a" }) as { status: string; proofPurpose: string }
assert.equal(defaultPurpose.proofPurpose, "community"); assert.equal(defaultPurpose.status, "unknown"); assert.equal(probes, beforeDefault)
listMember = true
assert.equal((await check()).status, "unknown", "an unknown earlier interface list cannot fall through to main/all")
listMember = false
afterTrace = async () => { opaque = "NEVER_CONTROL_PATH_DRIFT" }
assert.equal((await check()).reason, "STATE_CONFLICT")
let finalRequests = 0
afterTrace = async () => { await pool.query("UPDATE servers SET password='NEVER_CONTROL_PATH_ROTATED' WHERE id=$1", [sid]); finalRequests = requests }
assert.equal((await check()).reason, "STATE_CONFLICT"); assert.equal(requests, finalRequests, "source drift is checked before polling a replacement endpoint")
const cancelled = new AbortController(), beforeCancel = requests
afterRead = async () => { cancelled.abort() }
await assert.rejects(invokeMcpTool(principal, "mm_route_path_verify", { profile, candidateId: "a", proofPurpose: "control-path" }, cancelled.signal))
assert.equal(requests, beforeCancel + 1)
afterRead = () => setConnectionStatus(connectionId!, "paused", actor)
const beforeRevoke = requests
await assert.rejects(check()); assert.equal(requests, beforeRevoke + 1)
assert.equal(writes, 0)
assert.ok(!JSON.stringify((await pool.query("SELECT result FROM mcp_requests WHERE connection_id=$1", [connectionId])).rows).includes("NEVER_"))
console.log("✓ Control path context: BGP-absent bounded probes, independent VRF/IP/interface/hops, explicit purpose and HMAC isolation from Community and legacy evidence, scoped private target API, late dependency/source/cancel/revocation fences, return-path unknown, private results and zero writes")
} finally {
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
await pool.query("DELETE FROM servers WHERE id=$1", [sid])
native.closeAllConnections(); await new Promise<void>(resolve => native.close(() => resolve()))
}
}