Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c49e01299c | ||
|
|
187a0cd45e | ||
|
|
731c19a14d | ||
|
|
94c50b9660 |
No files matched your search
@@ -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",
|
||||
|
||||
@@ -180,7 +180,7 @@ for (const resource of rosResources) {
|
||||
: z.object({ serverId, id: rowId.optional(), fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
|
||||
const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete"
|
||||
const guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id)
|
||||
const previousVersion = action === "create" ? (["ospf_template", "wireguard_peer", "wireguard", "bfd_configuration"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
|
||||
const previousVersion = action === "create" ? (resource.id === "bfd_configuration" ? 4 : ["ospf_template", "wireguard_peer", "wireguard"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
|
||||
add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, {
|
||||
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 1 : 0),
|
||||
prepare: async (input, context) => {
|
||||
|
||||
@@ -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.safeExtend({ serverId: z.number().int().positive().safe() })
|
||||
register("routing.bgp.rib.read", "mm_bgp_rib_get", "IPv4 BGP RIB с filtered-путями. Для соседа укажите sessionName или 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]))
|
||||
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"),
|
||||
|
||||
@@ -11,7 +11,7 @@ const creates = rosResources.filter(resource => !resource.readOnly && resource.c
|
||||
assert.equal(creates.length, 30)
|
||||
for (const resource of creates) {
|
||||
const action = findAction(`mm_${resource.id}_create_plan`)
|
||||
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 8 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
|
||||
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 9 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
|
||||
assert.equal(action.schema.safeParse({ serverId: 1, fields: {} }).success, true)
|
||||
for (const id of ["*OLD", undefined, null, ""]) {
|
||||
const rejected = action.schema.safeParse({ serverId: 1, fields: {}, id })
|
||||
@@ -27,6 +27,7 @@ assert.throws(() => validateRosStep(bfdConfig, "create", { vrf: "main" }), inval
|
||||
assert.deepEqual(validateRosStep(bfdConfig, "create", { interfaces: "bridge1", vrf: "main" }), { interfaces: "bridge1", vrf: "main" })
|
||||
for (const interfaces of ["all", "none", "bridge1,all", "bridge1,"]) assert.throws(() => validateRosStep(bfdConfig, "create", { interfaces, vrf: "main" }), invalid)
|
||||
for (const [addresses, expected] of [["192.0.2.9/24", "192.0.2.0/24"], ["FD00::20/64", "fd00::/64"], ["192.0.2.9/32", "192.0.2.9/32"], ["fd00::20/128", "fd00::20/128"]]) {
|
||||
assert.deepEqual(validateRosStep(bfdConfig, "create", { addresses, vrf: "main" }), { addresses: expected, vrf: "main" })
|
||||
assert.deepEqual(validateRosStep(bfdConfig, "update", { addresses }, "*A"), { addresses: expected })
|
||||
}
|
||||
for (const addresses of ["0.0.0.0/0", "::/0", "192.0.2.1", "fd00::/129", "192.0.2.1/32/extra", "192.0.2.0/24,192.0.3.0/24", "fe80::%ether1/64"]) assert.equal(bfdConfig.fields.safeParse({ addresses }).success, false)
|
||||
|
||||
@@ -381,7 +381,7 @@ export function validateRosStep(resource: RosResourceSpec, action: RosStep["acti
|
||||
const parsed = resource.fields.parse(fields ?? {}) as Record<string, unknown>
|
||||
if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400)
|
||||
if (resource.id === "bfd_configuration" && action === "create") {
|
||||
if (!parsed.interfaces && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите интерфейсы или address-list", 400)
|
||||
if (!parsed.interfaces && !parsed.addresses && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите interfaces, addresses или address-list", 400)
|
||||
if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) {
|
||||
throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
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<string, string> = {}): Record<string, string> {
|
||||
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<string, string>[]) {
|
||||
const reads = { routePages: 0, counts: 0, sessionFilters: new Set<string>() }
|
||||
const client = {
|
||||
async get<T>(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<T>(path: string, body: Record<string, string | string[]>) {
|
||||
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]
|
||||
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) && (!session || row["bgp.session"] === session),
|
||||
).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 <T>() => 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 <T>() => ({ 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("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<string, string> = { ...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 <T>() => [] 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))
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
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)
|
||||
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: 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().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"]
|
||||
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<typeof bgpRibSelection>
|
||||
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<string, unknown>, table: string) {
|
||||
if (row["routing-table"] !== table) throw new Error("Unexpected native route table")
|
||||
if (otherFamilies.has(String(row.afi))) return null
|
||||
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")
|
||||
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: sessionIdentity.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<MikrotikClient, "get" | "post">, input: Selection,
|
||||
beforeRead: () => Promise<unknown> = async () => {}, signal?: AbortSignal) {
|
||||
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<unknown>(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 (scoped = false) => {
|
||||
const filter = scoped && peer ? [...query, peer.native + "=" + peer.value] : query
|
||||
const raw = await client.post<unknown>("/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<ReturnType<typeof ipv4Row>>
|
||||
let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null
|
||||
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<unknown>(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<string>(), 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 (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(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)
|
||||
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, sessionName: sessionName ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false }
|
||||
}
|
||||
Reference in new issue
Block a user