Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc39b0da3c |
No files matched your search
@@ -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,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)
|
||||
|
||||
@@ -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