import { z } from "zod" 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" import { fingerprint, McpError, privateSecretFingerprint } from "./security.js" import { readRosSnapshot, routerClient, type ConfigurationRow } from "./resources.js" import { registerMcpService } from "./service-registry.js" import type { ChangeEvidence } from "./action-types.js" import type { add } from "./actions.js" const modeSchema = z.enum(["disabled", "connected", "static"]).describe("Connected/static перераспределяют соответствующие маршруты таблицы peer. Disabled очищает только redistribution; output.network/default-originate и сам peer не отключаются.") const schema = z.object({ serverId: z.number().int().positive().safe(), id: z.string().trim().min(1).max(200), mode: modeSchema }).strict() const service = "routing.bgp.export" const modes = (values: BgpExportMode[]) => [...new Set(values)].sort() as BgpExportMode[] const configurationProof = (serverId: number, id: string, value: unknown) => privateSecretFingerprint(fingerprint(value), `bgp-export-connection:${serverId}:${id}`) function parseState(phase: string, parse: () => T): T { try { return parse() } catch (error) { if (error instanceof McpError) throw error throw new McpError("STATE_UNAVAILABLE", "Не подтверждён этап BGP export: " + phase, 409) } } async function readState(input: Record) { const serverId = Number(input.serverId), id = String(input.id), mode = modeSchema.parse(input.mode) const { server, client } = await routerClient(serverId) const serverProof = await privateSecretFingerprint(fingerprint(server), `bgp-export-server:${serverId}`) if (input.expectedServerProof !== undefined && input.expectedServerProof !== serverProof) throw new McpError("STATE_CONFLICT", "Назначение или credentials сервера BGP изменились; новое подключение не опрашивается", 409) const { connection: hydrated } = await readStaticBgpConnection(client, id) const localResponse = await client.post("/routing/bgp/connection/get", { ".id": id, "value-name": "output.redistribute" }) const localMode = parseState("локальное output.redistribute", () => bgpRedistributionMode(localResponse)) const templates = nativeBgpRows(await client.get("/routing/bgp/template")) const usedTemplates = new Map() const resolveTemplate = async (reference: string, stack: string[] = []): Promise => { const found = templates.filter(row => row[".id"] === reference || row.name === reference) if (found.length !== 1 || stack.length >= 16 || stack.includes(found[0][".id"])) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён граф шаблонов BGP", 409) const row = found[0], cached = usedTemplates.get(row[".id"]) if (typeof row.name !== "string" || !row.name.trim() || row.name.length > 100) throw new McpError("STATE_UNAVAILABLE", "Не подтверждено имя шаблона BGP", 409) if (cached) return cached.mode if (usedTemplates.size >= 100) throw new McpError("LIMIT_EXCEEDED", "Граф BGP превышает 100 шаблонов", 409) const [effective] = await readOspfEffectiveDisabled([row], nativeId => client.post("/routing/bgp/template/get", { ".id": nativeId, "value-name": "disabled" })) if (!["false", "no"].includes(String(effective.disabled))) throw new McpError("STATE_CONFLICT", "Используемый шаблон BGP отключён или его состояние неизвестно", 409) const setting = bgpRedistributionMode(await client.post("/routing/bgp/template/get", { ".id": row[".id"], "value-name": "output.redistribute" })) const refs = bgpTemplateReferences(await client.post("/routing/bgp/template/get", { ".id": row[".id"], "value-name": "templates" })) const parents: BgpExportMode[] = [] for (const ref of refs) parents.push(await resolveTemplate(ref, [...stack, row[".id"]])) if (new Set(parents).size > 1) throw new McpError("STATE_UNAVAILABLE", "Шаблоны BGP задают неоднозначный набор источников", 409) const result = setting ?? parents[0] ?? "disabled" const stable = { ...Object.fromEntries(Object.entries(effective).filter(([key]) => !["inactive", "invalid", "running"].includes(key) && !key.startsWith("debug."))), ".id": row[".id"], disabled: "false" } usedTemplates.set(row[".id"], { row: stable, mode: result, references: refs, localMode: setting }) return result } const templateRefs = bgpTemplateReferences(await client.post("/routing/bgp/connection/get", { ".id": id, "value-name": "templates" })) const inherited: BgpExportMode[] = [] for (const ref of templateRefs) inherited.push(await resolveTemplate(ref)) if (new Set(inherited).size > 1) throw new McpError("STATE_UNAVAILABLE", "BGP-подключение наследует неоднозначные источники", 409) const inheritedMode = inherited[0] ?? "disabled", currentMode = localMode ?? inheritedMode if (mode === "disabled" && currentMode !== "disabled" && inheritedMode !== "disabled") throw new McpError("STATE_CONFLICT", "Очистка output.redistribute может вернуть экспорт из шаблона; сначала измените наследование отдельным планом", 409) const connection = parseState("static/dynamic, disabled и явный instance/VRF/table", () => bgpExportConnection(hydrated, currentMode)) const sourceModes = input.sourceModes === undefined ? modes([currentMode, mode]) : modes(z.array(modeSchema).min(1).max(3).parse(input.sourceModes)) if (!sourceModes.includes(currentMode) || !sourceModes.includes(mode)) throw new McpError("STATE_CONFLICT", "Набор источников экспорта изменился", 409) const parentIds = ["bgp_instance", "vrf", "routing_table", "ipv4_address", "ipv6_address", "routing_filter"] const parents = await Promise.all(parentIds.map(resource => readRosSnapshot(serverId, resource))) if (parents.some(snapshot => snapshot.rows.length > 1000)) throw new McpError("LIMIT_EXCEEDED", "Каталог зависимостей BGP превышает 1000 объектов", 409) if (parents.filter(snapshot => ["ipv4_address", "ipv6_address", "routing_filter"].includes(snapshot.resource)).some(snapshot => snapshot.rows.some(row => typeof row[".id"] !== "string" || !row[".id"].trim() || row[".id"].length > 200))) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены native IDs адресов или фильтров BGP", 409) const rows = (resource: string) => parents.find(snapshot => snapshot.resource === resource)!.rows const unique = (resource: string, name: unknown) => { const found = rows(resource).filter(row => row.name === name) if (found.length !== 1 || typeof found[0][".id"] !== "string" || found[0].disabled === "true") throw new McpError("STATE_CONFLICT", "Не подтверждена зависимость экспорта BGP: " + resource, 409) return found[0] } const instance = unique("bgp_instance", connection.instance), vrf = unique("vrf", connection.vrf), table = unique("routing_table", connection["routing-table"]) 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 }, { kind: "bgp_instance", id: String(instance[".id"]), serverId }, { kind: "vrf", id: String(vrf[".id"]), serverId }, { kind: "routing_table", id: String(table[".id"]), serverId }, ...sources.map(row => ({ kind: row.family === 4 ? "ipv4_route" : "ipv6_route", id: row.id, serverId })), ...parents.filter(snapshot => ["ipv4_address", "ipv6_address", "routing_filter"].includes(snapshot.resource)).flatMap(snapshot => snapshot.rows.map(row => ({ kind: snapshot.resource, id: String(row[".id"]), serverId }))), ...[...usedTemplates.keys()].map(nativeId => ({ kind: "bgp_template", id: nativeId, serverId })), ] if (objects.some(row => !row.id || row.id === "undefined") || objects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены зависимости экспорта BGP", 409) const parentProof = parents.map(snapshot => ({ resource: snapshot.resource, rows: ["bgp_instance", "vrf", "routing_table"].includes(snapshot.resource) ? snapshot.rows.filter(row => row[".id"] === ({ bgp_instance: instance, vrf, routing_table: table } as Record)[snapshot.resource][".id"]) : snapshot.rows })) const templateProof = [...usedTemplates.values()].sort((a, b) => a.row[".id"].localeCompare(b.row[".id"])) 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, instanceContext, sources, templateProof }), `bgp-export-sources:${serverId}:${id}`) } return { server, client, connection, before, objects } } async function state(input: Record) { try { return await readState(input) } catch (error) { if (error instanceof McpError) throw error; throw new McpError("STATE_UNAVAILABLE", "Не подтверждены effective export, происхождение маршрутов или явный контекст BGP", 409) } } async function current(input: Record) { return (await state(input)).before } export function registerBgpExportActions(register: typeof add) { registerMcpService(service, { current, execute: async input => { const before = await state(input) if (fingerprint(before.before) !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "Подключение или источники BGP изменились после подтверждения", 409) const mode = modeSchema.parse(input.mode), expected = bgpExportConnection({ ...before.connection, ".id": String(input.id) }, mode) const receipt = { mode, connectionProof: await configurationProof(Number(input.serverId), String(input.id), expected), sourceProof: before.before.sourceProof, nativeDispatch: before.before.mode !== mode, forwardingVerified: false } if (before.before.mode !== mode) await executeGuardedApplicationWrite({ kind: "bgp-export", id: String(input.id) }, [Number(input.serverId)], async () => { const live = await state(input) if (fingerprint(live.before) !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "Источники BGP изменились перед записью", 409) await live.client.patch(`/routing/bgp/connection/${encodeURIComponent(String(input.id))}`, { "output.redistribute": nativeBgpExportValue(mode) }) }, async () => before.objects) return receipt }, verify: async (input, result) => { const expected = result as { mode: string; connectionProof: string; sourceProof: string }, saved = (await state(input)).before return saved.mode === expected.mode && saved.connectionProof === expected.connectionProof && saved.sourceProof === expected.sourceProof }, }) 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, steps: [{ kind: "service", service, input: request }], mutationCost: 1, requiresHuman: true, verificationScope: "configuration", warnings: ["Изменяется output.redistribute одного BGP-подключения. Connected/static экспортируют подходящие маршруты его явной таблицы; это не список разрешённых префиксов.", "Существующие input/output filters не изменяются; они могут разрешать или отклонять экспорт. Их конфигурация и исходные маршруты запечатаны в плане.", "Отключается только перераспределение connected/static. Output networks и default-originate не меняются; очистка в активный inherited export из шаблона отклоняется.", "Включение экспорта требует отдельного человеческого подтверждения. Проверяется конфигурация, обмен префиксами и forwarding требуют отдельных наблюдений.", "Поля TCP MD5 и исходные данные фильтров не выводятся: приватные proof привязаны к закрытому серверному ключу. Неопределённая запись не повторяется автоматически."] } }, }) }