Files
MikrotikManager/backend/src/services/ospf-route-proof.ts
T

81 lines
5.7 KiB
TypeScript

import { isIP } from "node:net"
import { z } from "zod"
import type { MikrotikClient } from "./mikrotik.js"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { observedBoolean, observedInteger } from "./ospf-observed-values.js"
export class OspfRouteProofError extends Error {}
const inactiveContributions = new Set<unknown>(["filtered", "unreachable", "candidate", "best-candidate"])
const flag = (value: unknown) => observedBoolean(typeof value === "boolean" ? String(value) : typeof value === "string" ? value : undefined)
const nativeRows = z.array(z.record(z.string(), z.unknown())).max(10000)
const nonIpRouteFamilies = new Set<unknown>(["link", "vpnv4", "vpnv6", "l2vpn", "l2vpn-cisco", "l2vpn-link", "evpn", "mip4", "mip6"])
export function canonicalOspfRouteProofPrefix(value: unknown) {
if (typeof value !== "string") return null
try { return canonicalBgpPolicyPrefix(value) } catch { return null }
}
async function readBoundedRows(client: Pick<MikrotikClient, "get">, path: string, beforeRead: () => Promise<unknown>) {
await beforeRead()
const raw = await client.get<unknown>(path, 10_000, undefined, 1_048_576)
if (Buffer.byteLength(JSON.stringify(raw) ?? "") > 1048576) throw new OspfRouteProofError("OSPF RIB proof exceeds 1 MiB")
const rows = nativeRows.parse(raw)
if (rows.some(row => typeof row[".id"] !== "string" || !row[".id"]) || new Set(rows.map(row => row[".id"])).size !== rows.length) throw new OspfRouteProofError("Invalid OSPF RIB identities")
return rows
}
export async function readOspfRouteAbsence(client: Pick<MikrotikClient, "get">, selection: { prefix: string; table: string }, beforeRead: () => Promise<unknown>) {
const prefix = canonicalOspfRouteProofPrefix(selection.prefix)
if (!prefix || !selection.table || selection.table.length > 200) throw new OspfRouteProofError("Invalid OSPF route absence context")
const routes = await readBoundedRows(client, "/routing/route", beforeRead)
for (const row of routes) {
const observed = row["dst-address"]
const scoped = typeof observed === "string" ? /^([0-9a-f:]+)%[^/%]+(\/\d+)$/i.exec(observed) : null
const destination = canonicalOspfRouteProofPrefix(scoped ? scoped[1] + scoped[2] : observed)
if (destination === null && nonIpRouteFamilies.has(row.afi)) continue
const table = row["routing-table"]
const unknownTable = typeof table !== "string" || !table.trim()
if ((unknownTable || table === selection.table) && (destination === null || destination === prefix)) {
throw new OspfRouteProofError("A matching route is present or cannot be excluded")
}
}
const tables = await readBoundedRows(client, "/routing/table?.proplist=.id,name,disabled,invalid", beforeRead)
const matching = tables.filter(row => row.name === selection.table)
if (matching.length !== 1 || ["disabled", "invalid"].some(key => matching[0][key] !== undefined && flag(matching[0][key]) !== false)) throw new OspfRouteProofError("Routing table is absent, disabled, invalid or ambiguous")
await beforeRead()
return { prefix, table: selection.table, absenceVerified: true as const }
}
/** A bounded operational proof. Missing protocol/active/metric values require native receipts. */
export async function readOspfRouteProof(client: Pick<MikrotikClient, "get" | "post">, selection: { prefix: string; table: string; interface: string }, beforeRead: () => Promise<unknown> = async () => {}) {
const prefix = canonicalOspfRouteProofPrefix(selection.prefix)
if (!prefix || !selection.table || !selection.interface || selection.table.length > 200 || selection.interface.length > 200) throw new OspfRouteProofError("Invalid OSPF route proof context")
const family = isIP(prefix.split("/")[0])
const rows = await readBoundedRows(client, "/routing/route", beforeRead)
const matches = rows.filter(row => {
if (row["routing-table"] !== selection.table || canonicalOspfRouteProofPrefix(row["dst-address"]) !== prefix) return false
const active = flag(row.active)
if (active === false && row.contribution === undefined) return false
if ((active === false || row.active === undefined || row.active === "") && inactiveContributions.has(row.contribution)) return false
return true
})
if (matches.length !== 1) throw new OspfRouteProofError("OSPF route is missing or ambiguous")
const row = matches[0]
const property = async (key: string) => {
if (row[key] !== undefined && row[key] !== "") return row[key]
if (!/^\*[a-z0-9]+$/i.test(String(row[".id"]))) throw new OspfRouteProofError("Invalid native route getter identity")
await beforeRead()
return (await client.post<{ ret?: unknown }>("/routing/route/get", { ".id": String(row[".id"]), "value-name": key })).ret
}
if (flag(await property("ospf")) !== true || flag(await property("active")) !== true || row.contribution !== undefined && row.contribution !== "active") throw new OspfRouteProofError("Active OSPF route not confirmed")
const value = await property("ospf.metric")
const metric = observedInteger(typeof value === "number" ? String(value) : typeof value === "string" ? value : undefined, 0, 0xffffff)
if (metric === null) throw new OspfRouteProofError("OSPF route metric not confirmed")
const gateway = typeof row["immediate-gw"] === "string" ? row["immediate-gw"] : ""
const context = /^([^%@]+)%([^@]+)(?:@([^@]+))?$/.exec(gateway)
if (!context || isIP(context[1]) !== family || context[2] !== selection.interface || context[3] && context[3] !== selection.table) throw new OspfRouteProofError("OSPF route does not resolve through the selected interface/VRF")
await beforeRead()
return { id: String(row[".id"]), family: family === 4 ? "ipv4" : "ipv6", prefix: selection.prefix, table: selection.table, interface: selection.interface, immediateGateway: gateway, ospf: true, active: true, metric }
}