Compare commits

...
3 Commits
Author SHA1 Message Date
Denozordec 37025f1f94 fix(mcp): учитывать отдельную таблицу маршрутизации пира
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 11m54s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-12-02 01:05:02 +07:00
Denozordec c49e01299c fix(mcp): сократить описание чтения RIB для реестра операций
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 12m0s
Docker images / frontend-image (push) Successful in 3m48s
Docker images / updater-image (push) Successful in 1m47s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m11s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-12-01 22:07:28 +07:00
Denozordec 187a0cd45e fix(mcp): учитывать отключённую статику и имя сессии при чтении RIB
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Failing after 3m28s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 4m54s
Docker images / updater-image (push) Successful in 2m8s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
2026-12-01 22:00:11 +07:00
5 changed files with 102 additions and 22 deletions

No files matched your search

@@ -61,7 +61,13 @@ async function readState(input: Record<string, unknown>) {
if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown")
Object.assign(instance, effectiveInstance)
const instanceContext = await readBgpInstanceContext(client, instance)
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instanceContext.table)[".id"] !== table[".id"]) throw new Error("BGP instance/connection contexts disagree")
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"]) throw new Error("BGP instance/connection VRFs disagree")
const instanceTable = unique("routing_table", instanceContext.table)
const separateTables = instanceTable[".id"] !== table[".id"]
if (separateTables && snapshots.find(row => row.resource === "vrf")!.rows.some(owner =>
owner[".id"] !== vrf[".id"] && (owner.name === table.name || owner.name === instanceTable.name))) {
throw new Error("BGP routing table belongs to a different VRF")
}
const filters = nativeBgpRows(await client.get("/routing/filter/rule"))
if (filters.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог BGP filters превышает 1000 строк", 409)
const selected = filters.filter(row => row.chain === desired)
@@ -71,13 +77,14 @@ async function readState(input: Record<string, unknown>) {
const protections = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(serverId)])).rows
if (protections.length > 1000) throw new Error("BGP protection closure exceeds limit")
const objects: ChangeEvidence["objects"] = [{ kind: "bgp-policy", id, serverId }, { kind: "bgp_connection", id, serverId },
...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })),
...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table], ["routing_table", instanceTable]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record<string, unknown>)[".id"]), serverId })),
...filters.map(row => ({ kind: "routing_filter", id: row[".id"], serverId })), ...[...used.keys()].map(nativeId => ({ kind: "bgp_template", id: nativeId, serverId })),
...protections.map(({ object_ref: ref }) => ({ kind: ref.kind, id: ref.id, serverId }))]
const uniqueObjects = [...new Map(objects.map(row => [fingerprint(row), row])).values()]
if (uniqueObjects.length > 1000) throw new Error("BGP dependency closure exceeds limit")
const canonicalConnection = { ...stableBgpPolicyRow(connection), [property]: effectiveChain }
const dependencyProof = await proof(serverId, id, "dependencies", { serverProof, otherConnections: connections.filter(row => row[".id"] !== id).map(stableBgpPolicyRow), instance: stableBgpPolicyRow(instance), instanceContext, vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table),
...(separateTables ? { instanceTable: stableBgpPolicyRow(instanceTable) } : {}),
filters: filters.map(stableBgpPolicyRow), used: [...used.values()], references, protections })
const before = { serverId, id, direction: input.direction, property, instance: instance.name, vrf: vrf.name, table: table.name, localChain, inheritedChain, effectiveChain,
selectedRuleCount: selected.length, selectedEnabledRuleCount: effectiveFilters.filter(row => ["false", "no"].includes(String(row.disabled))).length, serverProof, dependencyProof,
@@ -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 или 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]))
@@ -19,7 +19,7 @@ function route(index: number, overrides: Record<string, string> = {}): Record<st
}
function fixture(rows: Record<string, string>[]) {
const reads = { routePages: 0, counts: 0 }
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")
@@ -40,14 +40,17 @@ function fixture(rows: Record<string, string>[]) {
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<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 }
+21 -13
View File
@@ -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<string, unknown>, 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<string, unknown>, 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<string, unknown>, 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<MikrotikClient, "get" | "post">, input: Selection,
beforeRead: () => Promise<unknown> = 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<unknown>(tablePath, 10_000, signal, 16_384, beforeRead)
@@ -75,8 +82,8 @@ export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, 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<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)
@@ -85,7 +92,7 @@ export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, i
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" || 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<unknown>(path, 30_000, signal, 8 * 1024 * 1024, beforeRead)
@@ -96,19 +103,20 @@ export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, 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 }
}
+26 -3
View File
@@ -51,7 +51,7 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
try {
await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,username,password) VALUES(79,'binding-fixture','127.0.0.1',$1,false,'fixture','NEVER_BIND_LOGIN')", [address.port])
const issued = await create(), principal = await authenticateMcpToken(issued.token)
const prepare = (chain = "in", direction = "input") => invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain, direction }) as Promise<{ planId: string; state: string }>
const prepare = (chain = "in", direction = "input") => invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain, direction }) as Promise<{ planId: string; state: string; changes: { objects: { kind: string; id: string }[] } }>
const wait = async (id: string) => { for (let n = 0; n < 400; n++) { const row = (await pool.query("SELECT id,state,error_code FROM mcp_operations WHERE id=$1", [id])).rows[0]; if (row && !["pending", "running"].includes(row.state)) return row; await delay(25) } assert.fail("Binding operation did not terminate") }
const apply = async (planId: string) => { await approvePlan(planId, actor, true); return wait((await applyPlan(principal, planId, randomUUID())).id) }
for (const permission of permissions) { const denied = await create(permissions.filter(value => value !== permission)), before = reads; await assert.rejects(invokeMcpTool(await authenticateMcpToken(denied.token), "mm_bgp_filter_binding_plan", { serverId: 79, id: "*peer", chain: "in", direction: "input" })); assert.equal(reads, before) }
@@ -70,12 +70,35 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
Object.assign(peer, context); Object.assign(collections["/routing/bgp/instance"][0], { vrf: "lab", "routing-table": "lab" })
Object.assign(peer, { instance: "*instance", vrf: "*vrf", "routing-table": "*table" }); assert.equal((await apply((await prepare()).planId)).state, "applied"); Object.assign(peer, context)
collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" })
collections["/routing/table"].push({ ".id": "*mainTable", name: "main", fib: "" })
const mainTable: Record<string, string> = { ".id": "*mainTable", name: "main", fib: "" }
const peerTable: Record<string, string> = { ".id": "*peerTable", name: "rtab-antiblock", fib: "true" }
collections["/routing/table"].push(mainTable, peerTable)
const instance = collections["/routing/bgp/instance"][0]
delete instance.vrf; delete instance["routing-table"]
Object.assign(peer, { vrf: "main", "routing-table": "main" }); unsetInstanceContext = true
assert.equal((await apply((await prepare()).planId)).state, "applied")
peer["routing-table"] = "lab"; await assert.rejects(prepare())
Object.assign(instance, { vrf: "main", "routing-table": "main" })
peer["routing-table"] = peerTable.name
for (const table of [mainTable, peerTable]) {
const stale = await prepare("in", "output")
const writesBefore: number = writes
table.comment = "changed after preview"
assert.notEqual((await apply(stale.planId)).state, "applied")
assert.equal(writes, writesBefore)
delete table.comment
}
const overrideTablePlan = await prepare("in", "output")
assert.deepEqual(overrideTablePlan.changes.objects.filter(row => row.kind === "routing_table").map(row => row.id).sort(), ["*mainTable", "*peerTable"])
assert.equal((await apply(overrideTablePlan.planId)).state, "applied")
assert.equal(local["output.filter-chain"], "in")
assert.equal(peer["routing-table"], "rtab-antiblock")
assert.equal(instance["routing-table"], "main")
peer.vrf = "lab"; await assert.rejects(prepare()); peer.vrf = "main"
for (const foreignTableRef of ["lab", "*table"]) {
peer["routing-table"] = foreignTableRef
await assert.rejects(prepare(), "A table owned by another VRF cannot override the main instance table")
}
peer["routing-table"] = "lab"
Object.assign(instance, { vrf: "main", "routing-table": "lab" })
assert.equal((await apply((await prepare("out", "output")).planId)).state, "applied")
Object.assign(peer, context); Object.assign(instance, { vrf: "lab", "routing-table": "lab" }); unsetInstanceContext = false