diff --git a/backend/src/modules/mcp/bgp-filter-binding-actions.ts b/backend/src/modules/mcp/bgp-filter-binding-actions.ts index dde6ffbc..444959e9 100644 --- a/backend/src/modules/mcp/bgp-filter-binding-actions.ts +++ b/backend/src/modules/mcp/bgp-filter-binding-actions.ts @@ -61,7 +61,13 @@ async function readState(input: Record) { 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) { 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)[".id"]), serverId })), + ...[["bgp_instance", instance], ["vrf", vrf], ["routing_table", table], ["routing_table", instanceTable]].map(([kind, row]) => ({ kind: String(kind), id: String((row as Record)[".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, diff --git a/backend/src/test/mcp-bgp-filter-binding.ts b/backend/src/test/mcp-bgp-filter-binding.ts index 19f89260..c079cabf 100644 --- a/backend/src/test/mcp-bgp-filter-binding.ts +++ b/backend/src/test/mcp-bgp-filter-binding.ts @@ -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 = { ".id": "*mainTable", name: "main", fib: "" } + const peerTable: Record = { ".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