Compare commits

...
3 Commits
Author SHA1 Message Date
Denozordec 94c50b9660 fix(mcp): разрешить правила обнаружения отказа по адресу соседа
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m46s
Docker images / backend-image (push) Successful in 2m44s
Docker images / frontend-image (push) Successful in 2m19s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-30 23:45:06 +07:00
Denozordec fc39b0da3c fix(mcp): учитывать контекст экземпляра при настройке маршрутизации
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m42s
Docker images / frontend-image (push) Successful in 2m17s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 2m36s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 22:40:29 +07:00
Denozordec 3c06a72349 fix(mcp): снимать свойство встроенного ключа туннеля вместо пустого значения
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m44s
Docker images / frontend-image (push) Successful in 5m2s
Docker images / updater-image (push) Successful in 4m40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m30s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 21:32:41 +07:00
16 changed files with 154 additions and 58 deletions

No files matched your search

+1 -1
View File
@@ -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) => {
+15 -5
View File
@@ -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,
@@ -36,11 +36,15 @@ export function registerGreMutationActions(register: typeof add) {
return receipt?.verified===true && fingerprint(await current(input))===receipt.afterFingerprint
}})
register(service,"mm_gre_tunnel_"+operation+"_plan","План "+["создания","изменения","удаления"][index]+" GRE и его внутренних адресов", "network","mm:network:write","write","servers",schemas[index],{
version: operation === "delete" ? 1 : 2,
prepare:async(input,context)=>{
const serverId = Number(input.serverId), {server} = await routerClient(serverId)
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
if (input.ipsecSecretRef && input.clearIpsecSecret) throw new McpError("INVALID_INPUT","Выберите новый PSK или явное удаление",400)
let mutation = greMutationSchema.parse({operation,...(operation==="create"?{fields:input.fields}:{...("rosId" in input?{rosId:input.rosId}:{}),...("name" in input?{name:input.name}:{}),...(operation==="update"?{fields:input.fields}:{})})})
if (mutation.operation === "update" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
mutation = { ...mutation, fields: { ...mutation.fields, ipsecSecret: "" } }
}
const state = await readGreMutationState(server,mutation), target = greTarget(mutation,state)
if (mutation.operation!=="delete" && (input.ipsecSecretRef || input.clearIpsecSecret)) {
const name = mutation.operation==="create"?mutation.fields.name:target?.name
let value = ""
@@ -69,6 +69,7 @@ export function registerGreRevisionActions(register:typeof add){
},
})
register(service,"mm_gre_revision_restore_plan","Восстановить GRE и все статические адреса из ревизии после подтверждения","network","mm:network:write","write","servers",z.object({serverId:z.number().int().positive().safe(),revisionId:z.string().uuid()}).strict(),{
version:2,
prepare:async(input,context)=>{
const req=request(input,context),source=await read(req,context.signal)
const desired=materializeGreRestore(source.revision.desired,source.state),steps=planGreRevisionRestore(desired,source.state)
@@ -34,14 +34,19 @@ const native=createServer(async(req,res)=>{
}
assert.ok(base,"Only typed GRE/address writes allowed")
writes++
if(base==="/interface/gre"&&data["ipsec-secret"]===""&&["yes","true"].includes(data["allow-fast-path"])){
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"failure: cannot enable fastpath together with ipsec yet"}));return
if(base==="/interface/gre"&&data["ipsec-secret"]===""){
res.statusCode=400;res.end(JSON.stringify({error:400,detail:"unexpected empty IPsec secret assignment"}));return
}
const fields=Object.fromEntries(Object.entries(data).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":String(v)]))
if(!ignored){
if(req.method==="PUT"){
const row=base==="/interface/gre"?{".id":"*G"+(++nextId),"local-address":"0.0.0.0",mtu:"1476",keepalive:"10s,10",dscp:"inherit",disabled:"false",dynamic:"false",running:"false","clamp-tcp-mss":"true","allow-fast-path":"true","ipsec-secret":"",comment:"",...fields}:{".id":"*A"+(++nextId),disabled:"false",dynamic:"false",invalid:"false",advertise:"false","no-dad":"false","eui-64":"false","from-pool":"",comment:"",...fields}
;(collections[base]??=[]).push(row)
}else if(req.method==="POST"&&path==="/interface/gre/unset"){
assert.equal(data["value-name"],"ipsec-secret")
const row=collections[base].find(r=>r[".id"]===data[".id"])
assert.ok(row)
row["ipsec-secret"]=""
}else if(req.method==="PATCH")Object.assign(collections[base].find(r=>r[".id"]===path.slice(base.length+1))!,fields)
else if(req.method==="DELETE")collections[base]=collections[base].filter(r=>r[".id"]!==path.slice(base.length+1))
else assert.fail("Unsupported native write")
@@ -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)
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -907,7 +907,7 @@ export function greInterfaceBody(t: GreSnapshotTunnel): Record<string, string> {
"allow-fast-path": t.allowFastPath ? "yes" : "no",
comment: writeGreComment(t.comment, peer),
disabled: rosYesNo(t.disabled),
"ipsec-secret": isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
"ipsec-secret": !t.ipsecSecret || isHiddenSecret(t.ipsecSecret) ? undefined : t.ipsecSecret,
})
}
+18 -1
View File
@@ -27,6 +27,7 @@ function apply(state:GreMutationState,op:RosWriteOp) {
next[key].push(row)
if (key==="gre") next.dependencies["/interface"].push({".id":"*C",name:row.name,type:"gre"})
} else if (op.op === "patch") Object.assign(next[key].find(row=>row[".id"]===id)!,body)
else if (op.op === "post" && op.path === "/interface/gre/unset") next.gre.find(row=>row[".id"]===body[".id"])!["ipsec-secret"] = ""
else if (op.op === "delete") {
next[key]=next[key].filter(row=>row[".id"]!==id)
if (key==="gre") next.dependencies["/interface"]=next.dependencies["/interface"].filter(row=>row[".id"]!==id)
@@ -40,6 +41,10 @@ let state = empty(), commands = 0
const ops = planGreMutation(server,create,state)
assert.equal(ops.length,3); assert.equal(ops[0].op,"put"); assert.equal("body" in ops[0]&&ops[0].body.disabled,"yes"); assert.equal(ops[2].path,"/interface/gre/@created")
assert.equal("body" in ops[0] && ops[0].body.mtu, "1476")
assert.ok("body" in ops[0] && !("ipsec-secret" in ops[0].body))
const createWithClear = greMutationSchema.parse({operation:"create",fields:{name:"clear-gre",remoteAddress:"192.0.2.2",ipsecSecret:""}})
const createWithClearOp = planGreMutation(server,createWithClear,state)[0]
assert.ok("body" in createWithClearOp && !("ipsec-secret" in createWithClearOp.body))
const autoCreate = greMutationSchema.parse({operation:"create",fields:{name:"own-gre",remoteAddress:"192.0.2.2",mtu:"auto"}})
const autoPut = planGreMutation(server,autoCreate,state)[0]
assert.equal("body" in autoPut && autoPut.body.mtu, "auto")
@@ -62,7 +67,19 @@ assert.equal(verifyGreMutationOp(autoState, autoAfter, autoPatch), false)
const commentPlan = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{mtu:1400}}),preserve)
assert.equal(commentPlan[0].op,"patch"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.keepalive,"1m,3"); assert.equal("body" in commentPlan[0]&&commentPlan[0].body.comment,native.comment); assert.ok(!("body" in commentPlan[0]&&"ipsec-secret" in commentPlan[0].body))
const clear = planGreMutation(server,greMutationSchema.parse({operation:"update",rosId:"*G",fields:{comment:"",remoteInnerIp:"",localAddress:"",ipsecSecret:""}}),preserve)
assert.equal(clear[0].op,"patch"); assert.equal("body" in clear[0]&&clear[0].body.comment,""); assert.equal("body" in clear[0]&&clear[0].body["ipsec-secret"],"")
assert.deepEqual(clear[0],{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
assert.equal(clear[1].op,"patch"); assert.equal("body" in clear[1]&&clear[1].body.comment,""); assert.ok("body" in clear[1]&&!("ipsec-secret" in clear[1].body))
const runningWithKey = structuredClone(preserve)
Object.assign(runningWithKey.gre[0], {disabled:"false","ipsec-secret":"fixture-key","allow-fast-path":"false"})
const clearRunning = greMutationSchema.parse({operation:"update",rosId:"*G",fields:{ipsecSecret:"",allowFastPath:true}})
const clearRunningOps = planGreMutation(server,clearRunning,runningWithKey)
assert.deepEqual(clearRunningOps.map(op=>op.op),["patch","post","patch","patch"])
assert.equal(verifyGreMutationOp(runningWithKey,runningWithKey,clearRunningOps[1]),false)
let afterClear = runningWithKey
const cleared = await executeGreMutationOps(clearRunning,runningWithKey,clearRunningOps,{read:async()=>afterClear,command:async op=>{afterClear=apply(afterClear,op)}})
assert.equal(cleared.verified,true)
assert.equal(afterClear.gre[0]["ipsec-secret"],"")
assert.equal(afterClear.gre[0].disabled,"false")
const collision = empty(); collision.dependencies["/interface"]=[{".id":"*E",name:"own-gre",type:"ether"}]
assert.throws(()=>planGreMutation(server,create,collision),/используется/)
assert.throws(()=>planGreMutation(server,greMutationSchema.parse({operation:"delete",rosId:"*G",name:"different"}),preserve),/разные/)
+25 -4
View File
@@ -12,6 +12,11 @@ import { greMutationSchema, greTunnelFromBody, type GreMutation } from "./gre-mu
import { assertGreDeleteDependencies, greMutationProblem, greMutationProof, greNativeValue, greStableRows, greTarget, readGreMutationState, type GreMutationState } from "./gre-mutation-state.js"
const same = (a: unknown,b: unknown) => fingerprint(a) === fingerprint(b)
export function greSecretUnsetOp(id: string): RosWriteOp {
return { op: "post", path: "/interface/gre/unset", body: { ".id": id, "value-name": "ipsec-secret" } }
}
export async function recordGreMutationRevision(server:ServerRow){
try{
const revisionRecorded=(await captureAndAppendRevision({serverId:server.id,section:"gre",source:"apply",capture:async()=>{
@@ -61,17 +66,29 @@ export function planGreMutation(server: ServerRow, input: GreMutation, before: G
const ops = planGreRestore({tunnels:[desired]},selected)
if (ops[0]?.op !== "patch") throw greMutationProblem("Не подготовлено изменение GRE")
const body = ops[0].body
if (fields.ipsecSecret === undefined) delete body["ipsec-secret"]
const clearSecret = fields.ipsecSecret === ""
if (!fields.ipsecSecret) delete body["ipsec-secret"]
else body["ipsec-secret"] = fields.ipsecSecret
if (fields.localAddress !== undefined) body["local-address"] = fields.localAddress || "0.0.0.0"
body.comment = fields.comment !== undefined || fields.remoteInnerIp !== undefined ? desired.comment : target.comment ?? ""
if (ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
if (!clearSecret && ops.length === 1 && Object.entries(body).every(([key,value])=>same(greNativeValue(key,target[key]),greNativeValue(key,value)))) throw greMutationProblem("GRE уже имеет запрошенную конфигурацию")
body.disabled = "yes"
if (clearSecret) {
// Clear even a configured empty value. RouterOS can create dynamic IKEv1 objects for it.
const path = ops[0].path
ops.unshift(greSecretUnsetOp(live.rosId))
if (!live.disabled) ops.unshift({ op: "patch", path, body: { disabled: "yes" } })
}
if (!desired.disabled) ops.push({op:"patch",path:"/interface/gre/"+live.rosId,body:{disabled:"no"}})
return ops
}
export function verifyGreMutationOp(before: GreMutationState, after: GreMutationState, op: RosWriteOp) {
if (op.op === "post" && op.path === "/interface/gre/unset" && op.body["value-name"] === "ipsec-secret") {
const id = op.body[".id"]
if (after.gre.find(row => row[".id"] === id)?.["ipsec-secret"] !== "") return false
return verifyGreMutationOp(before, after, { op: "patch", path: "/interface/gre/" + id, body: { "ipsec-secret": "" } })
}
const paths = {"/interface/gre":"gre","/ip/address":"ipv4","/ipv6/address":"ipv6"} as const
const path = Object.keys(paths).find(path=>op.path===path||op.path.startsWith(path+"/")) as keyof typeof paths|undefined
if (!path || !["put","patch","delete"].includes(op.op)) return false
@@ -79,8 +96,11 @@ export function verifyGreMutationOp(before: GreMutationState, after: GreMutation
const id = op.path === path ? undefined : decodeURIComponent(op.path.slice(path.length+1))
if (op.op === "put") {
const added = next[key].filter(row=>!prior[key].some(previous=>previous[".id"]===row[".id"]))
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key]) || !Object.entries(op.body).every(([field,value])=>same(greNativeValue(field,after[key].find(row=>row[".id"]===added[0][".id"])?.[field]),greNativeValue(field,value)))) return false
if (key!=="gre"&&observedBoolean(after[key].find(row=>row[".id"]===added[0][".id"])?.dynamic)!==false) return false
if (added.length !== 1 || !same(next[key].filter(row=>row!==added[0]),prior[key])) return false
const created = after[key].find(row => row[".id"] === added[0][".id"])
const expected = key === "gre" ? { "ipsec-secret": "", ...op.body } : op.body
if (!created || !Object.entries(expected).every(([field,value])=>same(greNativeValue(field,created[field]),greNativeValue(field,value)))) return false
if (key!=="gre"&&observedBoolean(created.dynamic)!==false) return false
// An address on our deliberately disabled GRE can legitimately be invalid.
// This proof confirms configuration, not link/DAD/forwarding readiness.
} else {
@@ -124,6 +144,7 @@ export async function mutateGreTunnel(server: ServerRow, raw: GreMutation, expec
const client = MikrotikClient.fromServer(fresh)
const receipt = await executeGreMutationOps(input,before,ops,{read:()=>readGreMutationState(fresh,input),...(input.operation==="delete"?{validate:(state:GreMutationState)=>{planGreMutation(fresh,input,state)}}:{}),command:op=>{
if (op.op === "put") return client.put(op.path,op.body)
if (op.op === "post") return client.post(op.path,op.body)
const slash = op.path.lastIndexOf("/"), path = op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
if (op.op === "delete") return client.delete(path)
if (op.op === "patch") return client.patch(path,op.body)
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState,greRestoreWireOp} from "./gre-revision-restore.js"
import {validateGreRestoreSnapshot,materializeGreRestore,planGreRevisionRestore,executeGreRevisionSteps,readGreRestoreState} from "./gre-revision-restore.js"
import {canonicalGreSnapshot,type GreSnapshot,type RosWriteOp} from "./entity-snapshots.js"
import {greDependencyPaths,type GreMutationState} from "./gre-mutation-state.js"
import {mapGreLive} from "./gre-live.js"
@@ -12,13 +12,6 @@ assert.equal(expiredAccess,0)
const empty=():GreMutationState=>({serverConfiguration:"source",restoreProtectionProof:"protections",gre:[],ipv4:[],ipv6:[],dependencies:Object.fromEntries(greDependencyPaths.map(p=>[p,[]])),bindings:[],filters:[]})
const native={".id":"*G",name:"old","local-address":"192.0.2.1","remote-address":"192.0.2.2",mtu:"1476",keepalive:"1m,3",dscp:"inherit",disabled:"false",dynamic:"false",running:"true","clamp-tcp-mss":"true","allow-fast-path":"false","ipsec-secret":" key ",comment:"old-comment","dont-fragment":"yes"}
const wanted=(name:string)=>({name,localAddress:"",remoteAddress:"192.0.2.2",localInnerIp:"",remoteInnerIp:"",innerAddresses:[],comment:"",disabled:false,mtu:1400,keepalive:"0",dscp:"inherit",clampTcpMss:true,allowFastPath:false,ipsecSecret:""})
const defaultCreate:RosWriteOp={op:"put",path:"/interface/gre",body:{name:"gre","ipsec-secret":"","allow-fast-path":"yes"}}
const defaultWire=greRestoreWireOp(defaultCreate,empty())
assert.ok("body"in defaultWire&&!("ipsec-secret"in defaultWire.body));assert.equal(defaultCreate.body["ipsec-secret"],"")
const keyState=empty();keyState.gre=[{...native}]
const clearKey:RosWriteOp={op:"patch",path:"/interface/gre/*G",body:{"ipsec-secret":"","allow-fast-path":"no"}}
assert.equal(greRestoreWireOp(clearKey,keyState),clearKey,"A real key removal must not be silently omitted")
keyState.gre[0]["ipsec-secret"]="";assert.ok("body"in greRestoreWireOp(clearKey,keyState)&&!("ipsec-secret"in(greRestoreWireOp(clearKey,keyState)as{body:Record<string,string>}).body))
const snapshot=(...names:string[])=>canonicalGreSnapshot({tunnels:names.map(wanted)})
let sequence=0
function apply(state:GreMutationState,op:RosWriteOp){
@@ -26,10 +19,11 @@ function apply(state:GreMutationState,op:RosWriteOp){
const key=path==="/interface/gre"?"gre":path==="/ip/address"?"ipv4":"ipv6",id=op.path.slice(path.length+1)
const body="body"in op?Object.fromEntries(Object.entries(op.body).map(([k,v])=>[k,v==="yes"?"true":v==="no"?"false":v])):{}
if(op.op==="put"){
const added={...(key==="gre"?native:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
const added={...(key==="gre"?{...native,"ipsec-secret":""}:{dynamic:"false",invalid:"false","no-dad":"false","eui-64":"false","from-pool":""}),...body,".id":"*N"+(++sequence)}
next[key].push(added)
if(key==="gre")next.dependencies["/interface"].push({".id":added[".id"],name:added.name,type:"gre"})
}else if(op.op==="patch")Object.assign(next[key].find(r=>r[".id"]===id)!,body)
else if(op.op==="post"&&op.path==="/interface/gre/unset")next.gre.find(r=>r[".id"]===body[".id"])!["ipsec-secret"]=""
else if(op.op==="delete"){
next[key]=next[key].filter(r=>r[".id"]!==id)
if(key==="gre")next.dependencies["/interface"]=next.dependencies["/interface"].filter(r=>r[".id"]!==id)
@@ -74,6 +68,13 @@ assert.deepEqual(state.ipv6.find(r=>r.interface==="ether1"),original.ipv6[0]);as
const firstAddress=commands.findIndex(op=>!op.path.startsWith("/interface/gre")),oldDisable=commands.findIndex(op=>op.path==="/interface/gre/*G"&&"body"in op&&op.body.disabled==="yes")
assert.ok(oldDisable>=0&&oldDisable<firstAddress);assert.ok(commands.slice(-2).every(op=>"body"in op&&op.body.disabled==="no"))
assert.deepEqual(planGreRevisionRestore(fixed,state),[])
assert.ok(commands.every(op=>!("body" in op)||op.body["ipsec-secret"]!==""))
const clearRevision=structuredClone(fixed)
clearRevision.tunnels.find(row=>row.name==="old")!.ipsecSecret=""
commands=[]
assert.equal((await execute(clearRevision)).verified,true)
assert.deepEqual(commands.find(op=>op.op==="post"),{op:"post",path:"/interface/gre/unset",body:{".id":"*G","value-name":"ipsec-secret"}})
assert.ok(commands.every(op=>!("body" in op)||!("ipsec-secret" in op.body)))
const deletion=planGreRevisionRestore({tunnels:[]},original)
assert.deepEqual(deletion[0],{kind:"native",op:{op:"patch",path:"/interface/gre/*G",body:{disabled:"yes"}}})
assert.equal(deletion.at(-1)?.kind,"native");state=structuredClone(original);commands=[]
+11 -17
View File
@@ -9,7 +9,7 @@ import { canonicalGreSnapshot,greAddressKey,greAddressPath,greInterfaceBody,isHi
import { mapGreLive } from "./gre-live.js"
import { greMtuSchema } from "./gre-mutation-input.js"
import { assertGreDeleteDependencies,greMutationProblem,greMutationProof,greNativeValue,readGreMutationState,type GreMutationState } from "./gre-mutation-state.js"
import { verifyGreMutationOp } from "./gre-mutation.js"
import { greSecretUnsetOp, verifyGreMutationOp } from "./gre-mutation.js"
import { observedBoolean } from "./ospf-observed-values.js"
import { MikrotikClient } from "./mikrotik.js"
import { withApplicationMutationLock,withConfigMutationLock } from "./config-mutation-lock.js"
@@ -69,17 +69,6 @@ export function materializeGreRestore(desired:GreSnapshot,before:GreMutationStat
})})
}
export type GreRestoreStep={kind:"native";op:RosWriteOp}|{kind:"enable";name:string}
/** RouterOS treats presence of an empty ipsec-secret as an IPsec write and
* rejects it together with FastPath. Omit a redundant empty assignment on the
* wire only; per-command verification still uses the original expected body. */
export function greRestoreWireOp(op:RosWriteOp,before:GreMutationState):RosWriteOp{
if((op.op!=="put"&&op.op!=="patch")||op.body["ipsec-secret"]!=="")return op
const creating=op.op==="put"&&op.path==="/interface/gre"
const live=op.op==="patch"&&op.path.startsWith("/interface/gre/")?before.gre.find(row=>row[".id"]===decodeURIComponent(op.path.slice("/interface/gre/".length))):undefined
if(!creating&&live?.["ipsec-secret"]!=="")return op
const body={...op.body};delete body["ipsec-secret"]
return{...op,body}
}
export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationState):GreRestoreStep[]{
const wanted=new Set(desired.tunnels.map(row=>row.name))
for(const live of before.gre){
@@ -95,10 +84,15 @@ export function planGreRevisionRestore(desired:GreSnapshot,before:GreMutationSta
let op=item
if((op.op==="put"&&op.path==="/interface/gre")||(op.op==="patch"&&op.path.startsWith("/interface/gre/"))){
const want=desired.tunnels.find(row=>row.name===("body"in op?op.body.name:undefined))!
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??"","ipsec-secret":want.ipsecSecret}
const body:Record<string,string>={...op.body,"local-address":want.localAddress||"0.0.0.0",comment:greInterfaceBody(want).comment??""}
const live=before.gre.find(row=>row.name===want.name)
const clearSecret=live&&Boolean(live["ipsec-secret"])&&!want.ipsecSecret
const addressChanges=legacy.some(row=>!row.path.startsWith("/interface/gre")&&("body"in row?row.body.interface===want.name:mapped.addrs.some(a=>a.interfaceName===want.name&&row.path===greAddressPath(a.address)+"/"+a.rosId)))
if(live&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
if(live&&!clearSecret&&Object.entries(body).every(([key,value])=>same(greNativeValue(key,live[key]),greNativeValue(key,value)))&&!addressChanges)continue
if(live&&clearSecret){
if(observedBoolean(live.disabled)===false)staging.push({kind:"native",op:{op:"patch",path:op.path,body:{disabled:"yes"}}})
staging.push({kind:"native",op:greSecretUnsetOp(live[".id"])})
}
body.disabled="yes";op={...op,body};if(!want.disabled)enable.add(want.name)
staging.push({kind:"native",op});continue
}
@@ -132,12 +126,12 @@ export async function restoreGreRevision(server:ServerRow,id:string,options:{bef
const desired=options.desired?validateGreRestoreSnapshot(options.desired):materializeGreRestore(revision.desired,before),steps=planGreRevisionRestore(desired,before),client=MikrotikClient.fromServer(server)
const checkRevision=async()=>{if((await readGreRestoreRevision(server.id,id,authorize)).revisionProof!==revision.revisionProof)throw problem("Ревизия изменилась во время GRE restore")}
const receipt=await executeGreRevisionSteps(before,steps,{read:()=>readGreRestoreState(server,authorize,undefined,deadlineAt),authorizeRevision:checkRevision,validate:state=>{planGreRevisionRestore(desired,state)},command:(op,gate)=>{
const wire=greRestoreWireOp(op,before)
const slash=op.path.lastIndexOf("/"),path=op.path.slice(0,slash+1)+encodeURIComponent(op.path.slice(slash+1))
const timeout=Math.max(1,Math.min(op.op==="delete"?10000:15000,deadlineAt-Date.now()))
if(wire.op==="put")return client.put(wire.path,wire.body,timeout,gate)
if(op.op==="put")return client.put(op.path,op.body,timeout,gate)
if(op.op==="post")return client.post(op.path,op.body,timeout,undefined,gate)
if(op.op==="delete")return client.delete(path,timeout,gate)
if(wire.op==="patch")return client.patch(path,wire.body,timeout,gate)
if(op.op==="patch")return client.patch(path,op.body,timeout,gate)
throw problem("Недопустимая команда GRE restore")
}})
const verified=receipt.verified&&planGreRevisionRestore(desired,receipt.after).length===0
+23 -4
View File
@@ -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)
+12 -2
View File
@@ -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)