Files
MikrotikManager/backend/src/modules/mcp/routing-network-verifier-model.test.ts
T

254 lines
19 KiB
TypeScript

import assert from "node:assert/strict"
import { test } from "node:test"
import { captureRoutingNetworkManifest, captureRoutingNetworkRounds, classifyRoutingNetwork, createRoutingNetworkBudget, createRoutingNetworkClassifier,
routingNetworkManifestSchema, spendRoutingNetworkBudget, type RoutingNetworkManifest, type RoutingNetworkRound } from "./routing-network-verifier-model.js"
const start = 1800000000000, now = start + 10000
function fixture() {
const manifest: RoutingNetworkManifest = {
revision: 1, phase: "forward", identity: { operationId: "00000000-0000-4000-8000-000000000001", stepIndex: 0,
profileId: "00000000-0000-4000-8000-000000000002", profileVersion: 1, sourceEpoch: "endpoint1", authorityIdentity: "original1" },
sourceCreatedAt: start, deadline: start + 120000, observationStartAt: start + 1000, maximumSampleAgeMs: 30000, serverIds: [1],
configuration: { serverId: 1, nativeId: "*1", table: "tenant", bodyIdentity: "desired-body", dependencyIdentity: "original-dependencies" },
routes: [{ key: "route1", serverId: 1, 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: 1, connectionId: "*c1", instance: "default", family: "ipv4", localAddress: "192.0.2.2", remoteAddress: "192.0.2.1", remoteAsn: 65001 }],
bfd: [{ key: "bfd1", serverId: 1, applicability: "required", configurationIdentity: "bfd-config1", localAddress: "192.0.2.2", remoteAddress: "192.0.2.1", interface: "wan1", vrf: "main" }],
probes: [{ key: "probe1", serverId: 1, family: "ipv4", destination: "203.0.113.1", source: "198.51.100.1", interface: "wan1", probeVrf: "diagnostic", expectedHops: ["192.0.2.1", "203.0.113.1"] }],
logs: [{ key: "logs1", serverId: 1, generation: "boot1", sequenceMode: "contiguous-capture", afterSequence: 100, topics: ["route", "bgp", "bfd", "interface"], relatedKeys: ["route1", "peer1", "bfd1", "probe1"] }],
}
const round = (offset: number): RoutingNetworkRound => ({ identity: structuredClone(manifest.identity), startedAt: start + offset, observedAt: start + offset + 100,
configuration: structuredClone(manifest.configuration), routes: manifest.routes.map(route => ({ ...structuredClone(route), active: true, resolved: true, protocol: "bgp", resolutionChain: route.resolutionChain.map(hop => ({ ...hop, resolved: true })) })),
bgp: manifest.bgp.map(peer => ({ ...peer, state: "established" })), bfd: manifest.bfd.map(session => session.applicability === "required" ? { ...session, state: "up" } : { ...session, configured: false }),
probes: manifest.probes.map(probe => ({ ...structuredClone(probe), sent: 3, received: 3, terminal: true, trace: { kind: "observed", hops: probe.expectedHops.map((address, index) => ({ hop: index + 1, address, state: "responded" })) } })),
logs: manifest.logs.map(scope => ({ ...structuredClone(scope), coverageStartAt: start + 1000, coveredUntil: start + offset + 100, capturedAt: start + offset + 100, toSequence: 100, responseRowCount: 0, moreAvailable: false, rotationDetected: false, clockSynchronized: true, rows: [] })),
})
const rounds = [round(2000), round(3000)]
const budget = spendRoutingNetworkBudget(createRoutingNetworkBudget(start, [start + 120000], start), "forward", now, { requests: 20, rows: 40, bytes: 40000 }).budget
return { manifest, rounds, budget }
}
const classify = (f: ReturnType<typeof fixture>) => classifyRoutingNetwork(f.manifest, f.rounds, now, f.budget)
test("complete stable raw vector passes without claiming authority or forwarding; probeVRF differs from installation table", () => {
const result = classify(fixture())
assert.equal(result.verdict, "passed"); assert.equal(result.completeRounds, 2)
assert.equal(result.securityProof, false); assert.equal(result.forwardingVerified, false)
assert(Object.isFrozen(result)); assert(Object.isFrozen(result.reasons))
})
test("contiguous log rounds preserve the prefix and may append events after the preceding interval", () => {
const f = fixture()
const initial = { sequence: 101, timestamp: start + 1500, topics: ["bgp" as const], relatedKey: "peer1", event: "informational" as const, severity: "info" as const }
const next = { ...initial, sequence: 102, timestamp: start + 2500 }
const setRows = (index: number, rows: typeof initial[]) => {
Object.assign(f.rounds[index].logs[0], { rows, toSequence: 100 + rows.length, responseRowCount: rows.length })
}
setRows(0, [initial])
setRows(1, [initial, next])
assert.equal(classify(f).verdict, "passed")
for (const rows of [[], [{ ...initial, timestamp: start + 1600 }, next], [initial, { ...next, timestamp: start + 2100 }]]) {
setRows(1, rows)
const result = classify(f)
assert.equal(result.verdict, "unknown")
assert.deepEqual(result.reasons, ["logs:inconsistent-across-rounds"])
}
setRows(1, [initial, next])
f.rounds[0].logs[0].coverageStartAt--
assert.deepEqual(classify(f).reasons, ["logs:inconsistent-across-rounds"])
})
for (const failure of ["route", "bgp", "bfd", "probe", "logs"] as const) test("complete stable explicit " + failure + " failure is classified failed", () => {
const f = fixture()
for (const round of f.rounds) {
if (failure === "route") round.routes[0].resolved = false
if (failure === "bgp") round.bgp[0].state = "idle"
if (failure === "bfd" && round.bfd[0].applicability === "required") round.bfd[0].state = "down"
if (failure === "probe") { round.probes[0].received = 0; round.probes[0].trace = { kind: "not-run", reason: "terminal-ping-failure" } }
if (failure === "logs") { round.logs[0].toSequence = 101; round.logs[0].responseRowCount = 1; round.logs[0].rows = [{ sequence: 101, timestamp: start + 1500, topics: ["bgp"], relatedKey: "peer1", event: "down", severity: "error" }] }
}
assert.equal(classify(f).verdict, "failed")
})
for (const missing of ["routes", "bgp", "bfd", "probes", "logs"] as const) test("missing " + missing + " overrides explicit terminal ping loss", () => {
const f = fixture()
for (const round of f.rounds) { round.probes[0].received = 0; round.probes[0].trace = { kind: "not-run", reason: "terminal-ping-failure" }; round[missing] = [] }
assert.equal(classify(f).verdict, "unknown")
})
for (const mutation of ["source", "authority", "profile", "table", "family", "prefix", "peer", "bfd-applicability", "probeVRF", "log-generation"] as const) test("mixed identity " + mutation + " is unknown", () => {
const f = fixture(), round = f.rounds[0]
if (mutation === "source") round.identity.sourceEpoch = "other"
if (mutation === "authority") round.identity.authorityIdentity = "new-credential"
if (mutation === "profile") round.identity.profileVersion++
if (mutation === "table") round.routes[0].table = "diagnostic"
if (mutation === "family") round.routes[0].family = "ipv6"
if (mutation === "prefix") round.routes[0].prefix = "203.0.114.0/24"
if (mutation === "peer") round.bgp[0].connectionId = "*c2"
if (mutation === "bfd-applicability") round.bfd[0] = { key: "bfd1", serverId: 1, configurationIdentity: "bfd-config1", applicability: "not-applicable", reason: "not-configured", configured: false }
if (mutation === "probeVRF") round.probes[0].probeVrf = "tenant"
if (mutation === "log-generation") round.logs[0].generation = "boot2"
assert.equal(classify(f).verdict, "unknown")
})
test("explicit BFD not-configured is supported only with the exact configuration applicability", () => {
const f = fixture()
f.manifest.bfd[0] = { key: "bfd1", serverId: 1, configurationIdentity: "absent1", applicability: "not-applicable", reason: "not-configured" }
f.rounds.forEach(round => { round.bfd[0] = { ...f.manifest.bfd[0], configured: false } })
assert.equal(classify(f).verdict, "passed")
f.rounds[0].bfd = []; assert.equal(classify(f).verdict, "unknown")
})
test("documented BGP not-established fact is failure without inventing an idle/connect FSM state", () => {
const f = fixture(); f.rounds.forEach(round => { round.bgp[0].state = "not-established" })
assert.equal(classify(f).verdict, "failed")
f.rounds[0].logs = []; assert.equal(classify(f).verdict, "unknown")
})
for (const mutation of ["truncated", "rotation", "clock", "stale-coverage", "future-capture", "rowcount", "duplicate", "unparsed", "old-event", "unordered", "empty-advanced-watermark", "unsupported-severity"] as const) test("log coverage " + mutation + " is unknown", () => {
const f = fixture(), log = f.rounds[0].logs[0]
if (mutation === "truncated") log.moreAvailable = true
if (mutation === "rotation") log.rotationDetected = true
if (mutation === "clock") log.clockSynchronized = false
if (mutation === "stale-coverage") log.coveredUntil--
if (mutation === "future-capture") log.capturedAt = now + 1
if (mutation === "rowcount") log.responseRowCount++
if (mutation === "empty-advanced-watermark") log.toSequence++
if (mutation === "unsupported-severity") { log.toSequence++; log.responseRowCount = 1; log.rows = [{ sequence: 101, timestamp: start + 1500, topics: ["bgp"], relatedKey: "peer1", event: "informational", severity: "critical" }] }
if (["duplicate", "unparsed", "old-event", "unordered"].includes(mutation)) {
log.toSequence = 101; log.rows = [{ sequence: 101, timestamp: start + 1500, topics: ["bgp"], relatedKey: "peer1", event: mutation === "unparsed" ? "unparsed" : "informational", severity: "info" }]
if (mutation === "duplicate") log.rows.push(structuredClone(log.rows[0]))
if (mutation === "old-event") log.rows[0].timestamp = start
if (mutation === "unordered") log.rows = [{ ...log.rows[0], sequence: 102 }, log.rows[0]]
log.responseRowCount = log.rows.length
}
assert.equal(classify(f).verdict, "unknown")
})
test("unrelated keys, cross-server log scope, omitted stage keys and topics cannot pass empty log coverage", () => {
for (const mutation of ["unrelated", "cross-server", "missing-key", "missing-topic"]) {
const f = fixture()
if (mutation === "unrelated") f.manifest.logs[0].relatedKeys = ["unrelated"]
if (mutation === "cross-server") { f.manifest.serverIds.push(2); f.manifest.logs[0].serverId = 2 }
if (mutation === "missing-key") f.manifest.logs[0].relatedKeys.pop()
if (mutation === "missing-topic") f.manifest.logs[0].topics = ["bgp"]
assert.equal(classify(f).verdict, "unknown", mutation)
}
})
test("unsupported probe/BGP/BFD states and partial counters never become a terminal failed result", () => {
for (const mutation of ["bgp", "bfd", "trace-timeout", "partial-ping", "sent-zero", "received-over-sent"]) {
const f = fixture(), round = f.rounds[0]
if (mutation === "bgp") round.bgp[0].state = "unknown"
if (mutation === "bfd" && round.bfd[0].applicability === "required") round.bfd[0].state = "unknown"
if (mutation === "trace-timeout" && round.probes[0].trace.kind === "observed") round.probes[0].trace.hops[0].state = "timeout"
if (mutation === "partial-ping") round.probes[0].terminal = false
if (mutation === "sent-zero") round.probes[0].sent = 0
if (mutation === "received-over-sent") round.probes[0].sent = 2
assert.equal(classify(f).verdict, "unknown", mutation)
}
})
test("at least two complete nonoverlapping stable rounds are required; no cherry-picking unknown rounds", () => {
const f = fixture()
assert.equal(classifyRoutingNetwork(f.manifest, f.rounds.slice(0, 1), now, f.budget).verdict, "unknown")
f.rounds[1].routes[0].active = false; assert.equal(classify(f).verdict, "unknown")
const g = fixture(); g.rounds[1].startedAt = g.rounds[0].observedAt - 1; assert.equal(classify(g).verdict, "unknown")
const h = fixture(); h.rounds.push({ ...structuredClone(h.rounds[1]), startedAt: start + 4000, observedAt: start + 4100 }); h.rounds[0].bgp[0].state = "unknown"
assert.equal(classify(h).verdict, "unknown")
})
test("stale, future and reversed sample times fail closed", () => {
for (const mutation of ["future", "stale", "backwards", "before-intent", "deadline"]) {
const f = fixture()
if (mutation === "future") f.rounds[0].observedAt = now + 1
if (mutation === "stale") f.manifest.maximumSampleAgeMs = 1
if (mutation === "backwards") f.rounds[0].observedAt = f.rounds[0].startedAt - 1
if (mutation === "before-intent") f.rounds[0].startedAt = start
if (mutation === "deadline") f.rounds[0].observedAt = f.manifest.deadline
assert.equal(classify(f).verdict, "unknown", mutation)
}
})
test("strict schema rejects supplied verdict flags, missing raw data, ambiguous keys and response bounds", () => {
const f = fixture()
for (const raw of [{ ...f.rounds[0], stagePassed: true }, { ...f.rounds[0], verdict: "passed" }, { ...f.rounds[0], routes: undefined }, { ...f.rounds[0], bgp: [...f.rounds[0].bgp, f.rounds[0].bgp[0]] }, { ...f.rounds[0], logs: [{ ...f.rounds[0].logs[0], rows: Array(201).fill({}) }] }]) {
assert.equal(classifyRoutingNetwork(f.manifest, [raw, f.rounds[1]], now, f.budget).verdict, "unknown")
}
f.manifest.routes.push({ ...f.manifest.routes[0], key: "duplicate-target" }); assert.equal(routingNetworkManifestSchema.safeParse(f.manifest).success, false)
})
test("CIDR must be canonical network address and canonical IPv6 prevents alias recursion cycles", () => {
for (const value of ["203.0.113.1/24", "203.0.113.0/024", "2001:0db8::/64", "2001:db8::1/64", "::ffff:192.0.2.0/120"]) {
const f = fixture(); f.manifest.routes[0].prefix = value; assert.equal(classify(f).verdict, "unknown", value)
}
const f = fixture(); f.manifest.routes[0].resolutionChain = [{ address: "192.0.2.1", table: "main", interface: "wan1" }, { address: "192.0.2.1", table: "main", interface: "wan1" }]
assert.equal(classify(f).verdict, "unknown")
const g = fixture(); g.manifest.routes[0].resolutionChain[0].address = "2001:0db8:0:0:0:0:0:1"; assert.equal(classify(g).verdict, "unknown")
})
test("AFI mismatches, missing BGP mapping and out-of-scope observations are unknown", () => {
const f = fixture(); f.manifest.routes[0].family = "ipv6"; assert.equal(classify(f).verdict, "unknown")
const g = fixture(); g.manifest.routes[0].sessionKey = "absent"; assert.equal(classify(g).verdict, "unknown")
const h = fixture(); h.rounds[0].routes[0].serverId = 2; assert.equal(classify(h).verdict, "unknown")
const b = fixture(); if (b.rounds[0].bfd[0].applicability === "required") b.rounds[0].bfd[0].remoteAddress = "2001:db8::1"
assert.equal(classify(b).verdict, "unknown", "raw BFD Up cannot accept a cross-family pair")
})
test("canonical IPv6 vector passes while compressed/expanded aliases and mismatched BFD AFI remain unsupported", () => {
const f = fixture()
for (const value of [f.manifest, ...f.rounds]) {
value.routes[0].family = "ipv6"; value.routes[0].prefix = "2001:db8:10::/64"; value.routes[0].nextHop = "2001:db8::1"; value.routes[0].resolutionChain[0].address = "2001:db8::1"
value.bgp[0].family = "ipv6"; value.bgp[0].localAddress = "2001:db8::2"; value.bgp[0].remoteAddress = "2001:db8::1"
if (value.bfd[0].applicability === "required") { value.bfd[0].localAddress = "2001:db8::2"; value.bfd[0].remoteAddress = "2001:db8::1" }
value.probes[0].family = "ipv6"; value.probes[0].destination = "2001:db8:10::1"; value.probes[0].source = "2001:db8:20::1"; value.probes[0].expectedHops = ["2001:db8::1", "2001:db8:10::1"]
}
f.rounds.forEach(round => { round.probes[0].trace = { kind: "observed", hops: [{ hop: 1, address: "2001:db8::1", state: "responded" }, { hop: 2, address: "2001:db8:10::1", state: "responded" }] } })
assert.equal(classify(f).verdict, "passed")
const alias = structuredClone(f)
alias.rounds[0].routes[0].resolutionChain.push({ address: "2001:0db8:0:0:0:0:0:1", table: "main", interface: "wan1", resolved: true })
assert.equal(classify(alias).verdict, "unknown")
if (f.manifest.bfd[0].applicability === "required") f.manifest.bfd[0].remoteAddress = "192.0.2.1"
assert.equal(classify(f).verdict, "unknown")
})
test("budget exact fit is cumulative across phases and cannot return to forward", () => {
let budget = createRoutingNetworkBudget(start, [start + 120000], start, { requests: 3, bytes: 30, rows: 3 })
let spent = spendRoutingNetworkBudget(budget, "forward", start + 1, { requests: 2, bytes: 20, rows: 2 }); assert(spent.accepted); budget = spent.budget
spent = spendRoutingNetworkBudget(budget, "inverse", start + 2, { requests: 1, bytes: 10, rows: 1 }); assert(spent.accepted)
assert.deepEqual(spent.budget.used, { requests: 3, bytes: 30, rows: 3 }); assert.equal(spent.budget.deadline, start + 120000)
assert.equal(spendRoutingNetworkBudget(spent.budget, "inverse", start + 3, { requests: 1, bytes: 0, rows: 0 }).accepted, false)
assert.equal(spendRoutingNetworkBudget(spent.budget, "forward", start + 3, { requests: 0, bytes: 0, rows: 0 }).accepted, false)
})
test("short by one requests/bytes/rows, clock rollback, deadline and malformed spend permanently exhaust the budget value", () => {
for (const work of [{ requests: 2, bytes: 0, rows: 0 }, { requests: 0, bytes: 2, rows: 0 }, { requests: 0, bytes: 0, rows: 2 }, { requests: -1, bytes: 0, rows: 0 }]) {
const spent = spendRoutingNetworkBudget(createRoutingNetworkBudget(start, [start + 1000], start, { requests: 1, bytes: 1, rows: 1 }), "forward", start + 1, work)
assert.equal(spent.accepted, false); assert.equal(spent.budget.exhausted, true)
assert.equal(spendRoutingNetworkBudget(spent.budget, "inverse", start + 2, { requests: 0, bytes: 0, rows: 0 }).accepted, false)
}
const budget = createRoutingNetworkBudget(start, [start + 1000], start + 10)
assert.equal(spendRoutingNetworkBudget(budget, "forward", start + 9, { requests: 0, bytes: 0, rows: 0 }).accepted, false)
assert.equal(spendRoutingNetworkBudget(budget, "inverse", start + 1000, { requests: 0, bytes: 0, rows: 0 }).accepted, false)
})
test("all original deadlines cap120seconds; malformed/future initialization and expired classification fail closed", () => {
assert.equal(createRoutingNetworkBudget(start, [start + 300000], start).deadline, start + 120000)
assert.equal(createRoutingNetworkBudget(start, [start + 300000, start + 500], start).deadline, start + 500)
for (const deadlines of [[], [NaN], [Infinity], [start]]) assert.throws(() => createRoutingNetworkBudget(start, deadlines, start))
assert.throws(() => createRoutingNetworkBudget(start, [start + 1000], start - 1))
const f = fixture(); assert.equal(classifyRoutingNetwork(f.manifest, f.rounds, f.manifest.deadline, f.budget).verdict, "unknown")
})
test("deep capture isolates external manifest/round/limit/deadline mutation; no capability or security proof is minted", () => {
const f = fixture(), classifier = createRoutingNetworkClassifier(f.manifest), captured = captureRoutingNetworkRounds(f.rounds)
const limits = { requests: 4, bytes: 50, rows: 4 }, deadlines = [start + 1000]
const budget = createRoutingNetworkBudget(start, deadlines, start, limits)
f.manifest.configuration.bodyIdentity = "tampered"; f.rounds[0].routes[0].active = false
limits.requests = 400; deadlines[0] = start + 300000
assert.equal(classifier.classify(captured, now, f.budget).verdict, "passed")
assert.equal(budget.limits.requests, 4); assert.equal(budget.deadline, start + 1000)
assert.throws(() => { captured[0].configuration.bodyIdentity = "tampered" }, TypeError)
assert.throws(() => { classifier.manifest.routes[0].resolutionChain.push({ address: "192.0.2.3", table: "main", interface: "wan1" }) }, TypeError)
assert(Object.isFrozen(captureRoutingNetworkManifest(fixture().manifest).logs[0].relatedKeys))
})