diff --git a/backend/package.json b/backend/package.json index 98e792de..75ca7285 100644 --- a/backend/package.json +++ b/backend/package.json @@ -183,7 +183,7 @@ "test:traffic-flow:read-budget": "tsx --test src/services/traffic-flow-read-budget.test.ts src/modules/mcp/flow-read-quality.test.ts && node scripts/test-flow-read-adapters.mjs", "test:traffic-flow:read-http:pg": "node scripts/test-flow-read-http-owned.mjs", "test:traffic-flow:read-source:pg": "tsx scripts/test-flow-read-sql-owned.mts", - "test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts", + "test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts src/services/bgp-rib-observation.test.ts", "test:mcp:routing-baseline:pg": "node scripts/test-routing-controller-baseline.mjs", "test:mcp:routing-baseline-inverse:pg": "node scripts/test-routing-controller-baseline.mjs --default-scoped", "test:sqlite-import-control:pg": "node scripts/test-sqlite-import-control-postgres.mjs", diff --git a/backend/src/modules/mcp/bgp-prefix-actions.ts b/backend/src/modules/mcp/bgp-prefix-actions.ts index c2a9bdf1..9611544b 100644 --- a/backend/src/modules/mcp/bgp-prefix-actions.ts +++ b/backend/src/modules/mcp/bgp-prefix-actions.ts @@ -1,10 +1,12 @@ import { z } from "zod" import { hasPermission } from "../../lib/permissions.js" import { bgpPrefixRows } from "../../services/bgp-prefix-model.js" +import { BgpRibChanged, bgpRibSelection, readBgpRib } from "../../services/bgp-rib-observation.js" import { nativeBgpRows } from "../../services/bgp-export-model.js" import { getServerRowById } from "../servers/repository/servers-repository.js" import { routerClient } from "./resources.js" import { effectiveMcpConnection } from "./store.js" +import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js" import { fingerprint, McpError } from "./security.js" import type { ActionContext } from "./action-types.js" import type { add } from "./actions.js" @@ -17,6 +19,27 @@ async function access(context: ActionContext) { if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область чтения BGP изменилась", 409) } export function registerBgpPrefixActions(register: typeof add) { + const observation = bgpRibSelection.extend({ serverId: z.number().int().positive().safe() }) + register("routing.bgp.rib.read", "mm_bgp_rib_get", "Нативная IPv4 BGP RIB по таблице: count-only или страницы всех путей, включая filtered. В следующих страницах передавайте expectedFingerprint первой страницы", "bgp", permissions, "read", "servers", observation, { read: async (input, context) => { + const { serverId, ...selection } = observation.parse(input) + await access(context) + const source = await createRoutingSourceContext(await readRoutingEndpoints([serverId])) + if (source.expected.length !== 1) throw new McpError("DEVICE_UNAVAILABLE", "Источник RIB недоступен", 409) + const check = async () => { await access(context); await source.assertCurrent() } + try { + await check() + const { client } = await routerClient(serverId) + const startedAt = new Date().toISOString() + const result = await readBgpRib(client, selection, check, context.signal) + await check() + return { serverId, ...result, startedAt, observedAt: new Date().toISOString(), timestampKind: "backend-receipt", forwardingVerified: false } + } catch (error) { + await check() + if (error instanceof McpError) throw error + if (error instanceof BgpRibChanged) throw new McpError("STATE_CONFLICT", "Состояние RIB изменилось; повторите чтение с первой страницы", 409) + throw new McpError("STATE_UNAVAILABLE", "Полнота нативного чтения IPv4 BGP RIB не подтверждена", 409) + } + } }) register("routing.bgp.prefixes.read", "mm_bgp_prefixes_get", "Наблюдаемые BGP-префиксы IPv4/IPv6 в явной таблице; active nullable, без доказательства forwarding или attribution к peer", "bgp", permissions, "read", "servers", z.object({ serverId: z.number().int().positive().safe(), family: z.enum(["ipv4", "ipv6"]).default("ipv4"), table: z.string().trim().min(1).max(100).refine(value => !/[\u0000-\u001f\u007f]/.test(value)).default("main"), diff --git a/backend/src/services/bgp-rib-observation.test.ts b/backend/src/services/bgp-rib-observation.test.ts new file mode 100644 index 00000000..f1bcba4d --- /dev/null +++ b/backend/src/services/bgp-rib-observation.test.ts @@ -0,0 +1,130 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { readBgpRib } from "./bgp-rib-observation.js" + +const table = "rtab-antiblock" +const primary = "*B000001" +const standby = "*B000002" +const selection = { table, mode: "page" as const, limit: 500, offset: 0 } + +function route(index: number, overrides: Record = {}): Record { + return { + ".id": "*" + (index + 1).toString(16).toUpperCase(), + afi: "ip", bgp: "true", dynamic: "true", "routing-table": table, + "dst-address": `198.18.${Math.floor(index / 256)}.${index % 256}/32`, + contribution: "active", active: "true", "bgp.peer-cache-id": primary, + gateway: "10.255.255.100", "immediate-gw": "10.253.250.1%gre-jh-test-msk", + ...overrides, + } +} + +function fixture(rows: Record[]) { + const reads = { routePages: 0, counts: 0 } + const client = { + async get(path: string, _timeout?: number, _signal?: AbortSignal, maxResponseBytes?: number) { + assert((maxResponseBytes ?? 8 * 1024 * 1024) <= 8 * 1024 * 1024, "MikrotikClient rejects GET limits above 8 MiB") + const { pathname, searchParams } = new URL(path, "http://router.invalid") + if (pathname === "/routing/table") return [{ ".id": "*1", name: table }] as T + assert.equal(pathname, "/routing/route") + assert(!searchParams.has("bgp") && !searchParams.has("afi"), "Independent RIB read must include unclassified rows") + assert.equal(searchParams.get("routing-table"), table) + reads.routePages++ + const properties = searchParams.get(".proplist")?.split(",") + assert(properties) + return rows.filter(row => row["routing-table"] === table) + .map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key)))) as T + }, + async post(path: string, body: Record) { + assert.equal(path, "/routing/route/print") + assert.equal(body["count-only"], "") + const query = body[".query"] + assert(Array.isArray(query)) + const peer = query.find(word => word.startsWith("bgp.peer-cache-id="))?.split("=")[1] + assert.deepEqual(query, [ + "routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|", + ...(peer ? ["bgp.peer-cache-id=" + peer] : []), + ]) + reads.counts++ + const count = rows.filter(row => + row["routing-table"] === table && row.bgp === "true" && (row.afi === "ip" || row.afi === "ip4") && + (!peer || row["bgp.peer-cache-id"] === peer), + ).length + return { ret: String(count) } as T + }, + } + return { client, reads } +} + +test("positive native count is cheap; a verified zero independently reads the target table", async () => { + const nonempty = fixture([route(0)]) + assert.equal((await readBgpRib(nonempty.client, { ...selection, mode: "count" })).total, 1) + assert.equal(nonempty.reads.routePages, 0) + const { client, reads } = fixture([route(0, { "routing-table": "main" }), route(1, { afi: "ip6", "dst-address": "2001:db8::/32" })]) + const result = await readBgpRib(client, { ...selection, mode: "count" }) + assert.equal(result.total, 0) + assert(reads.counts > 0) + assert.equal(reads.routePages, 1) + + for (const invalid of [[], {}, { ret: "" }, { ret: "0oops" }, { ret: "-1" }]) { + const broken = { ...client, post: async () => invalid as T } + await assert.rejects(readBgpRib(broken, { ...selection, mode: "count" })) + } +}) + +test("zero fails closed on a missed IPv4 BGP route or ambiguous native BGP evidence", async () => { + const staticRow = { ".id": "*70", afi: "ip", static: "true", "routing-table": table, "dst-address": "198.18.250.1/32", contribution: "active", active: "true" } + const justStatic = fixture([staticRow]) + assert.equal((await readBgpRib(justStatic.client, { ...selection, mode: "count" })).total, 0) + assert.equal(justStatic.reads.routePages, 1) + for (const ambiguous of [route(0), { ...staticRow, "bgp.peer-cache-id": primary }, { ...staticRow, "belongs-to": "BGP IP routes from 192.0.2.1" }]) { + const { client } = fixture([ambiguous]) + const wrongZero = { ...client, post: async () => ({ ret: "0" }) as T } + await assert.rejects(readBgpRib(wrongZero, { ...selection, mode: "count" })) + } +}) + +test("matching peer paths include filtered and inactive alternatives with distinct IDs", async () => { + const filtered = route(1, { "dst-address": "198.18.0.0/32", contribution: "filtered", filtered: "true", active: "false", "bgp.peer-cache-id": standby }) + const candidate = route(2, { afi: "ip4", contribution: "candidate", active: "false" }) + const { client } = fixture([route(0), filtered, candidate, route(3, { afi: "ip6", "dst-address": "2001:db8::/32" })]) + const result = await readBgpRib(client, selection) + assert.equal(result.total, 3) + assert(result.items) + const samePrefix = result.items.filter(item => item.prefix === "198.18.0.0/32") + assert.equal(samePrefix.length, 2) + assert.equal(new Set(samePrefix.map(item => item.id)).size, 2) + assert.equal(samePrefix.find(item => item.peerCacheId === standby)?.filtered, true) + assert.equal(result.items.find(item => item.id === candidate[".id"])?.active, false) + const otherPeer = await readBgpRib(client, { ...selection, peerCacheId: standby }) + assert.equal(otherPeer.total, 1) + assert.equal(otherPeer.items?.[0]?.id, filtered[".id"]) +}) + +test("missing table and missing peer attribution cannot prove a scoped zero", async () => { + const { client } = fixture([]) + const missingTable = { ...client, get: async () => [] as T } + await assert.rejects(readBgpRib(missingTable, { ...selection, mode: "count" }), /table/i) + const unknownPeer = route(0) + delete unknownPeer["bgp.peer-cache-id"] + const result = await readBgpRib(fixture([unknownPeer]).client, selection) + assert.equal(result.items?.[0].peerCacheId, null) + await assert.rejects(readBgpRib(fixture([unknownPeer]).client, { ...selection, mode: "count", peerCacheId: standby }), /peer/i) +}) + +test("pages beyond 13,000 preserve snapshot identity and reject a changed next page", async () => { + const rows = Array.from({ length: 13_705 }, (_, i) => route(i)) + const { client } = fixture(rows) + const first = await readBgpRib(client, selection) + assert.equal(first.total, rows.length) + assert.equal(first.items?.length, selection.limit) + assert.equal(first.nextOffset, selection.limit) + assert(first.fingerprint) + rows.reverse() + const tailSelection = { ...selection, offset: 13_700, expectedFingerprint: first.fingerprint } + const tail = await readBgpRib(client, tailSelection) + assert.equal(tail.items?.length, 5) + assert.equal(tail.nextOffset, null) + assert.equal(tail.fingerprint, first.fingerprint) + rows[0] = { ...rows[0], gateway: "10.255.255.101" } + await assert.rejects(readBgpRib(client, tailSelection)) +}) diff --git a/backend/src/services/bgp-rib-observation.ts b/backend/src/services/bgp-rib-observation.ts new file mode 100644 index 00000000..401dddd3 --- /dev/null +++ b/backend/src/services/bgp-rib-observation.ts @@ -0,0 +1,114 @@ +import { createHash } from "node:crypto" +import { isIP } from "node:net" +import { z } from "zod" +import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" +import type { MikrotikClient } from "./mikrotik.js" + +const rosId = z.string().regex(/^\*[0-9a-z]+$/i).max(64) +export const bgpRibSelection = z.object({ + table: z.string().min(1).max(100).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name)), + peerCacheId: rosId.optional(), + mode: z.enum(["count", "page"]).default("count"), + offset: z.number().int().min(0).max(100_000).default(0), + limit: z.number().int().min(1).max(500).default(100), + expectedFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(), +}).strict() + +const nativeRow = z.record(z.string(), z.unknown()) +const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"] +const properties = [".id", "afi", "dst-address", "routing-table", "bgp", "bgp.peer-cache-id", "bgp.session", "belongs-to", "contribution", "active", "filtered", "gateway", "immediate-gw", ...otherProtocols].join(",") +const otherFamilies = new Set(["ip6", "ipv6", "link", "vpnv4", "vpnv6", "l2vpn", "l2vpn-cisco", "l2vpn-link", "evpn", "mip4", "mip6"]) +type Selection = z.infer +const text = z.string().max(512) +export class BgpRibChanged extends Error {} +const contributions = new Set(["active", "filtered", "candidate", "best-candidate", "unreachable"]) + +function optionalFlag(value: unknown) { + if (value === undefined) return null + if (value === true || value === "true" || value === "yes") return true + if (value === false || value === "false" || value === "no") return false + throw new Error("Unrecognized RouterOS flag") +} + +function ipv4Row(row: Record, table: string) { + if (row["routing-table"] !== table) throw new Error("Unexpected native route table") + if (otherFamilies.has(String(row.afi))) return null + if (row.afi !== "ip" && row.afi !== "ip4") throw new Error("Unrecognized RouterOS address family") + const bgp = optionalFlag(row.bgp) + const other = otherProtocols.some(key => optionalFlag(row[key]) === true) + if (bgp !== true) { + // Missing origin flags occur on some RouterOS REST projections. Do not lose filtered paths or certify a false zero. + if (row["bgp.peer-cache-id"] || row["bgp.session"] || /\bbgp\b/i.test(String(row["belongs-to"] ?? "")) || bgp === null && !other) throw new Error("Unconfirmed native route origin") + return null + } + if (other) throw new Error("Conflicting native route origins") + const dst = text.parse(row["dst-address"]) + const prefix = isIP(dst) === 4 ? dst + "/32" : dst + if (isIP(prefix.split("/")[0]) !== 4 || canonicalBgpPolicyPrefix(prefix) !== prefix) throw new Error("Invalid IPv4 destination") + const id = rosId.parse(row[".id"]) + const peerCacheId = row["bgp.peer-cache-id"] === undefined ? null : rosId.parse(row["bgp.peer-cache-id"]) + const contribution = text.nullable().parse(row.contribution ?? null) + const activeFlag = optionalFlag(row.active), filteredFlag = optionalFlag(row.filtered) + const known = contribution !== null && contributions.has(contribution) + if (known && (activeFlag !== null && activeFlag !== (contribution === "active") || + filteredFlag !== null && filteredFlag !== (contribution === "filtered"))) throw new Error("Conflicting native route flags") + return { + id, prefix, table, peerCacheId, contribution, + active: activeFlag ?? (known ? contribution === "active" : null), + filtered: filteredFlag ?? (known ? contribution === "filtered" : null), + session: text.nullable().parse(row["bgp.session"] ?? null), + gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null), + } +} + +/** Counts run on RouterOS. Page offsets use deterministic route IDs and a digest over the full selection. */ +export async function readBgpRib(client: Pick, input: Selection, + beforeRead: () => Promise = async () => {}, signal?: AbortSignal) { + const { table, peerCacheId, mode, limit, offset, expectedFingerprint } = bgpRibSelection.parse(input) + if (offset > 0 && !expectedFingerprint || mode === "count" && (offset || expectedFingerprint)) throw new Error("Invalid RIB page cursor") + const query = ["routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|"] + const tablePath = "/routing/table?.proplist=.id,name,disabled,invalid&name=" + encodeURIComponent(table) + const tableIdentity = async () => { + const raw = await client.get(tablePath, 10_000, signal, 16_384, beforeRead) + if (!Array.isArray(raw) || raw.length !== 1) throw new Error("Missing or ambiguous routing table") + const row = nativeRow.parse(raw[0]) + if (row.name !== table || optionalFlag(row.disabled) || optionalFlag(row.invalid)) throw new Error("Routing table unavailable") + return rosId.parse(row[".id"]) + } + const nativeCount = async (peer?: string) => { + const filter = peer ? [...query, "bgp.peer-cache-id=" + peer] : query + const raw = await client.post("/routing/route/print", { "count-only": "", ".query": filter }, 15_000, signal, beforeRead) + const { ret } = z.object({ ret: z.string().regex(/^(?:0|[1-9]\d{0,14})$/) }).strict().parse(raw) + return Number(ret) + } + const identity = await tableIdentity() + const allCount = await nativeCount() + type Item = NonNullable> + let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null + if (mode === "page" || peerCacheId || allCount === 0) { + if (allCount > 100_000) throw new Error("RIB row limit exceeded") + const path = "/routing/route?.proplist=" + properties + "&routing-table=" + encodeURIComponent(table) + const raw = await client.get(path, 30_000, signal, 8 * 1024 * 1024, beforeRead) + if (!Array.isArray(raw) || raw.length > 100_000) throw new Error("Invalid or oversized RIB view") + const ids = new Set(), selected: Item[] = [] + for (const rawRow of raw) { + const observed = ipv4Row(nativeRow.parse(rawRow), table) + if (!observed) continue + if (ids.has(observed.id)) throw new Error("Duplicate native RIB identity") + ids.add(observed.id) + if (peerCacheId && !observed.peerCacheId) throw new Error("Native peer identity unavailable") + if (!peerCacheId || observed.peerCacheId === peerCacheId) selected.push(observed) + } + if (allCount !== ids.size || selected.length !== await nativeCount(peerCacheId)) throw new BgpRibChanged("Native RIB count changed or view incomplete") + total = selected.length + if (mode === "page") { + selected.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0) + fingerprint = createHash("sha256").update(JSON.stringify([table, identity, peerCacheId ?? null, selected])).digest("hex") + if (expectedFingerprint && fingerprint !== expectedFingerprint || offset > total) throw new BgpRibChanged("RIB snapshot changed; restart at offset 0") + items = selected.slice(offset, offset + limit) + nextOffset = offset + items.length < total ? offset + items.length : null + } + } + if (identity !== await tableIdentity()) throw new BgpRibChanged("Routing table changed during observation") + return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false } +}