From fc39b0da3c8ec412e4073d09b55e6d646d2efbbe Mon Sep 17 00:00:00 2001 From: Denozordec Date: Mon, 30 Nov 2026 22:40:29 +0700 Subject: [PATCH] =?UTF-8?q?fix(mcp):=20=D1=83=D1=87=D0=B8=D1=82=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D1=8C=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=BA?= =?UTF-8?q?=D1=81=D1=82=20=D1=8D=D0=BA=D0=B7=D0=B5=D0=BC=D0=BF=D0=BB=D1=8F?= =?UTF-8?q?=D1=80=D0=B0=20=D0=BF=D1=80=D0=B8=20=D0=BD=D0=B0=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=BE=D0=B9=D0=BA=D0=B5=20=D0=BC=D0=B0=D1=80=D1=88=D1=80?= =?UTF-8?q?=D1=83=D1=82=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/modules/mcp/bgp-export-actions.ts | 20 ++++++++++---- .../modules/mcp/bgp-filter-binding-actions.ts | 13 ++++----- backend/src/services/bgp-connection-read.ts | 16 +++++++++++ backend/src/test/mcp-bgp-export.ts | 27 ++++++++++++++++--- backend/src/test/mcp-bgp-filter-binding.ts | 14 ++++++++-- 5 files changed, 71 insertions(+), 19 deletions(-) diff --git a/backend/src/modules/mcp/bgp-export-actions.ts b/backend/src/modules/mcp/bgp-export-actions.ts index 47195b55..c62c499c 100644 --- a/backend/src/modules/mcp/bgp-export-actions.ts +++ b/backend/src/modules/mcp/bgp-export-actions.ts @@ -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) { 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("/ip/route"), client.get("/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(`${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) { 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) { @@ -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, diff --git a/backend/src/modules/mcp/bgp-filter-binding-actions.ts b/backend/src/modules/mcp/bgp-filter-binding-actions.ts index 4ad889f1..dde6ffbc 100644 --- a/backend/src/modules/mcp/bgp-filter-binding-actions.ts +++ b/backend/src/modules/mcp/bgp-filter-binding-actions.ts @@ -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) { const [effectiveInstance] = await readOspfEffectiveDisabled([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) { 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, diff --git a/backend/src/services/bgp-connection-read.ts b/backend/src/services/bgp-connection-read.ts index d8841eec..c8549180 100644 --- a/backend/src/services/bgp-connection-read.ts +++ b/backend/src/services/bgp-connection-read.ts @@ -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, 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, id: string) { const connections = nativeBgpRows(await client.get("/routing/bgp/connection")), target = connections.find(row => row[".id"] === id) diff --git a/backend/src/test/mcp-bgp-export.ts b/backend/src/test/mcp-bgp-export.ts index eb05130d..458cdc9d 100644 --- a/backend/src/test/mcp-bgp-export.ts +++ b/backend/src/test/mcp-bgp-export.ts @@ -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 = { ".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 = { + const routes: Record[]> = { "/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 : {} @@ -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) diff --git a/backend/src/test/mcp-bgp-filter-binding.ts b/backend/src/test/mcp-bgp-filter-binding.ts index f9b9903c..19f89260 100644 --- a/backend/src/test/mcp-bgp-filter-binding.ts +++ b/backend/src/test/mcp-bgp-filter-binding.ts @@ -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 = { ".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 = { "input.filter": null, "output.filter-chain": null }, inherited: Record = { "input.filter": null, "output.filter-chain": null } const context: Record = { 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)