Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c49e01299c | ||
|
|
187a0cd45e | ||
|
|
731c19a14d | ||
|
|
94c50b9660 | ||
|
|
fc39b0da3c |
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,5 +1,5 @@
|
||||
import { z } from "zod"
|
||||
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { bgpExportConnection, bgpExportSources, bgpRedistributionMode, bgpTemplateReferences, nativeBgpExportValue, nativeBgpRows, type BgpExportMode, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
||||
import { executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
||||
@@ -70,9 +70,18 @@ async function readState(input: Record<string, unknown>) {
|
||||
return found[0]
|
||||
}
|
||||
const instance = unique("bgp_instance", connection.instance), vrf = unique("vrf", connection.vrf), table = unique("routing_table", connection["routing-table"])
|
||||
if (instance.vrf !== connection.vrf || instance["routing-table"] !== connection["routing-table"] || vrf.name !== table.name) throw new McpError("STATE_CONFLICT", "Экспорт требует одинаковые явные instance/connection VRF и таблицу", 409)
|
||||
const [v4, v6] = await Promise.all([client.get<unknown>("/ip/route"), client.get<unknown>("/ipv6/route")])
|
||||
const sources = [...parseState("IPv4 source origins/table/prefixes", () => bgpExportSources(v4, String(table.name), sourceModes, 4)), ...parseState("IPv6 source origins/table/prefixes", () => bgpExportSources(v6, String(table.name), sourceModes, 6))]
|
||||
const instanceContext = await readBgpInstanceContext(client, { ...instance, ".id": String(instance[".id"]) })
|
||||
if (unique("vrf", instanceContext.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instanceContext.table)[".id"] !== table[".id"]) throw new McpError("STATE_CONFLICT", "Контекст VRF и таблицы у BGP instance и connection расходится", 409)
|
||||
const tableName = String(table.name)
|
||||
const sourceGroups = await Promise.all(([4, 6] as const).flatMap(family => sourceModes.filter(kind => kind !== "disabled").map(async kind => {
|
||||
const params = new URLSearchParams({ "routing-table": tableName, [kind === "connected" ? "connect" : "static"]: "true" })
|
||||
const rows = nativeBgpRows(await client.get<unknown>(`${family === 4 ? "/ip/route" : "/ipv6/route"}?${params}`))
|
||||
const candidates = parseState(`IPv${family} source origins/table/prefixes`, () => bgpExportSources(rows, tableName, [kind], family))
|
||||
if (candidates.length !== rows.length) throw new McpError("STATE_UNAVAILABLE", "Ответ RouterOS не соответствует запросу источников BGP", 409)
|
||||
return candidates
|
||||
})))
|
||||
const sources = sourceGroups.flat().sort((a, b) => a.family - b.family || a.id.localeCompare(b.id))
|
||||
if (new Set(sources.map(row => `${row.family}:${row.id}`)).size !== sources.length) throw new McpError("STATE_UNAVAILABLE", "Повторяющиеся источники экспорта BGP", 409)
|
||||
if (sources.length > 500) throw new McpError("LIMIT_EXCEEDED", "Экспорт BGP превышает 500 исходных маршрутов", 409)
|
||||
const objects: ChangeEvidence["objects"] = [
|
||||
{ kind: "bgp-export", id, serverId }, { kind: "bgp_connection", id, serverId },
|
||||
@@ -87,7 +96,7 @@ async function readState(input: Record<string, unknown>) {
|
||||
const before = { serverId, serverProof, id, instance: connection.instance, vrf: connection.vrf, table: connection["routing-table"], mode: currentMode, localMode, inheritedMode,
|
||||
templates: templateProof.map(value => ({ id: value.row[".id"], name: value.row.name, mode: value.mode })),
|
||||
sourceModes, sources: sources.map(({ proof: _proof, ...row }) => row),
|
||||
connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) }
|
||||
connectionProof: await configurationProof(serverId, id, connection), sourceProof: await privateSecretFingerprint(fingerprint({ serverProof, parentProof, instanceContext, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) }
|
||||
return { server, client, connection, before, objects }
|
||||
}
|
||||
async function state(input: Record<string, unknown>) {
|
||||
@@ -117,6 +126,7 @@ export function registerBgpExportActions(register: typeof add) {
|
||||
},
|
||||
})
|
||||
register("routing.bgp.export", "mm_bgp_export_plan", "Человеческий план перераспределения connected/static в BGP с проверкой источников; disabled отключает только перераспределение", "bgp", ["mm:bgp:write", "mm:network:read", "mm:filters:read"], "write", "servers", schema, {
|
||||
version: 2,
|
||||
prepare: async input => {
|
||||
const initial = await state(input), before = initial.before, request = { ...input, sourceModes: before.sourceModes, beforeFingerprint: fingerprint(before), expectedServerProof: before.serverProof }
|
||||
return { target: { scope: "servers", serverIds: [Number(input.serverId)] }, objects: initial.objects, snapshots: [], before,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { readBgpInstanceContext, readStaticBgpConnection } from "../../services/bgp-connection-read.js"
|
||||
import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||
import { bgpFilterName, bgpFilterProperty, effectiveBgpFilter, stableBgpPolicyRow, type BgpFilterDirection } from "../../services/bgp-filter-binding-model.js"
|
||||
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
|
||||
@@ -60,12 +60,8 @@ async function readState(input: Record<string, unknown>) {
|
||||
const [effectiveInstance] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([instance], nativeId => client.post("/routing/bgp/instance/get", { ".id": nativeId, "value-name": "disabled" }))
|
||||
if (!["false", "no"].includes(String(effectiveInstance.disabled))) throw new Error("BGP instance disabled/unknown")
|
||||
Object.assign(instance, effectiveInstance)
|
||||
for (const key of ["vrf", "routing-table"]) if (instance[key] === undefined || instance[key] === "") {
|
||||
const value = bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": String(instance[".id"]), "value-name": key }))
|
||||
if (!value) throw new Error("BGP instance effective context not confirmed")
|
||||
instance[key] = value
|
||||
}
|
||||
if (unique("vrf", instance.vrf)[".id"] !== vrf[".id"] || unique("routing_table", instance["routing-table"])[".id"] !== table[".id"] || vrf.name !== table.name) throw new Error("BGP instance/connection contexts disagree")
|
||||
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")
|
||||
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)
|
||||
@@ -81,7 +77,7 @@ async function readState(input: Record<string, unknown>) {
|
||||
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), vrf: { ...stableBgpPolicyRow(vrf), ...(vrf.interfaces !== undefined ? { interfaces: canonicalVrfMembers(vrf.interfaces) } : {}) }, table: stableBgpPolicyRow(table),
|
||||
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),
|
||||
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,
|
||||
@@ -112,6 +108,7 @@ export function registerBgpFilterBindingActions(register: typeof add) {
|
||||
},
|
||||
})
|
||||
register("routing.bgp.filter.bind", "mm_bgp_filter_binding_plan", "Человеческий план локальной input/output привязки BGP к существующей цепочке; пустая chain очищает local binding", "bgp", ["mm:bgp:write", "mm:filters:read", "mm:network:read"], "write", "servers", schema, {
|
||||
version: 2,
|
||||
prepare: async input => {
|
||||
const initial = await state(input)
|
||||
return { target: { scope: "servers", serverIds: [initial.server.id] }, objects: initial.objects, snapshots: [], before: initial.before, requiresHuman: true, verificationScope: "configuration", mutationCost: 1,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,24 @@
|
||||
import type { MikrotikClient } from "./mikrotik.js"
|
||||
import { nativeBgpRows, type NativeBgpRow } from "./bgp-export-model.js"
|
||||
import { bgpFilterName } from "./bgp-filter-binding-model.js"
|
||||
import { readOspfEffectiveDisabled } from "./ospf-effective-disabled.js"
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
|
||||
export async function readBgpInstanceContext(client: Pick<MikrotikClient, "post">, row: NativeBgpRow) {
|
||||
const read = async (key: "vrf" | "routing-table") => {
|
||||
const value = row[key]
|
||||
return value === undefined || value === ""
|
||||
? bgpFilterName(await client.post("/routing/bgp/instance/get", { ".id": row[".id"], "value-name": key }))
|
||||
: bgpFilterName({ ret: value })
|
||||
}
|
||||
const [observedVrf, observedTable] = await Promise.all([read("vrf"), read("routing-table")])
|
||||
const vrf = observedVrf || "main"
|
||||
// Only infer the routing table when the instance uses the built-in VRF.
|
||||
const table = observedTable || (vrf === "main" ? "main" : null)
|
||||
if (!table) throw new McpError("STATE_UNAVAILABLE", "Не подтверждена таблица BGP instance", 409)
|
||||
return { vrf, table }
|
||||
}
|
||||
|
||||
/** Prove a configured peer, including RouterOS releases that omit the D flag. */
|
||||
export async function readStaticBgpConnection(client: Pick<MikrotikClient, "get" | "post">, id: string) {
|
||||
const connections = nativeBgpRows(await client.get("/routing/bgp/connection")), target = connections.find(row => row[".id"] === id)
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -9,10 +9,10 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
|
||||
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
|
||||
|
||||
export async function verifyMcpBgpExport(actor: AuthUser) {
|
||||
let mode = "", templateMode = "", writes = 0, reads = 0, ignored = false, unexpected = false, lost = false
|
||||
let mode = "", templateMode = "", writes = 0, reads = 0, ignored = false, unexpected = false, lost = false, ignoreRouteQuery = false
|
||||
let staticQueryReply: unknown = [{ ".id": "*peer" }]
|
||||
const connection: Record<string, string> = { ".id": "*peer", name: "export-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "remote.address": "192.0.2.2", "remote.as": "64513", "tcp-md5-key": "NEVER_BGP_EXPORT_MD5" }
|
||||
const routes: Record<string, unknown[]> = {
|
||||
const routes: Record<string, Record<string, unknown>[]> = {
|
||||
"/ip/route": [{ ".id": "*c4", "routing-table": "lab", "dst-address": "192.0.2.0/30", connect: "true", dynamic: "true", active: "true", comment: "NEVER_BGP_EXPORT_ROUTE_NOTE" },
|
||||
{ ".id": "*s4", "routing-table": "lab", "dst-address": "198.18.0.1/32", static: "true", dynamic: "false", active: "true" },
|
||||
{ ".id": "*b4", "routing-table": "lab", "dst-address": "198.18.1.1/32", bgp: "true", dynamic: "true", active: "true" }],
|
||||
@@ -29,10 +29,17 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
||||
"/routing/filter/rule": [{ ".id": "*f", chain: "export-out", rule: "NEVER_BGP_EXPORT_FILTER_SECRET", disabled: "false" }],
|
||||
}
|
||||
const mock = createServer(async (req, res) => {
|
||||
const path = (req.url ?? "").replace(/^\/rest/, "")
|
||||
const url = new URL(req.url ?? "/", "http://127.0.0.1")
|
||||
const path = url.pathname.replace(/^\/rest/, "")
|
||||
if (req.method === "GET") {
|
||||
reads++; res.setHeader("content-type", "application/json")
|
||||
res.end(JSON.stringify(path === "/routing/bgp/connection" ? [connection] : collections[path] ?? routes[path] ?? [])); return
|
||||
const candidates = routes[path]
|
||||
if (candidates) {
|
||||
const table = url.searchParams.get("routing-table"), kind = url.searchParams.has("connect") ? "connect" : "static"
|
||||
assert.ok(table); assert.equal(url.searchParams.get(kind), "true")
|
||||
res.end(JSON.stringify(ignoreRouteQuery ? candidates : candidates.filter(row => row["routing-table"] === table && row[kind] === "true"))); return
|
||||
}
|
||||
res.end(JSON.stringify(path === "/routing/bgp/connection" ? [connection] : collections[path] ?? [])); return
|
||||
}
|
||||
let raw = ""; for await (const data of req) raw += data
|
||||
const body = raw ? JSON.parse(raw) as Record<string, string> : {}
|
||||
@@ -49,6 +56,7 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
||||
const property = body["value-name"]
|
||||
res.end(JSON.stringify(property === "output.redistribute" ? templateMode ? { ret: templateMode } : [] : property === "templates" ? { ret: collections["/routing/bgp/template"][0].templates ?? "" } : { ret: "false" })); return
|
||||
}
|
||||
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify([])); return }
|
||||
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
|
||||
writes++
|
||||
assert.deepEqual(Object.keys(body), ["output.redistribute"])
|
||||
@@ -100,6 +108,7 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
||||
staticQueryReply = invalid; await assert.rejects(plan("connected")); assert.equal(writes, 0)
|
||||
}
|
||||
staticQueryReply = [{ ".id": "*peer" }]
|
||||
ignoreRouteQuery = true; await assert.rejects(plan("connected"), /не соответствует запросу источников/); ignoreRouteQuery = false
|
||||
let prepared = await plan("connected")
|
||||
assert.equal(prepared.state, "awaiting-approval"); assert.equal(prepared.changes.before.mode, "disabled"); assert.equal(prepared.changes.before.sources.length, 2)
|
||||
assert(prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*c4")); assert(!prepared.changes.objects.some(row => row.kind === "ipv4_route" && row.id === "*b4"))
|
||||
@@ -146,6 +155,16 @@ export async function verifyMcpBgpExport(actor: AuthUser) {
|
||||
const lostPlan = await plan("disabled"), lostOperation = await apply(lostPlan.planId)
|
||||
assert.equal(lostOperation.state, "unknown"); assert.equal(writes, beforeLost + 1); lost = false
|
||||
assert.equal((await applyPlan(principal, lostPlan.planId, randomUUID())).id, lostOperation.id); assert.equal(writes, beforeLost + 1)
|
||||
const instance = collections["/routing/bgp/instance"][0]
|
||||
delete instance.vrf; delete instance["routing-table"]
|
||||
Object.assign(connection, { vrf: "main", "routing-table": "main" }); mode = ""
|
||||
collections["/ip/vrf"].push({ ".id": "*mainVrf", name: "main", interfaces: "all" })
|
||||
collections["/routing/table"].push({ ".id": "*mainTable", name: "main", fib: "" })
|
||||
const baseRoute = routes["/ip/route"][0]
|
||||
routes["/ip/route"].push({ ...baseRoute, ".id": "*mainRoute", "routing-table": "main" })
|
||||
const defaultContextPlan = await plan("connected")
|
||||
assert.equal(defaultContextPlan.changes.before.sources.length, 1)
|
||||
assert.equal((await apply(defaultContextPlan.planId)).state, "applied")
|
||||
const requests = (await pool.query("SELECT input,result FROM mcp_requests WHERE connection_id=ANY($1::uuid[])", [connections])).rows
|
||||
const audit = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=ANY($1::uuid[])", [connections])).rows
|
||||
assert.equal(JSON.stringify({ requests, audit }).includes("NEVER_BGP_EXPORT_"), false)
|
||||
|
||||
@@ -9,7 +9,7 @@ import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.
|
||||
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
|
||||
|
||||
export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
||||
let reads = 0, writes = 0, ignored = false, corrupt = false, lost = false, lateDrift = false, lateFenceReached = false, intentBaseline = 0
|
||||
let reads = 0, writes = 0, ignored = false, corrupt = false, lost = false, lateDrift = false, lateFenceReached = false, intentBaseline = 0, unsetInstanceContext = false
|
||||
const peer: Record<string, string> = { ".id": "*peer", name: "binding-peer", disabled: "false", instance: "lab", vrf: "lab", "routing-table": "lab", templates: "default", "tcp-md5-key": "NEVER_BIND_PEER_SECRET", "output.redistribute": "connected,static,ospf" }
|
||||
const local: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }, inherited: Record<string, string | null> = { "input.filter": null, "output.filter-chain": null }
|
||||
const context: Record<string, string> = { instance: "lab", vrf: "lab", "routing-table": "lab" }
|
||||
@@ -29,7 +29,7 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
||||
if (path === "/routing/bgp/connection/get") { const value = property === "dynamic" ? null : property === "templates" ? peer.templates : property in local ? local[property] : property in peer ? peer[property] : context[property] ?? "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
|
||||
if (path === "/routing/bgp/connection/print") { assert.deepEqual(body[".query"], [".id=*peer", "-dynamic", "#&"]); res.end(JSON.stringify([{ ".id": "*peer" }])); return }
|
||||
if (path === "/routing/bgp/template/get") { const value = property in inherited ? inherited[property] : property === "templates" ? collections["/routing/bgp/template"][0].templates ?? "" : "false"; res.end(JSON.stringify(value === null ? [] : { ret: value })); return }
|
||||
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify({ ret: context[property] ?? "false" })); return }
|
||||
if (path === "/routing/bgp/instance/get") { res.end(JSON.stringify(unsetInstanceContext && ["vrf", "routing-table"].includes(property) ? [] : { ret: context[property] ?? "false" })); return }
|
||||
if (path === "/routing/filter/rule/get") { res.end(JSON.stringify({ ret: "false" })); return }
|
||||
if (req.method === "PATCH" && path === "/routing/bgp/connection/*peer") {
|
||||
writes++; assert.equal(Object.keys(body).length, 1); const key = Object.keys(body)[0]; assert.ok(key in local)
|
||||
@@ -69,6 +69,16 @@ export async function verifyMcpBgpFilterBinding(actor: AuthUser) {
|
||||
assert.equal((await apply((await prepare()).planId)).state, "applied", "Effective default context comes from native /get, not guessed main")
|
||||
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 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": "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
|
||||
collections["/routing/bgp/template"][0].templates = "default"; await assert.rejects(prepare()); delete collections["/routing/bgp/template"][0].templates
|
||||
await assert.rejects(prepare("In")); await assert.rejects(prepare("missing"))
|
||||
const beforeInvalid = reads; await assert.rejects(invokeMcpTool(principal, "mm_bgp_filter_binding_plan", { serverId: 79, id: "all", chain: "in", direction: "input" })); assert.equal(reads, beforeInvalid)
|
||||
|
||||
Reference in new issue
Block a user