From 187a0cd45edac36bd9ade901720696d5ef1a3041 Mon Sep 17 00:00:00 2001 From: Denozordec Date: Tue, 1 Dec 2026 22:00:11 +0700 Subject: [PATCH] =?UTF-8?q?fix(mcp):=20=D1=83=D1=87=D0=B8=D1=82=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D1=8C=20=D0=BE=D1=82=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D1=91=D0=BD=D0=BD=D1=83=D1=8E=20=D1=81=D1=82=D0=B0=D1=82=D0=B8?= =?UTF-8?q?=D0=BA=D1=83=20=D0=B8=20=D0=B8=D0=BC=D1=8F=20=D1=81=D0=B5=D1=81?= =?UTF-8?q?=D1=81=D0=B8=D0=B8=20=D0=BF=D1=80=D0=B8=20=D1=87=D1=82=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B8=20RIB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/modules/mcp/bgp-prefix-actions.ts | 4 +- .../src/services/bgp-rib-observation.test.ts | 46 ++++++++++++++++++- backend/src/services/bgp-rib-observation.ts | 34 ++++++++------ 3 files changed, 67 insertions(+), 17 deletions(-) diff --git a/backend/src/modules/mcp/bgp-prefix-actions.ts b/backend/src/modules/mcp/bgp-prefix-actions.ts index 9611544b..be0641cc 100644 --- a/backend/src/modules/mcp/bgp-prefix-actions.ts +++ b/backend/src/modules/mcp/bgp-prefix-actions.ts @@ -19,8 +19,8 @@ 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 observation = bgpRibSelection.safeExtend({ serverId: z.number().int().positive().safe() }) + register("routing.bgp.rib.read", "mm_bgp_rib_get", "Количество или страницы всех путей IPv4 BGP RIB, включая filtered. Для выборки по соседу укажите sessionName из bgp.session или peerCacheId. В следующих страницах передавайте 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])) diff --git a/backend/src/services/bgp-rib-observation.test.ts b/backend/src/services/bgp-rib-observation.test.ts index f1bcba4d..474cf8f0 100644 --- a/backend/src/services/bgp-rib-observation.test.ts +++ b/backend/src/services/bgp-rib-observation.test.ts @@ -19,7 +19,7 @@ function route(index: number, overrides: Record = {}): Record[]) { - const reads = { routePages: 0, counts: 0 } + const reads = { routePages: 0, counts: 0, sessionFilters: new Set() } 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") @@ -40,14 +40,17 @@ function fixture(rows: Record[]) { const query = body[".query"] assert(Array.isArray(query)) const peer = query.find(word => word.startsWith("bgp.peer-cache-id="))?.split("=")[1] + const session = query.find(word => word.startsWith("bgp.session="))?.slice("bgp.session=".length) assert.deepEqual(query, [ "routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|", ...(peer ? ["bgp.peer-cache-id=" + peer] : []), + ...(session ? ["bgp.session=" + session] : []), ]) reads.counts++ + if (session !== undefined) reads.sessionFilters.add(session) 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), + (!peer || row["bgp.peer-cache-id"] === peer) && (!session || row["bgp.session"] === session), ).length return { ret: String(count) } as T }, @@ -100,6 +103,45 @@ test("matching peer paths include filtered and inactive alternatives with distin assert.equal(otherPeer.items?.[0]?.id, filtered[".id"]) }) +test("RouterOS static rows without afi coexist with BGP paths identified by session name", async () => { + const nativeStatic = { + ".id": "*800002F2", "dst-address": "5.180.136.242/32", "routing-table": table, + contribution: "(unknown)", static: "true", + } + const sessionName = "ibgp-jh-test-anycast-1" + const received = route(0, { "bgp.session": sessionName }) + delete received["bgp.peer-cache-id"] + const { client, reads } = fixture([nativeStatic, received]) + const mixed = await readBgpRib(client, selection) + assert.equal(mixed.total, 1) + assert.deepEqual(mixed.items.map(item => [item.id, item.prefix, item.peerCacheId, item.session]), [ + [received[".id"], received["dst-address"], null, sessionName], + ]) + const bySession = await readBgpRib(client, { ...selection, sessionName }) + assert.equal(bySession.sessionName, sessionName) + assert.equal(bySession.total, 1) + assert.equal(bySession.items[0].id, received[".id"]) + assert.equal((await readBgpRib(client, { ...selection, mode: "count", sessionName: "ibgp-other-1" })).total, 0) + assert.deepEqual(reads.sessionFilters, new Set([sessionName, "ibgp-other-1"])) + assert(bySession.fingerprint) + await assert.rejects(readBgpRib(client, { ...selection, expectedFingerprint: bySession.fingerprint })) + await assert.rejects(readBgpRib(client, { ...selection, sessionName, peerCacheId: primary })) + await assert.rejects(readBgpRib(fixture([received, route(1)]).client, { ...selection, mode: "count", sessionName: "ibgp-other-1" })) + for (const invalid of [" ", sessionName + "\r"]) { + const malformed = fixture([{ ...received, "bgp.session": invalid }]).client + await assert.rejects(readBgpRib(malformed, { ...selection, mode: "count", sessionName })) + } + const onlyStatic = fixture([nativeStatic]) + assert.equal((await readBgpRib(onlyStatic.client, { ...selection, mode: "count" })).total, 0) + assert.equal(onlyStatic.reads.routePages, 1) + + const noOrigin: Record = { ...nativeStatic } + delete noOrigin.static + for (const ambiguous of [noOrigin, { ...nativeStatic, "bgp.session": "ibgp-to-jh-1" }, { ...noOrigin, bgp: "true" }]) { + await assert.rejects(readBgpRib(fixture([ambiguous]).client, { ...selection, mode: "count" })) + } +}) + test("missing table and missing peer attribution cannot prove a scoped zero", async () => { const { client } = fixture([]) const missingTable = { ...client, get: async () => [] as T } diff --git a/backend/src/services/bgp-rib-observation.ts b/backend/src/services/bgp-rib-observation.ts index 401dddd3..d7a9f645 100644 --- a/backend/src/services/bgp-rib-observation.ts +++ b/backend/src/services/bgp-rib-observation.ts @@ -5,14 +5,17 @@ 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) +const exactName = z.string().min(1).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name)) +const sessionIdentity = exactName.max(512) export const bgpRibSelection = z.object({ - table: z.string().min(1).max(100).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name)), + table: exactName.max(100), peerCacheId: rosId.optional(), + sessionName: sessionIdentity.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() +}).strict().refine(input => !(input.peerCacheId && input.sessionName), { message: "Choose only one BGP peer selector" }) const nativeRow = z.record(z.string(), z.unknown()) const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"] @@ -33,9 +36,11 @@ function optionalFlag(value: unknown) { 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) + // Disabled static routes on RouterOS can omit afi. Their explicit origin still has to agree with the BGP evidence below. + const missingNonBgpAfi = row.afi === undefined && other && bgp !== true + if (row.afi !== "ip" && row.afi !== "ip4" && !missingNonBgpAfi) throw new Error("Unrecognized RouterOS address family") 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") @@ -56,7 +61,7 @@ function ipv4Row(row: Record, table: string) { 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), + session: sessionIdentity.nullable().parse(row["bgp.session"] ?? null), gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null), } } @@ -64,9 +69,11 @@ function ipv4Row(row: Record, table: string) { /** 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) + const { table, peerCacheId, sessionName, 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 peer = peerCacheId ? { field: "peerCacheId", native: "bgp.peer-cache-id", value: peerCacheId } as const + : sessionName ? { field: "session", native: "bgp.session", value: sessionName } as const : null 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) @@ -75,8 +82,8 @@ export async function readBgpRib(client: Pick, i 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 nativeCount = async (scoped = false) => { + const filter = scoped && peer ? [...query, peer.native + "=" + peer.value] : 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) @@ -85,7 +92,7 @@ export async function readBgpRib(client: Pick, i 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 (mode === "page" || peer || 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) @@ -96,19 +103,20 @@ export async function readBgpRib(client: Pick, i 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 (peer && !observed[peer.field]) throw new Error("Native peer identity unavailable") + if (!peer || observed[peer.field] === peer.value) selected.push(observed) } - if (allCount !== ids.size || selected.length !== await nativeCount(peerCacheId)) throw new BgpRibChanged("Native RIB count changed or view incomplete") + if (allCount !== ids.size || selected.length !== await nativeCount(true)) 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") + const peerScope = sessionName ? { sessionName } : peerCacheId ?? null + fingerprint = createHash("sha256").update(JSON.stringify([table, identity, peerScope, 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 } + return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, sessionName: sessionName ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false } }