import assert from "node:assert/strict" import http from "node:http" import { randomUUID } from "node:crypto" import { basename, dirname, resolve } from "node:path" // Guard before imports which configure the database, authority or private keys. assert.equal(process.env.MMAPP_OWN_ROUTING_NETWORK_NATIVE, "true") const url = new URL(process.env.DATABASE_URL ?? "") assert.equal(url.hostname, "127.0.0.1"); assert.equal(url.pathname, "/postgres") assert(["postgres:", "postgresql:"].includes(url.protocol)) assert(process.env.MCP_STATE_DIR && basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-")) const { pool, closePool } = await import("../../db/index.js") const { applySqlMigrations } = await import("../../db/migrate.js") const { managedComment } = await import("../../managed-markers.js") const { installLoopbackFixtureAgent } = await import("../../test/loopback-http-agent.js") const { mcpConnectionPolicySchema } = await import("@mmapp/contracts/mcp") const { routeAiProfileSchema } = await import("@mmapp/contracts/mcp-routing") const security = await import("./security.js") const { effectiveMcpConnection, authenticateMcpToken } = await import("./store.js") const { invokeMcpTool } = await import("./runtime.js") const { createRoutingSourceContext, readRoutingEndpoints } = await import("./routing-observation-source.js") const { resolveRoutingProfileAuthority } = await import("./routing-profile-authority.js") await import("./actions.js") const { findMcpOperation } = await import("./registry.js") const { createRoutingNetworkNativeSession } = await import("./routing-network-native-session.js") const { captureRoutingNetworkNativeParser } = await import("./routing-network-native-parser.js") const { captureRoutingNetworkObservationAssembly } = await import("./routing-network-observation-assembly.js") const { readRoutingNetworkScopedCommunityContext } = await import("./routing-network-scoped-context.js") type Options = Parameters[0] type Mode = "topology-unknown" | "normal" | "zero-ping" | "redirect" | "auth" | "malformed" | "oversized" | "rows" | "total-bytes" | "total-rows" let mode: Mode = "normal", onRequest: (() => Promise | void) | undefined let logRows: Record[] = [] const requests: { method: string; path: string; body: Record }[] = [] let responseBytes = 0, writes = 0, sinks = 0 const profiles: string[] = [], connections: string[] = [] let serverId: number | undefined const addressRows = [ { ".id": "*a1", interface: "wan1", address: "198.51.100.1/24", disabled: "false", invalid: "false", dynamic: "false" }, { ".id": "*a2", interface: "exit1", address: "203.0.113.9/24", disabled: "false", invalid: "false", dynamic: "false" }, ] const collections = (path: string): Record[] => { if (path === "/system/resource") return [{ version: "7.26", uptime: "1d", "board-name": "CHR" }] if (path === "/interface") return ["wan1", "exit1"].map((name, i) => ({ ".id": "*i" + i, name, type: "ether", disabled: "false", running: "true" })) if (path === "/ip/address") return addressRows if (path === "/ipv6/address") return [] if (path === "/ip/vrf") return [{ ".id": "*v1", name: "probe", interfaces: "wan1", disabled: "false" }, { ".id": "*v2", name: "main", interfaces: "all", disabled: "false" }] if (path === "/routing/route") return [{ ".id": "*r1", afi: "ip", "dst-address": "203.0.113.0/24", "routing-table": "tenant", gateway: "192.0.2.1@main", "immediate-gw": "192.0.2.1%wan1", active: "true", dynamic: "true", contribution: "active", bgp: "true", "bgp.session": "*s1" }] if (path === "/routing/bgp/connection") return [{ ".id": "*c1", name: "peer1", instance: "default", "remote.address": "192.0.2.1", "local.address": "192.0.2.2", "remote.as": "65001", afi: "ip", templates: "", vrf: "main", "routing-table": "tenant", disabled: "false" }] if (path === "/routing/bgp/session") return [{ ".id": "*s1", name: "peer1-1", instance: "default", "remote.address": "192.0.2.1@main", "local.address": "192.0.2.2@main", "remote.as": "65001", "local.afi": "ip", "remote.afi": "ip", established: "true", "routing-table": "tenant" }] if (path === "/routing/bfd/session") return [{ ".id": "*b1", "local-address": "192.0.2.2", "remote-address": "192.0.2.1", interface: "wan1", vrf: "main", state: "up" }] if (path === "/log") return logRows if (path === "/routing/table") return ["main", "tenant", "probe"].map((name, i) => ({ ".id": "*t" + i, name, fib: "true" })) if (path === "/routing/bgp/instance") return [{ ".id": "*i1", name: "default", vrf: "main", "routing-table": "main", disabled: "false" }] if (["/routing/bgp/template", "/routing/filter/rule", "/interface/gre", "/ipv6/route"].includes(path)) return [] if (["/routing/ospf/instance", "/routing/rip/instance", "/routing/isis/instance", "/routing/filter/select-rule", "/routing/bgp/vpn", "/routing/rule", "/ip/firewall/mangle", "/ipv6/firewall/mangle"].includes(path)) return [] if (path === "/ip/route") return [1, 2].map(i => ({ ".id": "*r" + i, "dst-address": "192.0.2." + i + "/32", "routing-table": "main", gateway: "198.51.100.254", disabled: "false", comment: managedComment("owned-read-fixture") })) throw Error("Unapproved fixture path") } const router = http.createServer(async (req, res) => { try { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(Buffer.from(chunk)) const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record : {} const url = new URL(req.url!, "http://127.0.0.1") const path = url.pathname.replace(/^\/rest/, "") if (path === "/log") assert.deepEqual([...url.searchParams], [["buffer", "memory"], [".proplist", ".id,buffer,time,topics,message"]]) requests.push({ method: req.method!, path, body }) assert.equal(req.headers.authorization, "Basic " + Buffer.from("fixture:inert-only").toString("base64")) const callback = onRequest; onRequest = undefined; await callback?.() if (path === "/sink") { sinks++; res.end("[]"); return } if (mode === "redirect") { res.writeHead(302, { Location: "/rest/sink" }); res.end(); return } if (mode === "auth") { res.writeHead(401); res.end("fixture denied"); return } if (mode === "malformed") { res.end("["); return } if (mode === "oversized") { res.setHeader("Content-Type", "application/json"); res.write('[{"version":"7.26","padding":"'); res.end("路".repeat(400000) + '"}]'); return } let payload: unknown if (req.method === "GET") payload = collections(path) else if (req.method === "POST" && path.endsWith("/get")) { const field = body["value-name"] payload = { ret: field === "disabled" ? "false" : field === "instance" ? "default" : field === "vrf" ? "main" : field === "routing-table" ? (path === "/routing/bgp/instance/get" ? "main" : "tenant") : field === "afi" ? "ip" : "" } } else if (req.method === "POST" && path === "/tool/ping") { assert.equal(body.address, "203.0.113.9"); assert.equal(body["src-address"], "198.51.100.1"); assert.equal(body.interface, "wan1"); assert.equal(body.vrf, "probe"); assert.equal(body.count, "3") payload = mode === "zero-ping" ? [{ sent: "3", received: "0", "packet-loss": "100%" }] : [{ sent: "3", received: "3", "packet-loss": "0%", "avg-rtt": "1ms" }] } else if (req.method === "POST" && path === "/tool/traceroute") { assert.equal(body.address, "203.0.113.9"); assert.equal(body.interface, "wan1"); assert.equal(body.vrf, "probe"); assert.equal(body["max-hops"], "16") payload = [{ ".section": "0", address: "203.0.113.9", sent: "3", loss: "0", last: "1ms" }] } else { writes++; throw Error("Unexpected native mutation") } if (mode === "topology-unknown" && path === "/routing/route") payload = [{ ...collections(path)[0], "immediate-gw": "17", "bgp.peer-cache-id": "*s1" }] if (mode === "rows") payload = Array.from({ length: 1001 }, () => ({ version: "7.26" })) if (mode === "total-rows" && path !== "/system/resource") payload = Array.from({ length: 1000 }, () => ({ value: "fixture" })) if (mode === "total-bytes") payload = [{ version: "7.26", padding: "x".repeat(600000) }] const encoded = JSON.stringify(payload); responseBytes += Buffer.byteLength(encoded) res.setHeader("Content-Type", "application/json"); res.end(encoded) } catch { if (!res.headersSent) res.writeHead(500); res.end("fixture failed") } }) await new Promise(done => router.listen(0, "127.0.0.1", done)) const bound = router.address(); assert(bound && typeof bound === "object") const restoreAgent = installLoopbackFixtureAgent(router) const cases: string[] = [] const run = async (name: string, work: () => Promise) => { mode = "normal"; logRows = []; onRequest = undefined; await work(); cases.push(name) } async function source(withProbes = true) { assert(serverId) const connectionId = randomUUID(), credentialId = randomUUID(), profileId = randomUUID(), ownerId = "native-reader-" + randomUUID() const now = Date.now(), expiresAt = new Date(now + 600000).toISOString(), generation = await security.accessGeneration() const permissions = ["mm:network:read", "mm:network:write", "mm:filters:write"] const policy = mcpConnectionPolicySchema.parse({ id: connectionId, version: 1, status: "active", mode: "approval", permissions, expiresAt, scope: { serverIds: [serverId], operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify", "operations.recover"], allowGlobal: false }, limits: { callsPerMinute: 1000, mutationsPerHour: 10, concurrentReads: 4, serversPerPlan: 2, objectsPerPlan: 20 } }) await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'owned native reader',$2,$3::jsonb,$4::jsonb,$5,$6,$7)", [connectionId, ownerId, JSON.stringify(permissions), JSON.stringify(policy), generation, expiresAt, new Date(now - 1000)]) connections.push(connectionId) await pool.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [credentialId, connectionId, randomUUID(), expiresAt]) const profile = routeAiProfileSchema.parse({ name: "Owned native reader", serverId, community: "65000:10", family: "ipv4", table: "tenant", probeVrf: "probe", autoRecovery: true, candidates: ["a", "b"].map((id, i) => ({ id, jumpHostId: serverId!, exitNodeId: serverId!, wanInterface: "wan1", downstreamInterface: "exit1", gateway: "192.0.2." + (i + 1), gatewayRef: { resource: "ipv4_route", id: "*r" + (i + 1) }, controlProbe: { targetInterface: "exit1", targetAddress: "203.0.113.9", sourceAddress: "198.51.100.1", expectedHops: [{ serverId: serverId!, interface: "exit1", address: "203.0.113.9" }] } })) }) await pool.query("INSERT INTO mcp_routing_profiles(id,connection_id,config,enabled,grant_expires_at,credential_id,generation,policy_version) VALUES($1,$2,$3::jsonb,true,$4,$5,$6,1)", [profileId, connectionId, JSON.stringify(profile), expiresAt, credentialId, generation]) profiles.push(profileId) const principal = { connectionId, credentialId, credentialExpiresAt: expiresAt } const contextSources = (await createRoutingSourceContext(await readRoutingEndpoints([serverId]))).expected const authority = await resolveRoutingProfileAuthority({ profileId, expectedVersion: 1, profile, principal, ownerId, transport: { contextSources } }) const input: Record = { serverId, profile, principal, ownerId, candidateId: "b", originalCandidateId: "a", persistentProfileAuthority: authority, contextSources, policyProof: security.fingerprint(policy), connectionGeneration: generation, generation, receiptId: randomUUID(), proofRevision: 3, nativeId: "*r1", dependencyProof: "d".repeat(64), originalTargetProof: "a".repeat(64), desiredTargetProof: "b".repeat(64), originalRuleCiphertext: await security.encryptSecret("synthetic source data only"), desiredRuleCiphertext: await security.encryptSecret("synthetic desired data only"), rules: [{ community: profile.community, gateway: "192.0.2.2" }], beforeRules: [{ community: profile.community, gateway: "192.0.2.1" }] } input.requestProof = await security.privateSecretFingerprint(security.fingerprint(input), "route-ai-scoped-request-v3") const evidence = { target: { scope: "servers", serverIds: [serverId] }, objects: [], snapshots: [], before: input.beforeRules, steps: [{ kind: "service", service: "routing.community.scoped", input }], warnings: [], requiresHuman: true, mutationCost: 2 } const planId = randomUUID(), operationId = randomUUID() await pool.query("INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at,approved_by,approved_at) VALUES($1,$2,'routing.community.switch',$3,1,$4,$5::jsonb,$6::jsonb,'executing',$7,$8,now())", [planId, connectionId, findMcpOperation("routing.community.switch")!.version, generation, JSON.stringify({ sealed: await security.encryptSecret("{}") }), JSON.stringify({ sealed: await security.encryptSecret(JSON.stringify(evidence)) }), expiresAt, ownerId]) await pool.query("INSERT INTO mcp_operations(id,plan_id,connection_id,idempotency_key,state) VALUES($1,$2,$3,$4,'running')", [operationId, planId, connectionId, randomUUID()]) await pool.query("INSERT INTO mcp_operation_steps(operation_id,step_index,state,intended_state) VALUES($1,0,'intent',$2::jsonb)", [operationId, JSON.stringify(security.redact({ kind: "service", service: "routing.community.scoped", input }))]) let fences = 0 const options: Options = { sourceOperationId: operationId, context: { principal, connection: await effectiveMcpConnection(principal) }, authorize: async () => { fences++ }, deadline: Date.now() + 90000, manifest: { servers: [serverId], probes: withProbes ? [{ key: "a", serverId, destination: "203.0.113.9", source: "198.51.100.1", interface: "wan1", probeVrf: "probe" }] : [] } } return { options, operationId, profileId, planId, evidence, fences: () => fences } } try { await applySqlMigrations(pool) // Other genuine phases may have already created authenticated checkpoints in // this owned database. Read-only acceptance must preserve every existing row // and add none; raw SQL JSON also preserves timestamp microseconds that // conversion to a JavaScript Date would truncate. const checkpointBaselineRows = (await pool.query("SELECT to_jsonb(c)::text AS inventory_row FROM mcp_operation_checkpoints c ORDER BY operation_id,step_index")).rows const checkpointBaseline = security.fingerprint(checkpointBaselineRows) assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0) await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1") serverId = Number((await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES('owned-native-reader','127.0.0.1',$1,true,'fixture','inert-only',false,true) RETURNING id", [bound.port])).rows[0].id) await run("actual fixed read-only reader preserves one captured authority/source and cumulative wire budget across three stages", async () => { const f = await source(), originalAuthorize = f.options.authorize, session = await createRoutingNetworkNativeSession(f.options), before = responseBytes const first = await session.readSnapshot("before") assert.equal(first.securityProof, false); assert.equal(first.logCoverage, "unknown"); assert.equal(first.probes.length, 1) const server = first.servers[0] const manifest = { revision: 1, phase: "forward", identity: { operationId: f.operationId, stepIndex: 0, profileId: f.profileId, profileVersion: 1, sourceEpoch: "owned-fixture-epoch", authorityIdentity: "owned-fixture-authority" }, // Bind the diagnostic fixture to the actual acquisition interval. A guessed // lookback after SQL/HTTP completes can put its source after the first read. sourceCreatedAt: Date.parse(first.startedAt), deadline: f.options.deadline, observationStartAt: Date.parse(first.observedAt), maximumSampleAgeMs: 30000, serverIds: [serverId], configuration: { serverId, nativeId: "*r1", table: "tenant", bodyIdentity: "not-a-configuration-checkpoint", dependencyIdentity: "not-a-publication-proof" }, routes: [{ key: "route1", serverId, family: "ipv4", prefix: "203.0.113.0/24", table: "tenant", sessionKey: "peer1", nextHop: "192.0.2.1", interface: "wan1", resolverTable: "main", resolutionChain: [{ address: "192.0.2.1", table: "main", interface: "wan1" }] }], bgp: [{ key: "peer1", serverId, family: "ipv4", connectionId: "*c1", instance: "default", localAddress: "192.0.2.2", remoteAddress: "192.0.2.1", remoteAsn: 65001 }], bfd: [{ key: "bfd1", serverId, applicability: "required", configurationIdentity: "fixture-bfd", localAddress: "192.0.2.2", remoteAddress: "192.0.2.1", interface: "wan1", vrf: "main" }], probes: [{ key: "a", serverId, family: "ipv4", destination: "203.0.113.9", source: "198.51.100.1", interface: "wan1", probeVrf: "probe", expectedHops: ["203.0.113.9"] }], logs: [{ key: "logs1", serverId, generation: "fixture-ring", sequenceMode: "contiguous-capture", afterSequence: 0, topics: ["route", "bgp", "bfd", "interface"], relatedKeys: ["route1", "peer1", "bfd1", "a"] }], } const parser = captureRoutingNetworkNativeParser(manifest) const metadata = { serverId: server.serverId, routerOsVersion: server.routerOsVersion } const routeOrigin = parser.parseRoute("route1", { ...metadata, ...server.routes }) assert.equal(routeOrigin.status, "unknown"); if (routeOrigin.status === "unknown") assert.equal(routeOrigin.reason, "unsupported-route-bgp-origin-namespace") for (const parsed of [parser.parseBgp("peer1", { ...metadata, ...server.bgp }), parser.parseBfd("bfd1", { ...metadata, ...server.bfd }), parser.parseProbe("a", first.probes[0])]) assert.equal(parsed.status, "observed", JSON.stringify(parsed)) assert.equal(parser.parseLogs({ ...metadata, ...server.logs }).status, "unknown", "An empty actual log response cannot mint complete authenticated log coverage") const budgetBeforeContext = session.readBudget(), requestsBeforeContext = requests.length const shared = await readRoutingNetworkScopedCommunityContext(session.sharedContext) assert.equal(shared.before.scopedExecutionAvailable, false, "Read-only shared acquisition must retain existing execution guards") const budgetAfterContext = session.readBudget() assert.equal(budgetAfterContext.calls - budgetBeforeContext.calls, requests.length - requestsBeforeContext) assert(budgetAfterContext.bytes > budgetBeforeContext.bytes); assert(budgetAfterContext.rows > budgetBeforeContext.rows) const beforeFake = requests.length await assert.rejects(readRoutingNetworkScopedCommunityContext(JSON.parse(JSON.stringify(session.sharedContext)))) assert.equal(requests.length, beforeFake) f.options.manifest.servers.push(999999); f.options.authorize = async () => { throw Error("Outer provider must not replace captured fence") } const logRow = (id: string, message: string) => ({ ".id": id, buffer: "memory", time: "10:00:00", topics: "bgp,info", message }) const up = logRow("*1", "session up"), down = logRow("*2", "session down"), restored = logRow("*3", "session restored") logRows = [up, down] const second = await session.readSnapshot("after-forward") assert.deepEqual(second.servers[0].logs.payload, [up, down]) logRows = [down, restored] const secondRound = await session.readSnapshot("after-forward") logRows = [restored, logRow("*1", "session restarted")] const third = await session.readSnapshot("after-inverse") const thirdRound = await session.readSnapshot("after-inverse") for (const snapshot of [second, secondRound, third, thirdRound]) { assert.equal(snapshot.logCoverage, "unknown") assert.equal(snapshot.servers[0].logs.payload.length, 2) } const assembledForward = captureRoutingNetworkObservationAssembly(manifest).assemble([first, second, secondRound], Date.now()) const assembledInverse = captureRoutingNetworkObservationAssembly({ ...manifest, phase: "inverse", observationStartAt: Date.parse(third.startedAt) }).assemble([first, second, secondRound, third, thirdRound], Date.now()) for (const assembled of [assembledForward, assembledInverse]) { assert.equal(assembled.verdict, "unknown"); assert.equal(assembled.securityProof, false); assert.equal(assembled.completeRounds, 0) assert.equal(assembled.diagnostics.length, 2, JSON.stringify(assembled.reasons)) assert(assembled.reasons.includes("configuration-proof-unavailable")) assert(assembled.reasons.includes("authenticated-log-interval-coverage-unsupported")) assert(assembled.diagnostics.every(round => round.observations.filter(entry => entry.stage !== "logs" && entry.stage !== "routes").every(entry => entry.result.status === "observed"))) assert(assembled.diagnostics.every(round => round.observations.filter(entry => entry.stage === "routes").every(entry => entry.result.status === "unknown" && entry.result.reason === "unsupported-route-bgp-origin-namespace"))) } assert(second.budget.calls > first.budget.calls); assert(third.budget.calls > second.budget.calls) assert.equal(third.budget.deadline, f.options.deadline); assert.equal(session.readBudget().bytes, responseBytes - before) assert(third.budget.rows > second.budget.rows); assert(f.fences() > 20) assert(Object.isFrozen(first.servers[0].routes.payload)); session.close() const count = requests.length; await assert.rejects(createRoutingNetworkNativeSession({ ...f.options, authorize: originalAuthorize, manifest: { servers: [serverId!], probes: [] } }), /уже создавалась/); assert.equal(requests.length, count) }) await run("actual terminal zero-received ping skips traceroute without inventing log coverage", async () => { const f = await source(), session = await createRoutingNetworkNativeSession(f.options), count = requests.length mode = "zero-ping" const snapshot = await session.readSnapshot("before") assert.equal(snapshot.probes.length, 1) assert.deepEqual(snapshot.probes[0].pingPayload, [{ sent: "3", received: "0", "packet-loss": "100%" }]) assert.equal(snapshot.probes[0].tracePayload, undefined) assert.equal(snapshot.logCoverage, "unknown") assert.equal(requests.slice(count).filter(request => request.path === "/tool/ping").length, 1) assert.equal(requests.slice(count).filter(request => request.path === "/tool/traceroute").length, 0) session.close() }) await run("reordered stage permanently closes session without native continuation", async () => { const f = await source(false), session = await createRoutingNetworkNativeSession(f.options), count = requests.length await assert.rejects(session.readSnapshot("after-forward")); await assert.rejects(session.readSnapshot("before")); assert.equal(requests.length, count) }) for (const scenario of ["profile", "endpoint-aba", "cancel"] as const) await run("late " + scenario + " after actual GET stops subsequent native requests", async () => { const f = await source(false), abort = new AbortController(); f.options.context.signal = abort.signal const session = await createRoutingNetworkNativeSession(f.options), count = requests.length onRequest = async () => { if (scenario === "profile") await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=$1", [f.profileId]) else if (scenario === "endpoint-aba") { await pool.query("UPDATE servers SET username='temporary' WHERE id=$1", [serverId]); await pool.query("UPDATE servers SET username='fixture' WHERE id=$1", [serverId]) } else abort.abort() } await assert.rejects(session.readSnapshot("before")); assert.equal(requests.length, count + 1) await assert.rejects(session.readSnapshot("after-forward")); assert.equal(requests.length, count + 1) }) await run("tampered source request and extended original deadline refuse before HTTP", async () => { const f = await source(false), count = requests.length f.evidence.steps[0].input.requestProof = "f".repeat(64) await pool.query("UPDATE mcp_plans SET evidence=$2::jsonb WHERE id=$1", [f.planId, JSON.stringify({ sealed: await security.encryptSecret(JSON.stringify(f.evidence)) })]) await assert.rejects(createRoutingNetworkNativeSession(f.options)); assert.equal(requests.length, count) const g = await source(false); await pool.query("UPDATE mcp_operations SET created_at=now()-interval '60 seconds' WHERE id=$1", [g.operationId]) await assert.rejects(createRoutingNetworkNativeSession(g.options)); assert.equal(requests.length, count) }) for (const fault of ["redirect", "auth", "malformed", "oversized", "rows"] as const) await run("actual " + fault + " response stops without retry or redirect", async () => { const f = await source(false), session = await createRoutingNetworkNativeSession(f.options), count = requests.length mode = fault; await assert.rejects(session.readSnapshot("before")); assert.equal(requests.length, count + 1) await assert.rejects(session.readSnapshot("after-forward")); assert.equal(requests.length, count + 1); assert.equal(sinks, 0) }) await run("actual aggregate wire bytes remain charged across forward and inverse", async () => { const f = await source(false), session = await createRoutingNetworkNativeSession(f.options); mode = "total-bytes" await session.readSnapshot("before"); await session.readSnapshot("after-forward") await assert.rejects(session.readSnapshot("after-forward")); assert(session.readBudget().bytes > 8 * 1048576) }) await run("actual row count remains charged across phases and rejects total10000 overflow", async () => { const f = await source(false), session = await createRoutingNetworkNativeSession(f.options); mode = "total-rows" await session.readSnapshot("before"); await assert.rejects(session.readSnapshot("after-forward")); assert(session.readBudget().rows > 10000) }) const topologyObserver = async () => { const f = await source(false), { connectionId, credentialId } = f.options.context.principal const policy = mcpConnectionPolicySchema.parse({ ...f.options.context.connection.policy, mode: "observer", permissions: ["mm:network:read"], scope: { serverIds: [serverId!], operationIds: ["routing.topology.read"], allowGlobal: false } }) await pool.query("UPDATE mcp_connections SET policy=$2::jsonb,owner_permissions=$3::jsonb WHERE id=$1", [connectionId, JSON.stringify(policy), JSON.stringify(["mm:network:read"])]) const token = security.randomToken("bearer") await pool.query("UPDATE mcp_credentials SET digest=$2 WHERE id=$1", [credentialId, security.tokenDigest(token)]) return { principal: await authenticateMcpToken(token), connectionId } } await run("actual public topology bearer reader observes final gateway without operation binding or namespace joins", async () => { const f = await topologyObserver(), count = requests.length, plans = Number((await pool.query("SELECT count(*) AS n FROM mcp_plans")).rows[0].n) const result = await invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId }) as { routeResolution: { status: string; items: Array<{ status: string; immediateGateway: { address: string; interface: string }; semanticProof: boolean; routeOriginVerified: boolean; recursiveChainVerified: boolean }> } } assert.equal(requests.length - count, 11) assert.equal(result.routeResolution.status, "observed") const route = result.routeResolution.items[0] assert.equal(route.status, "observed"); assert.deepEqual(route.immediateGateway, { address: "192.0.2.1", interface: "wan1" }) assert.equal(route.semanticProof, false); assert.equal(route.routeOriginVerified, false); assert.equal(route.recursiveChainVerified, false) assert.equal(Number((await pool.query("SELECT count(*) AS n FROM mcp_plans")).rows[0].n), plans) assert(!JSON.stringify(result).includes("peer-cache-id")); assert(!JSON.stringify(result).includes("bgp.session")) }) await run("actual public topology preserves unknown numeric gateway despite matching BGP cache/session strings", async () => { const f = await topologyObserver(); mode = "topology-unknown" const result = await invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId }) as { routeResolution: { items: Array<{ status: string; reason: string }> } } assert.equal(result.routeResolution.items[0].status, "unknown") assert.equal(result.routeResolution.items[0].reason, "unconfirmed-immediate-endpoint") }) await run("actual public topology bearer and server scope/disabled checks refuse before native I/O", async () => { const f = await topologyObserver(), count = requests.length await assert.rejects(authenticateMcpToken("not-a-token")) await assert.rejects(invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId: serverId! + 100000 })) await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId]) await assert.rejects(invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId })) await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [serverId]) assert.equal(requests.length, count) }) await run("actual public topology pause endpoint ABA and cancellation retire at first response without publication", async () => { for (const fault of ["pause", "endpoint-aba", "cancel"] as const) { const f = await topologyObserver(), count = requests.length, cancel = new AbortController() onRequest = async () => { if (fault === "pause") await pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"paused\"') WHERE id=$1", [f.connectionId]) else if (fault === "endpoint-aba") { await pool.query("UPDATE servers SET verify_ssl=NOT verify_ssl WHERE id=$1", [serverId]) await pool.query("UPDATE servers SET verify_ssl=NOT verify_ssl WHERE id=$1", [serverId]) } else cancel.abort() } await assert.rejects(invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId }, cancel.signal)) assert.equal(requests.length, count + 1) } }) assert.equal(writes, 0) assert.equal(security.fingerprint((await pool.query("SELECT to_jsonb(c)::text AS inventory_row FROM mcp_operation_checkpoints c ORDER BY operation_id,step_index")).rows), checkpointBaseline, "Read-only acceptance must preserve existing checkpoints exactly and create none") console.log("Owned routing native reader SQL/HTTP:", JSON.stringify({ cases: cases.length, names: cases, requests: requests.length, nativeWrites: writes, actualSql: true, actualHttp: true, syntheticEncryptedSourcePlans: true, genuinePrepareAccepted: false, configurationCheckpointFabricated: false, priorCheckpointsPreserved: checkpointBaselineRows.length, checkpointInventoryUnchanged: true, signedNetworkOutcomePublished: false, logCoverage: "unknown", reservedDispatchEnabled: false, realChr: false })) } finally { if (profiles.length) await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=ANY($1::uuid[])", [profiles]).catch(() => {}) if (connections.length) await pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"paused\"') WHERE id=ANY($1::uuid[])", [connections]).catch(() => {}) if (serverId) await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId]).catch(() => {}) restoreAgent(); router.closeAllConnections(); await new Promise(done => router.close(() => done())) await closePool() }