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

241 lines
23 KiB
TypeScript

import { isIP } from "node:net"
import { z } from "zod"
import { canonicalBgpPolicyPrefix } from "../../services/bgp-community-policy-model.js"
/** Inert classification only. These values are not signed observations,
* authority, a native grant, or proof that a caller collected complete data. */
const key = z.string().min(1).max(128).regex(/^[a-zA-Z0-9_.:*@/-]+$/)
const clock = z.number().int().safe().nonnegative()
const ip = z.string().max(45).refine(value => {
try { return !!isIP(value) && canonicalBgpPolicyPrefix(value + "/" + (isIP(value) === 4 ? 32 : 128)).split("/")[0] === value } catch { return false }
})
const family = z.enum(["ipv4", "ipv6"])
const named = z.string().min(1).max(128).regex(/^[^\s\x00-\x1f]+$/)
const identity = z.object({ operationId: z.string().uuid(), stepIndex: z.literal(0), profileId: z.string().uuid(), profileVersion: z.number().int().positive().safe(), sourceEpoch: key, authorityIdentity: key }).strict()
const prefix = z.string().max(49).refine(value => {
try { return canonicalBgpPolicyPrefix(value) === value } catch { return false }
})
const hop = z.object({ address: ip, table: named, interface: named }).strict()
const route = z.object({ key, serverId: z.number().int().positive(), family, prefix, table: named, sessionKey: key,
nextHop: ip, interface: named, resolverTable: named, resolutionChain: z.array(hop).min(1).max(8) }).strict()
const bgp = z.object({ key, serverId: z.number().int().positive(), connectionId: key, instance: named, family,
localAddress: ip, remoteAddress: ip, remoteAsn: z.number().int().min(1).max(4294967295) }).strict()
const bfdCommon = { key, serverId: z.number().int().positive(), configurationIdentity: key }
const bfd = z.discriminatedUnion("applicability", [
z.object({ ...bfdCommon, applicability: z.literal("required"), localAddress: ip, remoteAddress: ip, interface: named, vrf: named }).strict(),
z.object({ ...bfdCommon, applicability: z.literal("not-applicable"), reason: z.literal("not-configured") }).strict(),
])
const probe = z.object({ key, serverId: z.number().int().positive(), family, destination: ip, source: ip, interface: named, probeVrf: named,
expectedHops: z.array(ip).min(1).max(16) }).strict()
const topic = z.enum(["bgp", "bfd", "route", "interface"])
const logScope = z.object({ key, serverId: z.number().int().positive(), generation: key, sequenceMode: z.literal("contiguous-capture"), afterSequence: clock,
topics: z.array(topic).min(1).max(4), relatedKeys: z.array(key).min(1).max(64) }).strict()
const configuration = z.object({ serverId: z.number().int().positive(), nativeId: key, table: named, bodyIdentity: key, dependencyIdentity: key }).strict()
const unique = <T>(values: T[], identityOf: (value: T) => string) => new Set(values.map(identityOf)).size === values.length
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
const sameIp = (a: string, b: string) => isIP(a) === isIP(b) && a.toLowerCase() === b.toLowerCase()
export const routingNetworkManifestSchema = z.object({ revision: z.literal(1), phase: z.enum(["forward", "inverse"]), identity,
sourceCreatedAt: clock, deadline: clock, observationStartAt: clock, maximumSampleAgeMs: z.number().int().min(1).max(30000),
serverIds: z.array(z.number().int().positive()).min(1).max(32), configuration,
routes: z.array(route).min(1).max(32), bgp: z.array(bgp).min(1).max(32), bfd: z.array(bfd).min(1).max(32),
probes: z.array(probe).min(1).max(8), logs: z.array(logScope).min(1).max(32),
}).strict().superRefine((value, ctx) => {
const reject = (message: string) => ctx.addIssue({ code: "custom", message })
if (value.deadline <= value.sourceCreatedAt || value.deadline > value.sourceCreatedAt + 120000 || value.observationStartAt < value.sourceCreatedAt || value.observationStartAt >= value.deadline) reject("invalid original execution window")
if (!unique(value.serverIds, String) || !same(value.serverIds, [...value.serverIds].sort((a, b) => a - b))) reject("scope must be sorted and unique")
const groups: Array<Array<{ key: string; serverId: number }>> = [value.routes, value.bgp, value.bfd, value.probes, value.logs]
if (groups.some(group => !unique(group, entry => entry.key))) reject("duplicate manifest keys")
if (!value.serverIds.includes(value.configuration.serverId) || groups.some(group => group.some(entry => !value.serverIds.includes(entry.serverId)))) reject("manifest outside scope")
if (!unique(groups.flat(), entry => entry.key)) reject("stage keys must be globally unique")
if (!unique(value.routes, entry => [entry.serverId, entry.family, entry.prefix, entry.table].join("|")) || !unique(value.bgp, entry => [entry.serverId, entry.connectionId, entry.instance, entry.family].join("|")) || !unique(value.logs, entry => String(entry.serverId))) reject("ambiguous target mapping")
const expectedKeys = new Set([...value.routes, ...value.bgp, ...value.bfd, ...value.probes].map(entry => entry.key))
if (value.logs.some(scope => !unique(scope.topics, String) || !unique(scope.relatedKeys, String) || scope.relatedKeys.some(id => !expectedKeys.has(id)))) reject("log selectors are ambiguous")
if (value.serverIds.some(id => !value.logs.some(scope => scope.serverId === id))) reject("every source requires log coverage")
for (const scope of value.logs) {
const serverKeys = [...value.routes, ...value.bgp, ...value.bfd, ...value.probes].filter(entry => entry.serverId === scope.serverId).map(entry => entry.key).sort()
if (!same([...scope.relatedKeys].sort(), serverKeys)) reject("logs must cover exact same-server stage keys")
const requiredTopics = [value.routes.some(entry => entry.serverId === scope.serverId) ? "route" : null,
value.bgp.some(entry => entry.serverId === scope.serverId) ? "bgp" : null,
value.bfd.some(entry => entry.serverId === scope.serverId && entry.applicability === "required") ? "bfd" : null,
value.probes.some(entry => entry.serverId === scope.serverId) ? "interface" : null].filter(Boolean)
if (requiredTopics.some(required => !scope.topics.some(actual => actual === required))) reject("missing relevant log topics")
}
for (const entry of value.routes) {
if (isIP(entry.prefix.split("/")[0]) !== (entry.family === "ipv4" ? 4 : 6) || isIP(entry.nextHop) !== (entry.family === "ipv4" ? 4 : 6) || entry.resolutionChain.some(link => isIP(link.address) !== (entry.family === "ipv4" ? 4 : 6))) reject("route AFI mismatch")
if (!value.bgp.some(session => session.key === entry.sessionKey && session.serverId === entry.serverId && session.family === entry.family)) reject("route has no exact BGP session")
if (!unique(entry.resolutionChain, link => link.address.toLowerCase() + "/" + link.table)) reject("recursive cycle")
const last = entry.resolutionChain.at(-1)!
if (entry.resolutionChain[0].table !== entry.resolverTable || last.address !== entry.nextHop || last.interface !== entry.interface) reject("resolution chain does not terminate at exact nexthop")
}
for (const entry of value.bfd) if (entry.applicability === "required" && isIP(entry.localAddress) !== isIP(entry.remoteAddress)) reject("BFD AFI mismatch")
for (const entry of [...value.bgp, ...value.probes]) {
const addresses = "destination" in entry ? [entry.destination, entry.source, ...entry.expectedHops] : [entry.localAddress, entry.remoteAddress]
if (addresses.some(address => isIP(address) !== (entry.family === "ipv4" ? 4 : 6))) reject("probe/session AFI mismatch")
if ("destination" in entry && !sameIp(entry.expectedHops.at(-1)!, entry.destination)) reject("trace must end at exact destination")
if ("destination" in entry && !unique(entry.expectedHops, String)) reject("ambiguous expected probe path")
}
})
export type RoutingNetworkManifest = z.infer<typeof routingNetworkManifestSchema>
const observedRoute = route.extend({ active: z.boolean(), resolved: z.boolean(), protocol: z.enum(["bgp", "static", "ospf", "connected"]),
resolutionChain: z.array(hop.extend({ resolved: z.boolean() }).strict()).min(1).max(8) }).strict()
const observedBgp = bgp.extend({ state: z.enum(["established", "not-established", "idle", "connect", "active", "opensent", "openconfirm", "disabled", "unknown"]) }).strict()
const observedBfd = z.discriminatedUnion("applicability", [
z.object({ ...bfdCommon, applicability: z.literal("required"), localAddress: ip, remoteAddress: ip, interface: named, vrf: named,
state: z.enum(["up", "down", "init", "admin-down", "unknown"]) }).strict(),
z.object({ ...bfdCommon, applicability: z.literal("not-applicable"), reason: z.literal("not-configured"), configured: z.literal(false) }).strict(),
]).refine(value => value.applicability !== "required" || isIP(value.localAddress) === isIP(value.remoteAddress), "BFD AFI mismatch")
const trace = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("observed"), hops: z.array(z.object({ hop: z.number().int().min(1).max(16), address: ip.nullable(), state: z.enum(["responded", "timeout", "unsupported"]) }).strict()).min(1).max(16) }).strict(),
z.object({ kind: z.literal("not-run"), reason: z.literal("terminal-ping-failure") }).strict(),
])
const observedProbe = probe.extend({ sent: z.number().int().min(0).max(3), received: z.number().int().min(0).max(3), terminal: z.boolean(), trace }).strict()
const logRow = z.object({ sequence: clock, timestamp: clock, topics: z.array(topic).min(1).max(4), relatedKey: key,
event: z.enum(["up", "down", "route-withdrawn", "route-unresolved", "authentication-failure", "informational", "unparsed"]),
severity: z.enum(["info", "warning", "error", "critical"]) }).strict()
const observedLogs = logScope.extend({ coverageStartAt: clock, coveredUntil: clock, capturedAt: clock, toSequence: clock,
responseRowCount: z.number().int().min(0).max(200), moreAvailable: z.boolean(), rotationDetected: z.boolean(), clockSynchronized: z.boolean(),
rows: z.array(logRow).max(200) }).strict()
export const routingNetworkRoundSchema = z.object({ identity, startedAt: clock, observedAt: clock, configuration,
routes: z.array(observedRoute).max(32), bgp: z.array(observedBgp).max(32), bfd: z.array(observedBfd).max(32),
probes: z.array(observedProbe).max(8), logs: z.array(observedLogs).max(32) }).strict()
export type RoutingNetworkRound = z.infer<typeof routingNetworkRoundSchema>
/** Aggregate counters only. Actual per-response wire-byte/page limits remain
* the future native adapter's responsibility and are not proved here. */
export const routingNetworkBudgetLimits = Object.freeze({ requests: 256, bytes: 8 * 1048576, rows: 10000 })
const workSchema = z.object({ requests: clock, bytes: clock, rows: clock }).strict()
const limitsSchema = z.object({ requests: z.number().int().min(1).max(256), bytes: z.number().int().min(1).max(8 * 1048576), rows: z.number().int().min(1).max(10000) }).strict()
const budgetSchema = z.object({ sourceCreatedAt: clock, deadline: clock, lastAt: clock, phase: z.enum(["forward", "inverse"]), limits: limitsSchema,
used: workSchema, exhausted: z.boolean() }).strict().refine(value => value.deadline > value.sourceCreatedAt && value.deadline <= value.sourceCreatedAt + 120000 && value.lastAt >= value.sourceCreatedAt &&
value.used.requests <= value.limits.requests && value.used.bytes <= value.limits.bytes && value.used.rows <= value.limits.rows)
export type RoutingNetworkBudget = z.infer<typeof budgetSchema>
const frozenBudget = (value: RoutingNetworkBudget): Readonly<RoutingNetworkBudget> => Object.freeze({ ...value, used: Object.freeze({ ...value.used }), limits: Object.freeze({ ...value.limits }) })
function deepFreeze<T>(value: T): T {
if (value && typeof value === "object") { Object.values(value).forEach(deepFreeze); Object.freeze(value) }
return value
}
export function captureRoutingNetworkManifest(raw: unknown): RoutingNetworkManifest { return deepFreeze(routingNetworkManifestSchema.parse(raw)) }
export function captureRoutingNetworkRounds(raw: unknown): RoutingNetworkRound[] { return deepFreeze(z.array(routingNetworkRoundSchema).min(2).max(3).parse(raw)) }
export function createRoutingNetworkClassifier(raw: unknown) {
const manifest = captureRoutingNetworkManifest(raw)
return Object.freeze({ manifest, classify: (rounds: unknown, now: number, budget: unknown) => classifyRoutingNetwork(manifest, rounds, now, budget) })
}
/** No restoration or grant semantics. Integration must retain this original
* state durably; constructing another pure value does not allocate work. */
export function createRoutingNetworkBudget(sourceCreatedAt: number, originalDeadlines: number[], now: number, limits = routingNetworkBudgetLimits): Readonly<RoutingNetworkBudget> {
clock.parse(sourceCreatedAt); clock.parse(now)
z.array(clock).min(1).max(16).parse(originalDeadlines)
const deadline = Math.min(sourceCreatedAt + 120000, ...originalDeadlines)
if (now >= deadline) throw Error("Original network budget expired")
return frozenBudget(budgetSchema.parse({ sourceCreatedAt, deadline, lastAt: now, phase: "forward", limits, used: { requests: 0, bytes: 0, rows: 0 }, exhausted: false }))
}
/** Account before work. A denied spend permanently exhausts this value. */
export function spendRoutingNetworkBudget(raw: RoutingNetworkBudget, phase: "forward" | "inverse", now: number, work: z.infer<typeof workSchema>) {
const budget = budgetSchema.parse(raw), parsed = workSchema.safeParse(work)
const denied = !parsed.success || !Number.isSafeInteger(now) || now < budget.lastAt || now >= budget.deadline || budget.exhausted || budget.phase === "inverse" && phase !== "inverse" || !["forward", "inverse"].includes(phase)
const next = parsed.success ? { requests: budget.used.requests + parsed.data.requests, bytes: budget.used.bytes + parsed.data.bytes, rows: budget.used.rows + parsed.data.rows } : budget.used
const exceeded = Object.keys(budget.limits).some(key => next[key as keyof typeof next] > budget.limits[key as keyof typeof next] || !Number.isSafeInteger(next[key as keyof typeof next]))
if (denied || exceeded) return { accepted: false, budget: frozenBudget({ ...budget, exhausted: true }) }
return { accepted: true, budget: frozenBudget({ ...budget, phase, lastAt: now, used: next }) }
}
type Verdict = "passed" | "failed" | "unknown"
type RoundResult = { verdict: Verdict; reasons: string[]; stability: string }
const byKey = <T extends { key: string }>(entries: T[]) => new Map(entries.map(entry => [entry.key, entry]))
function inspectRound(manifest: RoutingNetworkManifest, sample: RoutingNetworkRound, now: number): RoundResult {
const unknown: string[] = [], failed: string[] = [], stable: unknown[] = []
const uncertain = (reason: string) => unknown.push(reason)
const bad = (reason: string) => failed.push(reason)
if (!same(sample.identity, manifest.identity)) uncertain("mixed-source-identity")
if (sample.startedAt < manifest.observationStartAt || sample.observedAt < sample.startedAt || sample.observedAt > now || sample.observedAt >= manifest.deadline || now - sample.startedAt > manifest.maximumSampleAgeMs) uncertain("stale-future-or-outside-window")
if (!same(sample.configuration, manifest.configuration)) uncertain("configuration-or-dependency-drift")
const compare = <T extends { key: string }, U extends { key: string }>(expected: T[], actual: U[], stage: string, inspect: (wanted: T, got: U) => void) => {
if (expected.length !== actual.length || !unique(actual, entry => entry.key)) { uncertain(stage + ":incomplete-or-duplicate"); return }
const entries = byKey(actual)
for (const wanted of expected) { const got = entries.get(wanted.key); if (!got) uncertain(stage + ":missing"); else inspect(wanted, got) }
}
compare(manifest.routes, sample.routes, "routes", (wanted, got) => {
if (wanted.serverId !== got.serverId || wanted.family !== got.family || wanted.prefix !== got.prefix || wanted.table !== got.table) { uncertain("routes:mixed-identity"); return }
if (!unique(got.resolutionChain, link => link.address.toLowerCase() + "/" + link.table)) { uncertain("routes:recursive-cycle"); return }
const chain = got.resolutionChain.map(({ resolved: _resolved, ...link }) => link)
const healthy = got.active && got.resolved && got.protocol === "bgp" && got.sessionKey === wanted.sessionKey && sameIp(got.nextHop, wanted.nextHop) && got.interface === wanted.interface && got.resolverTable === wanted.resolverTable && same(chain, wanted.resolutionChain) && got.resolutionChain.every(link => link.resolved)
if (!healthy) bad("routes:unconverged")
stable.push(["route", wanted.key, healthy, got.nextHop, got.interface, got.active, got.resolved, got.protocol, got.sessionKey, got.resolverTable, got.resolutionChain])
})
compare(manifest.bgp, sample.bgp, "bgp", (wanted, got) => {
const { state, ...binding } = got
if (!same(wanted, binding)) { uncertain("bgp:mixed-identity"); return }
if (state === "unknown") uncertain("bgp:unsupported-state"); else if (state !== "established") bad("bgp:not-established")
stable.push(["bgp", wanted.key, state])
})
compare(manifest.bfd, sample.bfd, "bfd", (wanted, got) => {
const { state: _state, configured: _configured, ...binding } = got as typeof got & { state?: string; configured?: boolean }
if (!same(wanted, binding)) { uncertain("bfd:applicability-or-identity-drift"); return }
if (got.applicability === "required") {
if (got.state === "unknown") uncertain("bfd:unsupported-state"); else if (got.state !== "up") bad("bfd:not-up")
stable.push(["bfd", got.key, got.state])
} else stable.push(["bfd", got.key, "not-configured", got.configurationIdentity])
})
compare(manifest.probes, sample.probes, "probes", (wanted, got) => {
const { sent, received, terminal, trace, ...binding } = got
if (!same(wanted, binding)) { uncertain("probe:mixed-identity"); return }
if (!terminal || sent !== 3 || received > sent) { uncertain("probe:incomplete-counts"); return }
if (received < sent) {
if (trace.kind !== "not-run") uncertain("probe:inconsistent-terminal-failure"); else bad("probe:terminal-loss")
stable.push(["probe", wanted.key, sent, received, "terminal-loss"]); return
}
if (trace.kind !== "observed" || trace.hops.some((hop, index) => hop.hop !== index + 1 || hop.state !== "responded" || !hop.address)) { uncertain("probe:incomplete-trace"); return }
const addresses = trace.hops.map(hop => hop.address)
if (!same(addresses, wanted.expectedHops)) bad("probe:unexpected-complete-path")
stable.push(["probe", wanted.key, sent, received, addresses])
})
compare(manifest.logs, sample.logs, "logs", (wanted, got) => {
const { coverageStartAt, coveredUntil, capturedAt, toSequence, responseRowCount, moreAvailable, rotationDetected, clockSynchronized, rows, ...binding } = got
if (!same(wanted, binding)) { uncertain("logs:mixed-identity-or-generation"); return }
if (coverageStartAt > manifest.observationStartAt || coveredUntil < sample.observedAt || capturedAt < coveredUntil || capturedAt > now || coveredUntil >= manifest.deadline || toSequence < wanted.afterSequence || moreAvailable || rotationDetected || !clockSynchronized || responseRowCount !== rows.length || !unique(rows, row => String(row.sequence))) { uncertain("logs:incomplete-interval"); return }
// This model supports only a declared contiguous unfiltered capture
// sequence. Raw RouterOS IDs/cursor gaps need an adapter, never guessing.
if (toSequence - wanted.afterSequence !== rows.length || rows.some((row, index) => row.sequence !== wanted.afterSequence + index + 1 || row.timestamp < coverageStartAt || row.timestamp > coveredUntil || !unique(row.topics, String))) { uncertain("logs:malformed-interval"); return }
const relevant = rows.filter(row => wanted.relatedKeys.includes(row.relatedKey) && row.topics.some(topic => wanted.topics.includes(topic)))
if (relevant.some(row => row.event === "unparsed")) uncertain("logs:unsupported-relevant-event")
if (relevant.some(row => ["error", "critical"].includes(row.severity) && ["up", "informational"].includes(row.event))) uncertain("logs:unsupported-event-severity")
const blocking = relevant.filter(row => ["down", "route-withdrawn", "route-unresolved", "authentication-failure"].includes(row.event))
if (blocking.length) bad("logs:blocking-event")
stable.push(["logs", wanted.key, [...new Set(blocking.map(row => row.relatedKey + ":" + row.event))].sort()])
})
return { verdict: unknown.length ? "unknown" : failed.length ? "failed" : "passed", reasons: [...unknown, ...failed], stability: JSON.stringify(stable) }
}
/** No stagePassed flags or caller verdict are accepted. Even a passed result
* is only a classification of supplied data, never authenticated evidence. */
export function classifyRoutingNetwork(manifestRaw: unknown, roundsRaw: unknown, now: number, budgetRaw: unknown): { verdict: Verdict; reasons: string[]; completeRounds: number; securityProof: false; forwardingVerified: false } {
const result = (verdict: Verdict, reasons: string[], completeRounds = 0) => deepFreeze({ verdict, reasons: [...new Set(reasons)], completeRounds, securityProof: false as const, forwardingVerified: false as const })
const manifest = routingNetworkManifestSchema.safeParse(manifestRaw), rounds = z.array(routingNetworkRoundSchema).min(2).max(3).safeParse(roundsRaw), budget = budgetSchema.safeParse(budgetRaw)
if (!manifest.success || !rounds.success || !budget.success || !Number.isSafeInteger(now)) return result("unknown", ["malformed-or-unsupported-input"])
if (budget.data.exhausted || budget.data.sourceCreatedAt !== manifest.data.sourceCreatedAt || budget.data.deadline !== manifest.data.deadline || budget.data.phase !== manifest.data.phase || budget.data.lastAt > now || now >= manifest.data.deadline) return result("unknown", ["budget-or-original-window-unavailable"])
if (rounds.data.some((round, index) => index > 0 && round.startedAt < rounds.data[index - 1].observedAt)) return result("unknown", ["overlapping-or-reordered-rounds"])
const inspected = rounds.data.map(round => inspectRound(manifest.data, round, now))
if (inspected.some(round => round.verdict === "unknown")) return result("unknown", inspected.flatMap(round => round.reasons), inspected.filter(round => round.verdict !== "unknown").length)
// Each round declares a contiguous interval from the same source cursor.
// Later rounds must preserve the events already observed in that interval.
for (let index = 1; index < rounds.data.length; index++) {
const previous = rounds.data[index - 1], current = rounds.data[index]
const currentLogs = new Map(current.logs.map(log => [log.key, log]))
for (const earlier of previous.logs) {
const later = currentLogs.get(earlier.key)
if (!later || later.toSequence < earlier.toSequence || later.coverageStartAt > earlier.coverageStartAt ||
later.coveredUntil < earlier.coveredUntil ||
earlier.rows.some((row, rowIndex) => !same(row, later.rows[rowIndex])) ||
later.rows.slice(earlier.rows.length).some(row => row.timestamp <= earlier.coveredUntil)) {
return result("unknown", ["logs:inconsistent-across-rounds"])
}
}
}
if (!inspected.every(round => round.stability === inspected[0].stability)) return result("unknown", ["unstable-complete-rounds"], inspected.length)
return result(inspected.some(round => round.verdict === "failed") ? "failed" : "passed", inspected.flatMap(round => round.reasons), inspected.length)
}