210 lines
17 KiB
TypeScript
210 lines
17 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createServer } from "node:http"
|
|
import { randomUUID, createHash } from "node:crypto"
|
|
import { readFile } from "node:fs/promises"
|
|
import { runInNewContext } from "node:vm"
|
|
import { isIP } from "node:net"
|
|
import { test } from "node:test"
|
|
import ts from "typescript"
|
|
import { z } from "zod"
|
|
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
|
import { managedComment } from "../../managed-markers.js"
|
|
import { compileManagedFilterRules } from "../../services/filter-rules-write-model.js"
|
|
import { nativeBgpRows, bgpTemplateReferences } from "../../services/bgp-export-model.js"
|
|
import { bgpFilterName, effectiveBgpFilter, stableBgpPolicyRow } from "../../services/bgp-filter-binding-model.js"
|
|
import { canonicalVrfMembers } from "../../services/vrf-members.js"
|
|
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
|
import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
|
|
import * as contextModel from "./routing-community-context-model.js"
|
|
import { scopedTargetRuleMatches } from "./routing-community-scoped-model.js"
|
|
import { prepareOriginalEffectSelection } from "./routing-original-effects.js"
|
|
import { readMeasurementAddress } from "./routing-measurement-address.js"
|
|
import { routeContextClients } from "./routing-community-context-native.js"
|
|
import { pathProofTag } from "./path-proof-purpose.js"
|
|
|
|
async function loadSource(file: string, providers: Record<string, unknown>, exports: Record<string, unknown>) {
|
|
const source = await readFile(new URL(file, import.meta.url), "utf8")
|
|
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
|
runInNewContext(compiled, { exports, require(name: string) { assert(name in providers, "Unexpected production dependency: " + name); return providers[name] },
|
|
Buffer, AbortSignal, AbortController, structuredClone, Date })
|
|
}
|
|
type Token = Record<string, never>
|
|
type Session = { sharedContext: Token; readSnapshot(stage: string): Promise<unknown>; readBudget(): { calls: number; bytes: number; rows: number; closed: boolean }; close(): void }
|
|
type Context = { before: { scopedExecutionAvailable: boolean; scopedExecutionReason: string | null }; ownedTarget?: { nativeId: string }; clients?: unknown; signEvidence?: unknown }
|
|
|
|
/** Actual native session, context, private API and HTTP transport source, with
|
|
* owned loopback wire I/O. SQL/authority providers are inert fixtures. This is
|
|
* combined I/O accounting acceptance, not genuine SQL checkpoint acceptance. */
|
|
async function fixture(autoRecovery = false) {
|
|
let requests = 0, wireBytes = 0, wireRows = 0, rawGetObjects = 0, bulk = 0, padding = 0, revoked = false
|
|
let afterHttp: (() => void) | undefined, afterPath: { path: string; run(): void } | undefined
|
|
const body = compileManagedFilterRules([{ community: "65000:10", gateway: "192.0.2.1", outIface: "", action: "route", description: "" }])
|
|
const collections: Record<string, Record<string, unknown>[]> = {
|
|
"/system/resource": [{ version: "7.20.4" }],
|
|
"/routing/table": [{ ".id": "*t", name: "tenant", fib: "true" }, { ".id": "*tm", name: "main", fib: "true" }],
|
|
"/ip/vrf": [{ ".id": "*v", name: "main", interfaces: "all", disabled: "false" }],
|
|
"/routing/bgp/connection": [{ ".id": "*c1", name: "peer", instance: "default", vrf: "main", "routing-table": "tenant", afi: "ip", "input.filter": "custom", "output.filter-chain": "", templates: "", disabled: "false" }],
|
|
"/routing/bgp/instance": [{ ".id": "*i", name: "default", vrf: "main", "routing-table": "main", disabled: "false" }],
|
|
"/routing/filter/rule": [{ ".id": "*f", chain: "custom", rule: body, comment: managedComment("fixture") }],
|
|
"/ip/route": [1, 9].map(value => ({ ".id": "*r" + value, "dst-address": "192.0.2." + value + "/32", "routing-table": "main", disabled: "false", comment: managedComment("recursive") })),
|
|
"/interface": ["wan", "hop", "target"].map((name, index) => ({ ".id": "*if" + index, name, disabled: "false" })),
|
|
"/ip/address": ["wan", "hop", "target"].map((name, index) => ({ ".id": "*ad" + index, interface: name, address: "198.51.100." + (index + 1) + "/32", disabled: "false", invalid: "false" })),
|
|
}
|
|
const router = createServer(async (req, res) => {
|
|
let raw = ""; for await (const chunk of req) raw += chunk
|
|
const args = raw ? JSON.parse(raw) : {}, path = decodeURIComponent((req.url ?? "").replace(/^\/rest/, ""))
|
|
assert(["GET", "POST"].includes(req.method ?? "")); requests++
|
|
let response: unknown
|
|
if (req.method === "POST") {
|
|
assert(path.endsWith("/get")); const resource = path.slice(0, -4)
|
|
const row = collections[resource]?.find(row => row[".id"] === args[".id"])
|
|
const value = args["value-name"] === "disabled" ? "false" : row?.[args["value-name"]]
|
|
response = value === undefined ? [] : { ret: value }; if (!Array.isArray(response)) rawGetObjects++
|
|
} else if (["/routing/ospf/instance", "/routing/rip/instance"].includes(path)) {
|
|
response = Array.from({ length: bulk || (padding ? 1 : 0) }, (_, index) => ({ ".id": "*e" + index, fixture: padding ? "я".repeat(padding) : "row" }))
|
|
} else response = collections[path] ?? []
|
|
const encoded = JSON.stringify(response); wireBytes += Buffer.byteLength(encoded); wireRows += Array.isArray(response) ? response.length : 1
|
|
res.setHeader("content-type", "application/json"); res.end(encoded)
|
|
afterHttp?.(); afterHttp = undefined
|
|
if (afterPath?.path === path) { const run = afterPath.run; afterPath = undefined; run() }
|
|
})
|
|
const now = Date.now(), fingerprint = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex")
|
|
const endpoint = { id: 1, host: "127.0.0.1", port: 0, username: "fixture", password: "private", useSsl: false, verifySsl: true, enabled: true, routingEndpointEpoch: randomUUID() }
|
|
const principal = { connectionId: randomUUID(), credentialId: randomUUID(), credentialExpiresAt: new Date(now + 600000).toISOString() }
|
|
const connection = { id: principal.connectionId, owner_id: "owner", generation: "generation", owner_permissions: ["mm:network:read"],
|
|
policy: { permissions: ["mm:network:read"], scope: { serverIds: [1] }, expiresAt: new Date(now + 600000).toISOString() }, owner_valid_until: new Date(now + 600000) }
|
|
const profile = routeAiProfileSchema.parse({ name: "shared fixture", serverId: 1, family: "ipv4", community: "65000:10", table: "tenant", probeVrf: "main", autoRecovery,
|
|
bgpContext: { connectionId: "*c1", instance: "default", vrf: "main", inputChain: "custom" },
|
|
candidates: [1, 9].map(value => ({ id: value === 1 ? "a" : "b", jumpHostId: 1, exitNodeId: 1, wanInterface: "wan", downstreamInterface: "hop", gateway: "192.0.2." + value, gatewayRef: { resource: "ipv4_route", id: "*r" + value },
|
|
...(autoRecovery ? { controlProbe: { targetInterface: "target", expectedHops: [{ serverId: 1, interface: "hop" }, { serverId: 1, interface: "target" }] } } : {}) })) })
|
|
const sources = [{ serverId: 1, proof: "source" }]
|
|
const input = { profile, principal, ownerId: "owner", candidateId: "a", contextSources: sources, generation: "generation", connectionGeneration: "generation", policyProof: fingerprint(connection.policy) }
|
|
const step = { kind: "service", service: "routing.community.scoped", input }
|
|
const row = { id: randomUUID(), state: "running", step_state: "intent", created_at: new Date(now), plan_id: randomUUID(), operation_id: "routing.community.switch", operation_version: 7,
|
|
approved_by: "owner", expires_at: new Date(now + 600000), intended_state: step, evidence: { sealed: JSON.stringify({ target: { scope: "servers", serverIds: [1] }, steps: [step] }) } }
|
|
const security = { fingerprint, redact: (value: unknown) => value, constantEqual: (a: string, b: string) => a === b,
|
|
McpError: class extends Error { constructor(readonly code: string, message: string) { super(message) } }, accessGeneration: async () => "generation", decryptSecret: async (value: string) => value,
|
|
privateFingerprinter: async () => (value: string) => fingerprint(value) }
|
|
const authority = async () => { if (revoked) throw Error("revoked fixture authority") }
|
|
const observationSource = { readRoutingEndpoints: async () => [endpoint], createRoutingSourceContext: async () => ({ expected: sources, assertCurrent: authority }) }
|
|
const sql = { query: async (query: string | { text: string }) => (typeof query === "string" ? query : query.text).includes("mcp_protections") ? { rows: [{ refs: [], overflow: false }] } : { rows: [row] } }
|
|
const native: Record<string, unknown> = {}, context: Record<string, unknown> = {}, privateApi: Record<string, unknown> = {}
|
|
const common = { "../../db/index.js": { pool: sql }, "./security.js": security, "./store.js": { effectiveMcpConnection: async () => { await authority(); return connection } },
|
|
"../../lib/permissions.js": { hasPermission: (values: string[], value: string) => values.includes(value) }, "./routing-observation-source.js": observationSource,
|
|
"./routing-community-context-native.js": { routeContextClients }, "../../services/vrf-members.js": { canonicalVrfMembers }, "../../services/ospf-effective-disabled.js": { readOspfEffectiveDisabled },
|
|
"./routing-measurement-address.js": { readMeasurementAddress } }
|
|
await loadSource("./routing-community-context.ts", { ...common, "./routing-network-native-session.js": native,
|
|
"../../services/routing-table-fib.js": { isConfirmedRoutingFibTable }, "./routing-original-effects.js": { prepareOriginalEffectSelection },
|
|
"../../services/bgp-export-model.js": { nativeBgpRows, bgpTemplateReferences }, "../../services/bgp-filter-binding-model.js": { bgpFilterName, effectiveBgpFilter, stableBgpPolicyRow },
|
|
"./routing-community-context-model.js": contextModel, "./routing-community-scoped-model.js": { scopedTargetRuleMatches },
|
|
"./path-proof-purpose.js": { pathProofTag },
|
|
"./management-transport.js": { assertManagementTransport: async () => { throw Error("No alternate management fixture") } } }, context)
|
|
await loadSource("./routing-network-native-session.ts", { ...common, "node:net": { isIP }, zod: { z }, "@mmapp/contracts/mcp-routing": { routeAiProfileSchema },
|
|
"./routing-community-context.js": context, "./registry.js": { findMcpOperation: () => ({ version: 7 }) },
|
|
"./routing-community-scoped-request.js": { assertScopedCommunityRequest: async () => "inert request boundary" },
|
|
"./routing-profile-authority.js": { assertPersistentScopedProfileAuthority: authority, routingProfileAuthorityBindingSchema: { parse: () => { throw Error("No persistent checkpoint claimed") } } },
|
|
"./routing-network-native-destination.js": { resolveRoutingNetworkDestinationPins: async () => [{ serverId: 1, host: endpoint.host, address: "127.0.0.1", family: 4 }] } }, native)
|
|
await loadSource("./routing-network-scoped-context.ts", { "./routing-network-native-session.js": native }, privateApi)
|
|
const create = native.createRoutingNetworkNativeSession as (options: unknown) => Promise<Session>
|
|
const abort = new AbortController()
|
|
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
|
endpoint.port = (router.address() as { port: number }).port
|
|
const closeRouter = () => {
|
|
router.closeAllConnections()
|
|
return new Promise<void>(resolve => router.close(() => resolve()))
|
|
}
|
|
const session = await create({ sourceOperationId: row.id, context: { principal, connection, signal: abort.signal }, authorize: authority, deadline: now + 119000, manifest: { servers: [1], probes: [] } }).catch(async error => {
|
|
await closeRouter()
|
|
throw error
|
|
})
|
|
const readContext = privateApi.readRoutingNetworkScopedCommunityContext as (token: Token) => Promise<Context>
|
|
return { session, readContext: () => readContext(session.sharedContext), forged: () => readContext(JSON.parse(JSON.stringify(session.sharedContext))),
|
|
readResource: native.readRoutingNetworkSharedResource as (token: Token, server: number, path: string, body?: Record<string, string>) => Promise<unknown>,
|
|
bypassTail: context.readRouteCommunityContextWithSharedNativeSession as (token: Token) => Promise<unknown>,
|
|
counters: () => ({ requests, wireBytes, wireRows, rawGetObjects }), bulk: (value: number) => { bulk = value }, padding: (value: number) => { padding = value },
|
|
revoke: () => { revoked = true }, abort: () => abort.abort(), afterHttp: (hook: () => void) => { afterHttp = hook }, afterPath: (path: string, hook: () => void) => { afterPath = { path, run: hook } },
|
|
cleanup: async () => { session.close(); await closeRouter() } }
|
|
}
|
|
|
|
test("actual source context and snapshots share one pinned HTTP request/byte/row budget including object /get", async () => {
|
|
const f = await fixture()
|
|
try {
|
|
await f.session.readSnapshot("before"); const before = f.session.readBudget(); assert.equal(before.calls, 6)
|
|
const context = await f.readContext(); assert.equal(context.before.scopedExecutionAvailable, true); assert.equal(context.ownedTarget?.nativeId, "*f")
|
|
assert.equal(context.clients, undefined); assert.equal(context.signEvidence, undefined)
|
|
const after = f.session.readBudget(); assert(after.calls > before.calls); assert(f.counters().rawGetObjects > 0)
|
|
await f.session.readSnapshot("after-forward"); const final = f.session.readBudget(), wire = f.counters()
|
|
assert.equal(final.calls, after.calls + 6); assert.equal(final.calls, wire.requests); assert.equal(final.bytes, wire.wireBytes); assert.equal(final.rows, wire.wireRows)
|
|
assert.equal(final.closed, false)
|
|
} finally { await f.cleanup() }
|
|
})
|
|
|
|
for (const dimension of ["requests", "bytes", "rows"]) test("combined " + dimension + " exhaustion closes both context and later snapshot I/O", async () => {
|
|
const f = await fixture()
|
|
try {
|
|
if (dimension === "bytes") f.padding(350000)
|
|
if (dimension === "rows") f.bulk(1000)
|
|
await f.session.readSnapshot("before")
|
|
let denied = false
|
|
for (let index = 0; index < 20; index++) { try { await f.readContext() } catch { denied = true; break } }
|
|
assert(denied); assert.equal(f.session.readBudget().closed, true)
|
|
const stopped = f.counters().requests
|
|
await assert.rejects(f.readContext()); await assert.rejects(f.session.readSnapshot("after-forward")); assert.equal(f.counters().requests, stopped)
|
|
if (dimension === "requests") assert.equal(f.session.readBudget().calls, 256)
|
|
if (dimension === "bytes") assert(f.session.readBudget().bytes > 8388608)
|
|
if (dimension === "rows") assert(f.session.readBudget().rows > 10000)
|
|
} finally { await f.cleanup() }
|
|
})
|
|
|
|
test("JSON metadata cannot reconstruct a shared transport owner", async () => {
|
|
const f = await fixture()
|
|
try { await assert.rejects(f.forged(), /Unknown native shared context/); assert.equal(f.counters().requests, 0) } finally { await f.cleanup() }
|
|
})
|
|
|
|
for (const request of ["foreign-server", "write-path", "probe", "wrong-field", "extra-field"]) test("owner metadata cannot issue direct " + request + " resource I/O outside acquisition", async () => {
|
|
const f = await fixture()
|
|
try {
|
|
const path = request === "write-path" ? "/routing/filter/rule/*f" : request === "probe" ? "/tool/ping" : "/routing/bgp/connection/get"
|
|
const body = request === "wrong-field" ? { ".id": "*c1", "value-name": "password" } : request === "extra-field" ? { ".id": "*c1", "value-name": "disabled", extra: "forged" } : undefined
|
|
await assert.rejects(f.readResource(f.session.sharedContext, request === "foreign-server" ? 2 : 1, path, body))
|
|
assert.equal(f.counters().requests, 0); assert.equal(f.session.readBudget().closed, false)
|
|
} finally { await f.cleanup() }
|
|
})
|
|
|
|
test("the internal context entry point cannot bypass the serialized owner API", async () => {
|
|
const f = await fixture()
|
|
try { await assert.rejects(f.bypassTail(f.session.sharedContext), /Unknown or completed shared context acquisition/); assert.equal(f.counters().requests, 0) }
|
|
finally { await f.cleanup() }
|
|
})
|
|
|
|
test("revocation after a real shared HTTP response closes the original native session", async () => {
|
|
const f = await fixture()
|
|
try { f.afterHttp(f.revoke); await assert.rejects(f.readContext(), /revoked/); assert.equal(f.session.readBudget().closed, true); const stopped = f.counters().requests; await assert.rejects(f.session.readSnapshot("before")); assert.equal(f.counters().requests, stopped) }
|
|
finally { await f.cleanup() }
|
|
})
|
|
|
|
test("configuration and snapshot acquisitions serialize on the same tail", async () => {
|
|
const f = await fixture()
|
|
try {
|
|
const work = f.readContext(), snapshot = f.session.readSnapshot("before")
|
|
await work; const calls = f.session.readBudget().calls
|
|
await snapshot; assert.equal(f.session.readBudget().calls, calls + 6)
|
|
} finally { await f.cleanup() }
|
|
})
|
|
|
|
test("shared transport preserves autoRecovery execution guard in actual context source", async () => {
|
|
const f = await fixture(true)
|
|
try { const context = await f.readContext(); assert.equal(context.before.scopedExecutionAvailable, false); assert.equal(context.before.scopedExecutionReason, "ROUTE_RECOVERY_EXECUTOR_UNAVAILABLE") }
|
|
finally { await f.cleanup() }
|
|
})
|
|
|
|
test("original cancellation during shared context wire I/O closes queued snapshot acquisition", async () => {
|
|
const f = await fixture()
|
|
try {
|
|
f.afterHttp(f.abort)
|
|
const context = f.readContext(), snapshot = f.session.readSnapshot("before")
|
|
const results = await Promise.allSettled([context, snapshot]); assert(results.every(result => result.status === "rejected"))
|
|
assert.equal(f.session.readBudget().closed, true); assert.equal(f.counters().requests, 1)
|
|
} finally { await f.cleanup() }
|
|
})
|