Compare commits

..
4 Commits
Author SHA1 Message Date
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
Denozordec ea13365f37 fix(mcp): принимать перечень команд при выполнении плана туннеля
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m46s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 2m25s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 20:00:42 +07:00
Denozordec 8a962c1984 fix(mcp): продолжать настройку туннелей со штатным набором алгоритмов
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m34s
Docker images / frontend-image (push) Successful in 2m23s
Docker images / updater-image (push) Successful in 46s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / backend-image (push) Successful in 2m8s
Docker images / publish-release (push) Successful in 15s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 19:28:43 +07:00
16 changed files with 322 additions and 97 deletions

No files matched your search

+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,
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import test from "node:test"
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
import { greIke2SideCommands, greIke2StableCatalogues, validateNewPairSide, verifyGreIke2Create } from "./gre-ikev2-pair-actions.js"
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, greIke2StepInput, greIke2StepSchema, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
import { redact } from "./security.js"
const pair = { endpoints: [
@@ -13,11 +13,10 @@ const empty = () => Object.fromEntries(Object.values(greIpsecPaths).map(path =>
test("emits the IX transport suite with a fixed GRE selector and independent identities", () => {
const [left, right] = ([0, 1] as const).map(side => greIke2SideCommands(pair, side, secret))
assert.equal(left.length, 7)
assert.equal(right.length, 7)
for (const path of [greIpsecPaths.profile, greIpsecPaths.proposal]) {
assert.deepEqual(left.find(command => command.path === path), right.find(command => command.path === path))
}
assert.equal(left.length, 6)
assert.equal(right.length, 6)
assert.equal(left.some(command => command.path === greIpsecPaths.proposal), false)
assert.deepEqual(left.find(command => command.path === greIpsecPaths.profile), right.find(command => command.path === greIpsecPaths.profile))
assert.equal(left.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "true")
assert.equal(right.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "false")
assert.equal(left.find(command => command.path === greIpsecPaths.identity)?.fields.secret, secret)
@@ -28,6 +27,7 @@ test("emits the IX transport suite with a fixed GRE selector and independent ide
assert.deepEqual([leftPolicy["src-address"], leftPolicy["dst-address"], leftPolicy.protocol, leftPolicy.level, leftPolicy.tunnel],
["192.0.2.3/32", "198.51.100.6/32", "gre", "require", "false"])
assert.equal(rightPolicy["src-address"], leftPolicy["dst-address"])
assert.equal(leftPolicy.proposal, "default")
assert.equal(rightPolicy["dst-address"], leftPolicy["src-address"])
assert.deepEqual(left.slice(0, 2).map(command => command.fields["ipsec-policy"]), ["in,none", "out,none"])
})
@@ -36,15 +36,55 @@ test("rejects existing objects and opposing IPv4 selectors without touching othe
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty()
catalogs[greIpsecPaths.policy].push({ ".id": "*A", template: "true", protocol: "all", "src-address": "0.0.0.0/0", "dst-address": "0.0.0.0/0" })
catalogs[greIpsecPaths.peer].push({ ".id": "*B", address: "0.0.0.0/0", "exchange-mode": "ike2" })
assert.doesNotThrow(() => validateNewPairSide(pair, 0, catalogs, commands))
assert.doesNotThrow(() => planGreIke2Side(pair, 0, catalogs, commands))
catalogs[greIpsecPaths.policy].push({ ".id": "*C", "src-address": "192.0.2.0/24", "dst-address": "198.51.100.0/24", protocol: "all" })
assert.throws(() => validateNewPairSide(pair, 0, catalogs, commands), /перекрывает GRE/)
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /перекрывает GRE/)
catalogs[greIpsecPaths.policy].pop()
catalogs[greIpsecPaths.peer].push({ ".id": "*D", address: "198.51.100.6/32", "exchange-mode": "ike2" })
assert.throws(() => validateNewPairSide(pair, 0, catalogs, commands), /Уже настроен IKEv2 peer/)
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /Уже настроен IKEv2 peer/)
catalogs[greIpsecPaths.peer].pop()
catalogs[greIpsecPaths.filter].push({ ".id": "*E", comment: commands[0].fields.comment! })
assert.throws(() => validateNewPairSide(pair, 0, catalogs, commands), /уже присутствуют/)
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /изменённый объект/)
})
test("checks the existing defaults for a common encrypted suite and equal PFS", () => {
const catalogs = empty()
const first = { ".id": "*A", name: "default", "pfs-group": "modp1024", "enc-algorithms": "3des,aes-128-cbc,aes-256-cbc", "auth-algorithms": "sha1,sha256" }
catalogs[greIpsecPaths.proposal].push(first)
assert.equal(greIke2DefaultProposal(catalogs), first)
const second = { ...first, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256" }
assert.doesNotThrow(() => validateGreIke2Defaults(first, second))
assert.throws(() => validateGreIke2Defaults(first, { ...second, "pfs-group": "modp2048" }), /несовместимы/)
assert.throws(() => validateGreIke2Defaults(first, { ...second, "enc-algorithms": "null" }), /несовместимы/)
})
test("resumes a partial side and changes only the verified old test policy's proposal", () => {
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty()
const name = commands.find(command => command.path === greIpsecPaths.profile)!.fields.name!
for (const [index, command] of commands.entries()) catalogs[command.path].push({ ...command.fields, ".id": `*${index + 1}` })
const [policy] = catalogs[greIpsecPaths.policy]
policy.proposal = name
const [patch] = planGreIke2Side(pair, 0, catalogs, commands)
assert.deepEqual(patch, { path: greIpsecPaths.policy, id: policy[".id"], fields: { proposal: "default" } })
const after = structuredClone(catalogs)
delete after[greIpsecPaths.policy][0].proposal
assert.equal(verifyGreIke2Update(catalogs, after, patch), true)
assert.deepEqual(planGreIke2Side(pair, 0, after, commands), [])
after[greIpsecPaths.policy][0].level = "use"
assert.equal(verifyGreIke2Update(catalogs, after, patch), false)
})
test("the runner can parse the prepared plan after its JSON round trip", () => {
const planned = greIke2StepInput(pair, 0, secret, "source-proof", [
{ path: greIpsecPaths.peer, fields: {} },
{ path: greIpsecPaths.policy, id: "*4", fields: { proposal: "default" } },
])
assert.deepEqual(greIke2StepSchema.parse(JSON.parse(JSON.stringify(planned))), planned)
assert.deepEqual(planned.writes, [
{ path: greIpsecPaths.peer, action: "create" },
{ path: greIpsecPaths.policy, id: "*4", action: "update" },
])
assert.throws(() => greIke2StepSchema.parse({ ...planned, writes: [{ path: greIpsecPaths.proposal, id: "*4", action: "update" }] }))
})
test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => {
+121 -31
View File
@@ -22,16 +22,30 @@ const endpoint = z.object({
outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"),
}).strict()
const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict()
const stepSchema = schema.extend({ side: z.union([z.literal(0), z.literal(1)]), ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/), beforeFingerprint: z.string() })
const writePath = z.enum([greIpsecPaths.filter, greIpsecPaths.profile, greIpsecPaths.peer, greIpsecPaths.identity, greIpsecPaths.policy])
export const greIke2StepSchema = schema.extend({
side: z.union([z.literal(0), z.literal(1)]),
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
beforeFingerprint: z.string(),
writes: z.array(z.discriminatedUnion("action", [
z.object({ path: writePath, action: z.literal("create") }).strict(),
z.object({ path: z.literal(greIpsecPaths.policy), action: z.literal("update"), id: z.string().regex(/^\*[a-z0-9]+$/i) }).strict(),
])).max(6),
})
type Pair = z.infer<typeof schema>
type Side = 0 | 1
type Fields = Record<string, string>
type Catalogue = Record<string, Fields[]>
type RouterWrite = { path: string; fields: Fields; id?: string }
export function greIke2StepInput(input: Pair, side: Side, ipsecSecret: string, beforeFingerprint: string, commands: RouterWrite[]) {
const writes = commands.map(({ path, id }) => id ? { path, id, action: "update" } : { path, action: "create" })
return greIke2StepSchema.parse({ endpoints: input.endpoints, side, ipsecSecret, beforeFingerprint, writes })
}
const sides = [0, 1] as const
const paths = Object.values(greIpsecPaths)
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
[greIpsecPaths.filter]: new Set(["bytes", "packets"]),
[greIpsecPaths.policy]: new Set(["active", "ph2-count", "ph2-state"]),
[greIpsecPaths.policy]: new Set(["active", "invalid", "ph2-count", "ph2-state"]),
}
function target(input: Pair): ChangeEvidence["target"] {
@@ -50,9 +64,9 @@ export function greIke2SideCommands(input: Pair, side: Side, secret: string) {
return [
{ path: greIpsecPaths.filter, fields: { ...inbound, comment: `${name}:plain-in` } },
{ path: greIpsecPaths.filter, fields: { ...outbound, comment: `${name}:plain-out` } },
...(["profile", "proposal", "peer"] as const).map(kind => ({ path: greIpsecPaths[kind], fields: fields[kind] })),
...(["profile", "peer"] as const).map(kind => ({ path: greIpsecPaths[kind], fields: fields[kind] })),
{ path: greIpsecPaths.identity, fields: { ...fields.identity, comment: `${name}:identity` } },
{ path: greIpsecPaths.policy, fields: { ...fields.policy, comment: `${name}:policy` } },
{ path: greIpsecPaths.policy, fields: { ...fields.policy, proposal: "default", comment: `${name}:policy` } },
] satisfies Array<{ path: string; fields: Fields }>
}
@@ -66,21 +80,59 @@ function includesIp(selector: string | undefined, address: string) {
return inIxNetwork(`${host}/${length ?? "32"}`, address)
}
export function validateNewPairSide(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>) {
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress
if (commands.some(command => catalogs[command.path].some(row => row.name === name || ("comment" in command.fields && row.comment === command.fields.comment)))) {
throw new McpError("STATE_CONFLICT", "Объекты этой пары IKEv2 уже присутствуют. Требуется сверка обеих сторон", 409)
function ownedRows(catalogs: Catalogue, command: RouterWrite) {
return catalogs[command.path].filter(row => command.fields.comment ? row.comment === command.fields.comment : row.name === command.fields.name)
}
export function greIke2DefaultProposal(catalogs: Catalogue) {
const rows = catalogs[greIpsecPaths.proposal].filter(row => row.name === "default")
const row = rows[0]
if (rows.length !== 1 || observedBoolean(row.disabled) === true || !row["pfs-group"] || !row["enc-algorithms"] || row["auth-algorithms"] === undefined) {
throw new McpError("STATE_UNAVAILABLE", "Не подтверждены действующие параметры IPsec proposal default", 502)
}
if (catalogs[greIpsecPaths.peer].some(row => row["exchange-mode"] === "ike2" && observedBoolean(row.disabled) !== true &&
return row
}
export function validateGreIke2Defaults(first: Fields, second: Fields) {
const list = (row: Fields, field: string) => row[field].split(",").map(value => value.trim())
const shared = (field: string) => list(first, field).filter(value => list(second, field).includes(value))
const encryption = shared("enc-algorithms").filter(value => !!value && value !== "null")
const compatible = first["pfs-group"] === second["pfs-group"] && encryption.some(value => value.endsWith("-gcm") || value === "chacha20-poly1305" || shared("auth-algorithms").some(auth => !!auth && auth !== "null"))
if (!compatible || (list(first, "enc-algorithms").includes("null") && list(second, "enc-algorithms").includes("null"))) {
throw new McpError("DEPENDENCY_CONFLICT", "IPsec proposal default на двух CHR несовместимы или допускают GRE без шифрования", 409)
}
}
export function planGreIke2Side(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>): RouterWrite[] {
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress
if (catalogs[greIpsecPaths.peer].some(row => row.name !== name && row["exchange-mode"] === "ike2" && observedBoolean(row.disabled) !== true &&
[remote, `${remote}/32`].includes(row.address) && (!row["local-address"] || ["0.0.0.0", local].includes(row["local-address"])))) {
throw new McpError("DEPENDENCY_CONFLICT", "Уже настроен IKEv2 peer для этих внешних адресов", 409)
}
if (catalogs[greIpsecPaths.policy].some(row => observedBoolean(row.template) !== true && observedBoolean(row.disabled) !== true &&
if (catalogs[greIpsecPaths.policy].some(row => row.comment !== `${name}:policy` && observedBoolean(row.template) !== true && observedBoolean(row.disabled) !== true &&
[undefined, "", "all", "0", "255", "gre", "47"].includes(row.protocol) &&
((includesIp(row["src-address"], local) && includesIp(row["dst-address"], remote)) ||
(includesIp(row["src-address"], remote) && includesIp(row["dst-address"], local))))) {
throw new McpError("DEPENDENCY_CONFLICT", "Существующая IPsec policy перекрывает GRE между выбранными адресами", 409)
}
return commands.flatMap<RouterWrite>(command => {
const found = ownedRows(catalogs, command), row = found[0]
if (!row) return [command]
if (found.length === 1 && observedBoolean(row.dynamic) !== true && observedBoolean(row.builtin) !== true && observedBoolean(row.disabled) !== true) {
if (matches(command.fields, row)) {
if (command.path === greIpsecPaths.filter && catalogs[command.path].slice(0, catalogs[command.path].indexOf(row)).some(previous =>
observedBoolean(previous.dynamic) !== true && observedBoolean(previous.disabled) !== true && previous.chain === row.chain && previous.action !== "drop" &&
[undefined, "", "all", "0", "255", "gre", "47"].includes(previous.protocol) && !previous["ipsec-policy"]?.endsWith(",ipsec"))) {
throw new McpError("DEPENDENCY_CONFLICT", "Правило против незашифрованного GRE находится после правила, которое может пропустить его", 409)
}
return []
}
if (command.path === greIpsecPaths.policy && matches({ ...command.fields, proposal: name }, row)) {
return [{ path: command.path, id: row[".id"], fields: { proposal: "default" } }]
}
}
throw new McpError("STATE_CONFLICT", `Пара IKEv2 имеет неоднозначный или изменённый объект в ${command.path}`, 409)
})
}
export function greIke2StableCatalogues(catalogs: Catalogue) {
@@ -95,10 +147,38 @@ function matches(expected: Fields, observed: Fields) {
if (["disabled", "tunnel", "passive"].includes(key)) return (observedBoolean(actual) ?? (actual === undefined ? false : null)) === observedBoolean(value)
if (["address", "src-address", "dst-address"].includes(key)) return actual?.replace(/\/32$/, "") === value.replace(/\/32$/, "")
if (key === "protocol" && value === "gre") return actual === "gre" || actual === "47"
if (key === "proposal" && value === "default") return actual === undefined || actual === "default"
return actual === value
})
}
export function verifyGreIke2Update(before: Catalogue, after: Catalogue, command: RouterWrite) {
const source = before[command.path].find(row => row[".id"] === command.id)
const observed = after[command.path].find(row => row[".id"] === command.id)
if (!source || !observed || !matches(command.fields, observed)) return false
const projected = { ...source }
for (const key of Object.keys(command.fields)) {
if (observed[key] === undefined) delete projected[key]
else projected[key] = observed[key]
}
return fingerprint({ ...before, [command.path]: before[command.path].map(row => row === source ? projected : row) }) === fingerprint(after)
}
function pairSecret(input: Pair, sides: Catalogue[]) {
const name = nameFor(input)
const identities = sides.flatMap(catalogs => catalogs[greIpsecPaths.identity].filter(row => row.comment === `${name}:identity`))
const values = new Set(identities.map(row => row.secret))
if (values.size === 0) return randomBytes(32).toString("hex")
const [value] = values
if (values.size !== 1 || typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) throw new McpError("STATE_CONFLICT", "Не подтверждён общий PSK частично настроенной пары", 409)
return value
}
function completedPairProof(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>) {
if (planGreIke2Side(input, side, catalogs, commands).length !== 0) throw new McpError("VERIFICATION_FAILED", "IKEv2 остался настроен не полностью", 502)
return fingerprint({ proposal: greIke2DefaultProposal(catalogs), objects: commands.map(command => ({ path: command.path, id: ownedRows(catalogs, command)[0][".id"] })) })
}
export function verifyGreIke2Create(before: Catalogue, after: Catalogue, command: { path: string; fields: Fields }, nativeId: string | undefined, first: string | undefined) {
const created = after[command.path].find(row => row[".id"] === nativeId)
return !!created && !before[command.path].some(row => row[".id"] === nativeId) && matches(command.fields, created) &&
@@ -126,28 +206,34 @@ async function readSide(input: Pair, side: Side) {
export function registerGreIke2PairActions(register: typeof add) {
registerMcpService(operation, {
current: async raw => {
const input = stepSchema.parse(raw)
const input = greIke2StepSchema.parse(raw)
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
},
execute: async raw => {
const input = stepSchema.parse(raw), side = input.side, state = await readSide(input, side)
const input = greIke2StepSchema.parse(raw), side = input.side, state = await readSide(input, side)
if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409)
const commands = greIke2SideCommands(input, side, input.ipsecSecret)
validateNewPairSide(input, side, state.catalogs, commands)
const desired = greIke2SideCommands(input, side, input.ipsecSecret)
const commands = planGreIke2Side(input, side, state.catalogs, desired)
const reviewed = greIke2StepInput(input, side, input.ipsecSecret, state.proof, commands).writes
if (fingerprint(reviewed) !== fingerprint(input.writes)) throw new McpError("STATE_CONFLICT", "Подготовленные команды IKEv2 отличаются от плана", 409)
let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0
for (const command of commands) {
let dispatched = false
try {
const first = command.path === greIpsecPaths.filter ? before[command.path][0]?.[".id"] : undefined
const ack = await state.client.put<Fields>(command.path, { ...command.fields, ...(first ? { "place-before": first } : {}) }, 10000, async () => {
const fence = async () => {
await assertVerifiedConfigurationAccess()
if (fingerprint((await routerClient(Number(state.server.id))).server) !== fingerprint(state.server)) throw new McpError("STATE_CONFLICT", "Источник RouterOS изменился перед записью", 409)
if (fingerprint(greIke2StableCatalogues(await state.readCatalogues())) !== fingerprint(before)) throw new McpError("STATE_CONFLICT", "IPsec изменился перед записью", 409)
dispatched = true
})
}
const ack = command.id
? await state.client.patch<Fields>(`${command.path}/${encodeURIComponent(command.id)}`, command.fields, 10000, fence)
: await state.client.put<Fields>(command.path, { ...command.fields, ...(first ? { "place-before": first } : {}) }, 10000, fence)
confirmed++
const after = greIke2StableCatalogues(await state.readCatalogues())
if (!verifyGreIke2Create(before, after, command, ack?.[".id"], first)) {
const exact = command.id ? verifyGreIke2Update(before, after, command) : verifyGreIke2Create(before, after, command, ack?.[".id"], first)
if (!exact) {
throw new McpError("VERIFICATION_FAILED", "Ответ RouterOS не подтверждает точное добавление объекта", 502)
}
before = after
@@ -159,31 +245,35 @@ export function registerGreIke2PairActions(register: typeof add) {
}
}
const after = await readSide(input, side)
if (fingerprint(greIke2StableCatalogues(after.catalogs)) !== fingerprint(before)) throw new IpsecServerInitExecutionError("VERIFICATION_FAILED", "Состояние IPsec изменилось после последней команды", confirmed, verified, commands.length)
return { verified: true, commandCount: commands.length, afterFingerprint: after.proof, greEnabled: false, forwardingVerified: false }
const afterFingerprint = completedPairProof(input, side, after.catalogs, desired)
return { verified: true, commandCount: commands.length, afterFingerprint, greEnabled: false, forwardingVerified: false }
},
verify: async (raw, result) => {
const input = stepSchema.parse(raw)
const input = greIke2StepSchema.parse(raw)
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
return receipt?.verified === true && receipt.afterFingerprint === (await readSide(input, input.side)).proof
return receipt?.verified === true && receipt.afterFingerprint === completedPairProof(input, input.side,
(await readSide(input, input.side)).catalogs, greIke2SideCommands(input, input.side, input.ipsecSecret))
},
})
register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, {
version: 3,
target: raw => target(schema.parse(raw)),
prepare: async raw => {
const input = schema.parse(raw), scope = target(input), ipsecSecret = randomBytes(32).toString("hex")
const input = schema.parse(raw), scope = target(input)
const before = await Promise.all(sides.map(side => readSide(input, side)))
const steps = sides.map(side => {
const commands = greIke2SideCommands(input, side, ipsecSecret)
validateNewPairSide(input, side, before[side].catalogs, commands)
return { kind: "service" as const, service: operation, input: { ...input, side, ipsecSecret, beforeFingerprint: before[side].proof } }
})
const catalogs = before.map(state => state.catalogs)
validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1]))
const ipsecSecret = pairSecret(input, catalogs)
const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret)))
const steps = sides.map(side => ({ kind: "service" as const, service: operation,
input: greIke2StepInput(input, side, ipsecSecret, before[side].proof, changes[side]),
}))
const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat()
return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: 14, requiresHuman: true,
return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: Math.max(1, changes.flat().length), requiresHuman: true,
warnings: [
`На каждом CHR создаются выделенные объекты ${nameFor(input)}: profile, proposal, peer, identity, статическая policy GRE в транспортном режиме и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
"Существующие GRE остаются отключёнными. PSK автоматически создаётся для пары. Глобальные IPsec-профили не меняются. Для IKE/ESP требуются разрешения действующего firewall.",
"Планы проверяются и применяются последовательно. При сбое требуется сверить уже добавленные объекты до повтора. IPsec SA и прохождение трафика проверяются после отдельного включения GRE.",
`На каждом CHR настраиваются выделенные объекты ${nameFor(input)}: profile, peer, identity, транспортная policy GRE с proposal default и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
"GRE остаются отключёнными. Proposal default используется после проверки совместимости и не изменяется. Для IKE/ESP требуются разрешения действующего firewall.",
"Ранее созданные объекты пары переиспользуются только при совпадении параметров. У старой политики пары разрешена смена proposal на default. IPsec SA проверяется после отдельного включения GRE.",
],
}
},
@@ -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")
@@ -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)
+1 -1
View File
@@ -137,7 +137,7 @@ npm --prefix backend run mcp:stdio
Применение создаёт две отключённые стороны. Сверьте обе через `mm_gre_state_get`, затем включите их через `mm_gre_tunnel_update_plan` и проверьте IPsec и связность. При ошибке сверяйте обе стороны перед следующей операцией. Первая сторона может остаться созданной и отключённой.
Для выделенных профилей, как в управляемом GRE/IPsec на IX, используйте `mm_gre_ikev2_pair_configure_plan` с допуском `network.gre.ikev2_pair.configure`. Ему нужны два существующих отключённых GRE с выключенным FastPath и пустым `ipsec-secret`. Передайте в `endpoints` по одному объекту с `serverId`, `greName` и локальным `outerAddress`. Первая сторона отвечает на IKEv2, вторая инициирует соединение. Manager создаёт отдельные профили, общий PSK для пары и статические политики транспортного режима только для GRE между этими адресами. После проверки плана включите GRE отдельно и проверьте SA и связность. Если ранее для GRE был задан встроенный PSK, очистите его через `mm_gre_tunnel_update_plan` с `clearIpsecSecret: true` при отключённом интерфейсе.
Для выделенных профилей, как в управляемом GRE/IPsec на IX, используйте `mm_gre_ikev2_pair_configure_plan` с допуском `network.gre.ikev2_pair.configure`. Ему нужны два существующих отключённых GRE с выключенным FastPath и пустым `ipsec-secret`. Передайте в `endpoints` по одному объекту с `serverId`, `greName` и локальным `outerAddress`. Первая сторона отвечает на IKEv2, вторая инициирует соединение. Manager создаёт отдельные профили, общий PSK для пары и статические политики транспортного режима только для GRE между этими адресами. Политики используют существующие proposal `default` после проверки их совместимости. Повторный план сверяет и переиспользует совпадающие объекты пары, а у проверенной политики предыдущей версии переключает только proposal. После проверки плана включите GRE отдельно и проверьте SA и связность. Если ранее для GRE был задан встроенный PSK, очистите его через `mm_gre_tunnel_update_plan` с `clearIpsecSecret: true` при отключённом интерфейсе.
### Разбор отказа и проверка резерва