fix(ipsec): удаление сервера убирает свои profile и proposal

mm_ipsec_server_remove_plan и REST-удаление оставляли profile и proposal ipsec-vpn (стенд IPsec 2026-11-21). Теперь они удаляются после policy и peer, если это строки продукта (метка или ipsec-vpn без комментария), не встроенные, и на них ссылаются только удаляемые строки; общие с чужой конфигурацией остаются без отказа. Версия операции 3. Тесты: модель (освобождение, общий профиль, встроенные, профиль init), приёмка со сценарием освобождения и паритетом MCP/REST.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-11-21 17:01:14 +07:00
1 parent 8d4169bb50
commit d02a019b3b
7 files changed
+65 -18

No files matched your search

@@ -100,6 +100,16 @@ export async function acceptIpsecServerDelete(actor: AuthUser) {
const successfulCommands = commands.slice(before); reset(scenario.crl); const restBefore: number = commands.length, historyBefore = historyCalls
const response = await rest.inject({ method: "DELETE", url: `/api/ipsec/server/${serverId}?removeCertificates=${scenario.remove}` }); assert.equal(response.statusCode, 200, response.body); assert.deepEqual(response.json(), { ok: true }); assert.deepEqual(commands.slice(restBefore), successfulCommands); assert.deepEqual(catalogs, desired(original, scenario.remove)); assert.equal(historyCalls, historyBefore + 1)
}
// Without foreign users the product proposal/profile are released: MCP and REST remove them after policy/peer, identically.
const released = () => { reset(); for (const [path, id] of [["/ip/ipsec/peer", "*p2"], ["/ip/ipsec/policy", "*s2"], ["/ip/ipsec/identity", "*i2"]]) catalogs[path] = catalogs[path].filter(row => row[".id"] !== id) }
{
released(); const before = commands.length, result = await apply(false)
assert.equal(result.state, "applied", JSON.stringify(result)); assert.equal(catalogs["/ip/ipsec/profile"].length, 0); assert.equal(catalogs["/ip/ipsec/proposal"].length, 0)
const mcpCommands = commands.slice(before); assert.deepEqual(mcpCommands.slice(7), ["/ip/ipsec/proposal/*r1", "/ip/ipsec/profile/*f1"])
released(); const restBefore = commands.length
const response = await rest.inject({ method: "DELETE", url: `/api/ipsec/server/${serverId}?removeCertificates=false` }); assert.equal(response.statusCode, 200, response.body)
assert.deepEqual(commands.slice(restBefore), mcpCommands); assert.equal(catalogs["/ip/ipsec/profile"].length, 0); assert.equal(catalogs["/ip/ipsec/proposal"].length, 0)
}
reset(); ticking = true
catalogs["/ip/ipsec/policy"].push({ ".id": "*runtime", dynamic: "true", peer: "vanished-runtime-peer", group: "vanished-runtime-group", comment: marker })
const withCountdown = await apply(false)
@@ -132,7 +142,7 @@ export async function acceptIpsecServerDelete(actor: AuthUser) {
for (const table of ["mcp_audit", "mcp_plans", "mcp_operation_steps"]) {
const rows = table === "mcp_operation_steps" ? await originalQuery("SELECT s.* FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id WHERE o.connection_id=$1", [connectionId]) : await originalQuery(`SELECT * FROM ${table} WHERE connection_id=$1`, [connectionId]); assert.ok(!JSON.stringify(rows.rows).includes("NEVER_"), `${table} leaked private fixture data`)
}
console.log("✓ IPsec server removal SQL/loopback: full managed manifest, REST parity/defaults/noop history, raw foreign/profile/proposal preservation, closed CRL CA cascade, foreign/protected dependencies and ambiguity denied, per-step drift/fault stop without replay; native cascade/forwarding gate remains open")
console.log("✓ IPsec server removal SQL/loopback: full managed manifest, REST parity/defaults/noop history, raw foreign/shared profile/proposal preservation, released profile/proposal removal with REST parity, closed CRL CA cascade, foreign/protected dependencies and ambiguity denied, per-step drift/fault stop without replay; native cascade/forwarding gate remains open")
} finally {
closeFixtureAgent()
pool.query = originalQuery as typeof pool.query
@@ -18,7 +18,7 @@ const operation = "network.ipsec.server.delete", hash = z.string().regex(/^[a-f0
export const ipsecServerDeleteActionSchema = z.object({ serverId: z.number().int().positive().safe(), removeCertificates: z.boolean().default(true) }).strict()
const objectRef = z.object({ kind: z.string().min(1).max(100), id: z.string().min(1).max(200) }).strict()
const nativeId = z.string().regex(/^\*[a-z0-9]+$/i).max(100)
const command = z.object({ path: z.enum(["/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/policy", "/ip/ipsec/mode-config", "/ip/pool", "/ip/firewall/nat", "/ip/ipsec/policy/group", "/certificate"]), id: nativeId, cascadeIds: z.array(nativeId).max(2000).optional() }).strict()
const command = z.object({ path: z.enum(["/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/policy", "/ip/ipsec/mode-config", "/ip/pool", "/ip/firewall/nat", "/ip/ipsec/policy/group", "/ip/ipsec/proposal", "/ip/ipsec/profile", "/certificate"]), id: nativeId, cascadeIds: z.array(nativeId).max(2000).optional() }).strict()
const bindingSchema = ipsecServerDeleteActionSchema.extend({
operation: z.literal(operation), principal: z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string().datetime() }).strict(),
ownerId: z.string().min(1), ownerProof: hash, policyProof: hash, generation: z.string().min(1), sourceProof: hash, expectedProof: hash,
@@ -121,5 +121,5 @@ export function createIpsecServerDeleteAdapter(overrides: Partial<typeof product
export function registerIpsecServerDeleteActions(register: typeof add) {
const adapter = createIpsecServerDeleteAdapter()
registerMcpService(operation, adapter.service)
register(operation, "mm_ipsec_server_remove_plan", "Удалить управляемый сервер IPsec по полному манифесту", "network", "mm:network:write", "write", "servers", ipsecServerDeleteActionSchema, { version: 2, prepare: adapter.prepare })
register(operation, "mm_ipsec_server_remove_plan", "Удалить управляемый сервер IPsec по полному манифесту", "network", "mm:network:write", "write", "servers", ipsecServerDeleteActionSchema, { version: 3, prepare: adapter.prepare })
}
@@ -14,7 +14,7 @@ assert.equal(findAction("mm_ipsec_user_create_plan").operation.version, 3)
assert.equal(findAction("mm_ipsec_server_init_plan").operation.version, 5)
// RouterOS 7.24 certificate bodies (no comment, sign/export by .id): earlier prepared plans need a new approval.
assert.equal(findAction("mm_ipsec_existing_certificate_export_plan").operation.version, 2)
assert.equal(findAction("mm_ipsec_server_remove_plan").operation.version, 2)
assert.equal(findAction("mm_ipsec_server_remove_plan").operation.version, 3)
assert.equal(findAction("mm_ipsec_revision_restore_plan").operation.version, 1)
assert.equal(findAction("mm_wireguard_revision_restore_plan").operation.id, "config.wireguard.revisions.restore")
assert.equal(findAction("mm_vrf_update_plan").schema.safeParse({ serverId: 1, id: "*1", fields: { comment: "reviewed" }, productionAdmission: true }).success, true)
@@ -71,4 +71,4 @@ assert.equal(findAction("mm_ipsec_user_edit_plan").operation.id, "network.ipsec.
assert.deepEqual(findAction("mm_ipsec_user_edit_plan").operation.requiredPermissions, ["mm:network:write"])
for (const tool of ["mm_ipsec_peer_remove_plan", "mm_ipsec_certificate_remove_plan", "mm_ipsec_user_remove_plan", "mm_ipsec_peer_edit_plan"]) assert.equal(findAction(tool).operation.version, 2)
assert.equal(findAction("mm_ipsec_server_remove_plan").operation.version, 2)
assert.equal(findAction("mm_ipsec_server_remove_plan").operation.version, 3)
+14 -3
View File
@@ -1,14 +1,25 @@
import type { MikrotikClient } from "./mikrotik.js"
import { IPSEC_CA_CERT, IPSEC_SERVER_CERT, IPSEC_POLICY_GROUP, isManagedIpsecModeConfig, isIpsecManagedComment } from "./ipsec-config.js"
import { IPSEC_CA_CERT, IPSEC_SERVER_CERT, IPSEC_POLICY_GROUP, isManagedIpsecModeConfig, isIpsecManagedComment, isReleasableIpsecCryptoRow } from "./ipsec-config.js"
import { listByPath } from "./ipsec-ros.js"
/** Read the whole deletion scope before writing; never treat unreadable state as empty. */
export async function removeManagedIpsecServer(client: MikrotikClient, removeCertificates: boolean): Promise<void> {
const paths = ["/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/policy", "/ip/ipsec/mode-config", "/ip/pool", "/ip/firewall/nat", "/ip/ipsec/policy/group"]
// Proposal/profile after their policies/peers; certificates last.
const paths = ["/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/policy", "/ip/ipsec/mode-config", "/ip/pool", "/ip/firewall/nat", "/ip/ipsec/policy/group", "/ip/ipsec/proposal", "/ip/ipsec/profile"]
if (removeCertificates) paths.push("/certificate")
const snapshots = await Promise.all(paths.map(async path => ({ path, rows: await listByPath(client, path) })))
const linkedGroups = new Set(snapshots.find(s => s.path === "/ip/ipsec/policy")?.rows.filter(r => isIpsecManagedComment(r.comment)).map(r => r.group))
const owned = (path: string, row: Record<string, string | undefined>) => path === "/ip/ipsec/policy/group" ? row.name === IPSEC_POLICY_GROUP && linkedGroups.has(row.name) : isIpsecManagedComment(row.comment) || (path === "/ip/ipsec/mode-config" && isManagedIpsecModeConfig(row)) || (path === "/certificate" && (row.name === IPSEC_CA_CERT || row.name === IPSEC_SERVER_CERT || row.name?.startsWith("ipsec-user-")))
type Row = Record<string, string | undefined>
const rowsOf = (path: string) => snapshots.find(s => s.path === path)?.rows ?? []
// Same rule as the MCP plan: a product proposal/profile goes only when every row referencing it (by name or id) goes too.
const released = new Set<Row>()
const owned = (path: string, row: Row) => path === "/ip/ipsec/proposal" || path === "/ip/ipsec/profile" ? released.has(row) : path === "/ip/ipsec/policy/group" ? row.name === IPSEC_POLICY_GROUP && linkedGroups.has(row.name) : isIpsecManagedComment(row.comment) || (path === "/ip/ipsec/mode-config" && isManagedIpsecModeConfig(row)) || (path === "/certificate" && (row.name === IPSEC_CA_CERT || row.name === IPSEC_SERVER_CERT || row.name?.startsWith("ipsec-user-")))
for (const [path, consumerPath, field] of [["/ip/ipsec/proposal", "/ip/ipsec/policy", "proposal"], ["/ip/ipsec/profile", "/ip/ipsec/peer", "profile"]] as const) {
for (const row of rowsOf(path).filter(isReleasableIpsecCryptoRow)) {
const users = rowsOf(consumerPath).filter(user => user.dynamic !== "true" && user.dynamic !== "yes" && [row.name, row[".id"]].includes(user[field]?.trim()))
if (users.length && users.every(user => owned(consumerPath, user))) released.add(row)
}
}
const names = (path: string) => new Set(snapshots.find(s => s.path === path)?.rows.filter(row => owned(path, row)).map(row => row.name).filter((name): name is string => typeof name === "string" && name.length > 0))
const peerNames = names("/ip/ipsec/peer"), modeConfigs = names("/ip/ipsec/mode-config"), certificates = names("/certificate"), groups = names("/ip/ipsec/policy/group")
for (const { path, rows } of snapshots) {
+7
View File
@@ -126,6 +126,13 @@ export function clientCertName(userName: string): string {
return `ipsec-user-${ipsecSlug(userName) || "client"}`
}
/** IKE profile / ESP proposal the product created for its server: the product marker, or `ipsec-vpn` without a comment
* (server init writes the profile without one). Built-in and dynamic rows never qualify. A server removal deletes such a
* row only when every row that references it is removed too; a shared row stays (stand IPsec 2026-11-21: both were left). */
export function isReleasableIpsecCryptoRow(row: { name?: string; comment?: string; default?: string; dynamic?: string; builtin?: string }): boolean {
if ([row.default, row.dynamic, row.builtin].some(flag => flag === "true" || flag === "yes")) return false
return isIpsecManagedComment(row.comment) || (!row.comment?.trim() && row.name === IPSEC_COMMON_NAME)
}
export const IPSEC_CA_COMMON_NAME = "MikrotikManager IPsec CA"
/** RouterOS native id: `*<hex>` for configuration rows; RouterOS 7.24 `/file` rows use case-sensitive `**<base62>` ids
* whose length follows the file path (stand probe 2026-11-21). */
@@ -19,17 +19,19 @@ function base(): IpsecPeerDeleteState {
} }
}
const s = base(), before = structuredClone(s), full = plan(s, true)
assert.deepEqual(full.commands.map(c => [c.path, c.id]), [["/ip/ipsec/identity", "*i"], ["/ip/ipsec/policy", "*y"], ["/ip/ipsec/peer", "*p"], ["/ip/ipsec/mode-config", "*m"], ["/ip/pool", "*l"], ["/ip/firewall/nat", "*n"], ["/ip/ipsec/policy/group", "*g"], ["/certificate", "*s"], ["/certificate", "*c"], ["/certificate", "*a"]])
assert.equal(full.objects.length, 10)
assert.deepEqual(full.commands.map(c => [c.path, c.id]), [["/ip/ipsec/identity", "*i"], ["/ip/ipsec/policy", "*y"], ["/ip/ipsec/peer", "*p"], ["/ip/ipsec/mode-config", "*m"], ["/ip/pool", "*l"], ["/ip/firewall/nat", "*n"], ["/ip/ipsec/policy/group", "*g"], ["/ip/ipsec/proposal", "*o"], ["/ip/ipsec/profile", "*f"], ["/certificate", "*s"], ["/certificate", "*c"], ["/certificate", "*a"]])
assert.equal(full.objects.length, 12)
assert.deepEqual(full.companions, full.objects)
let next = s
for (const command of full.commands) next = project(next, command)
assert.deepEqual(s, before)
assert.deepEqual(next.protections, s.protections)
for (const path of ["/ip/ipsec/profile", "/ip/ipsec/proposal", "/ip/ipsec/active-peers"]) assert.deepEqual(next.catalogs[path], s.catalogs[path])
// Product proposal/profile used only by the removed policy/peer go with them (stand IPsec 2026-11-21: they were left).
assert.deepEqual(next.catalogs["/ip/ipsec/active-peers"], s.catalogs["/ip/ipsec/active-peers"])
for (const path of ["/ip/ipsec/profile", "/ip/ipsec/proposal"]) assert.deepEqual(next.catalogs[path], [])
assert.deepEqual(next.catalogs["/ip/ipsec/policy/group"], [s.catalogs["/ip/ipsec/policy/group"][1]])
const keepCerts = plan(s, false)
assert.equal(keepCerts.commands.length, 7)
assert.equal(keepCerts.commands.length, 9)
assert(!keepCerts.objects.some(o => o.kind === "certificate"))
assert.deepEqual(keepCerts.commands.reduce(project, s).catalogs["/certificate"], s.catalogs["/certificate"])
@@ -41,6 +43,15 @@ const mixedAfter = plan(mixed, true).commands.reduce(project, mixed)
assert.deepEqual(mixedAfter.catalogs["/ip/ipsec/peer"], [mixed.catalogs["/ip/ipsec/peer"][1]])
assert.deepEqual(mixedAfter.catalogs["/ip/ipsec/identity"], [mixed.catalogs["/ip/ipsec/identity"][1]])
assert.deepEqual(mixedAfter.catalogs["/ip/firewall/nat"], [mixed.catalogs["/ip/firewall/nat"][1]])
// The foreign peer still uses the product profile: it stays, no conflict; the proposal used only by the removed policy goes.
assert.deepEqual(mixedAfter.catalogs["/ip/ipsec/profile"], mixed.catalogs["/ip/ipsec/profile"])
assert.deepEqual(mixedAfter.catalogs["/ip/ipsec/proposal"], [])
// Built-in rows and foreign names never go, even when only removed rows reference them; an ipsec-vpn profile without a comment
// (as server init writes it) goes.
const builtin = base(); builtin.catalogs["/ip/ipsec/profile"] = [{ ".id": "*f", name: "profile", default: "true" }]; builtin.catalogs["/ip/ipsec/proposal"] = [{ ".id": "*o", name: "proposal", comment: "foreign" }]
assert(!plan(builtin, true).commands.some(c => c.path === "/ip/ipsec/profile" || c.path === "/ip/ipsec/proposal"))
const initProfile = base(); initProfile.catalogs["/ip/ipsec/profile"] = [{ ".id": "*f", name: "ipsec-vpn" }]; initProfile.catalogs["/ip/ipsec/peer"][0].profile = "ipsec-vpn"
assert(plan(initProfile, true).commands.some(c => c.path === "/ip/ipsec/profile" && c.id === "*f"))
for (const [path, row] of [
["/ip/ipsec/mode-config", { ".id": "*foreign", name: "foreign", "address-pool": "*l" }],
@@ -57,7 +68,7 @@ const aliases = base()
aliases.catalogs["/ip/ipsec/identity"][0].peer = "*P"
aliases.catalogs["/ip/ipsec/policy"][0].group = "*g"
aliases.catalogs["/ip/ipsec/mode-config"][0]["address-pool"] = "*L"
assert.equal(plan(aliases, true).objects.length, 10)
assert.equal(plan(aliases, true).objects.length, 12)
const runtime = base()
runtime.catalogs["/ip/ipsec/policy"].push({ ".id": "*runtime", peer: "ike", group: "mmapp-ipsec-vpn", dynamic: "yes", comment: marker, opaque: "runtime" })
assert(!plan(runtime, true).commands.some(c => c.id === "*runtime"))
@@ -82,7 +93,7 @@ assert.deepEqual(cascade, { path: "/certificate", id: "*a", cascadeIds: ["*s", "
assert.equal(crlPlan.commands.filter(c => c.path === "/certificate").length, 1)
assert.equal(crlPlan.objects.filter(o => o.kind === "certificate").length, 3)
assert.deepEqual(crlPlan.commands.reduce(project, crl).catalogs["/certificate"], [])
assert.equal(plan(crl, false).commands.length, 7)
assert.equal(plan(crl, false).commands.length, 9)
const nested = base()
nested.catalogs["/certificate"].push({ ".id": "*inter", name: "ipsec-user-intermediate", ca: "ipsec-ca", authority: "true", crl: "true" })
nested.catalogs["/certificate"][2].ca = "*inter"
@@ -112,7 +123,7 @@ assert.throws(() => project(foreignExpanded, { path: "/certificate", id: "*a", c
const commaName = base()
commaName.catalogs["/certificate"][0].name = "ipsec-user-ca,with-comma"
for (const row of commaName.catalogs["/certificate"].slice(1)) row.ca = "ipsec-user-ca,with-comma"
assert.equal(plan(commaName, true).objects.length, 10)
assert.equal(plan(commaName, true).objects.length, 12)
const notCa = base(); notCa.catalogs["/certificate"][0].authority = "false"
assert.throws(() => plan(notCa, true), /CA-издатель/)
const poolChain = base()
@@ -1,16 +1,16 @@
import { assertPoolMutationDependencies,ipsecExternalPoolDependencyPaths } from "./ipsec-pool-dependencies.js"
import { McpError } from "../modules/mcp/security.js"
import type { IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
import { IPSEC_CA_CERT, IPSEC_SERVER_CERT, IPSEC_POLICY_GROUP, isIpsecManagedComment, isManagedIpsecModeConfig } from "./ipsec-config.js"
import { IPSEC_CA_CERT, IPSEC_SERVER_CERT, IPSEC_POLICY_GROUP, isIpsecManagedComment, isManagedIpsecModeConfig, isReleasableIpsecCryptoRow } from "./ipsec-config.js"
import { observedBoolean } from "./ospf-observed-values.js"
type Row = Record<string, string>
const paths = ["/ip/ipsec/peer", "/ip/ipsec/identity", "/ip/ipsec/mode-config", "/ip/pool", "/ip/ipsec/policy", "/ip/firewall/nat", "/certificate", "/ip/ipsec/profile", "/ip/ipsec/proposal", "/ip/ipsec/policy/group", "/ip/ipsec/active-peers"] as const
export type IpsecServerDeletePath = "/ip/ipsec/identity" | "/ip/ipsec/peer" | "/ip/ipsec/policy" | "/ip/ipsec/mode-config" | "/ip/pool" | "/ip/firewall/nat" | "/ip/ipsec/policy/group" | "/certificate"
export type IpsecServerDeletePath = "/ip/ipsec/identity" | "/ip/ipsec/peer" | "/ip/ipsec/policy" | "/ip/ipsec/mode-config" | "/ip/pool" | "/ip/firewall/nat" | "/ip/ipsec/policy/group" | "/ip/ipsec/proposal" | "/ip/ipsec/profile" | "/certificate"
export interface IpsecServerDeleteCommand { path: IpsecServerDeletePath; id: string; cascadeIds?: string[] }
export interface IpsecServerDeleteObject { kind: string; id: string }
export interface IpsecServerDeletePlan { commands: IpsecServerDeleteCommand[]; objects: IpsecServerDeleteObject[]; companions: IpsecServerDeleteObject[]; removeCertificates: boolean }
const kinds: Record<IpsecServerDeletePath, string> = { "/ip/ipsec/identity": "ipsec_identity", "/ip/ipsec/peer": "ipsec_peer", "/ip/ipsec/policy": "ipsec_policy", "/ip/ipsec/mode-config": "ipsec_mode_config", "/ip/pool": "ip_pool", "/ip/firewall/nat": "ip_nat", "/ip/ipsec/policy/group": "ipsec_policy_group", "/certificate": "certificate" }
const kinds: Record<IpsecServerDeletePath, string> = { "/ip/ipsec/identity": "ipsec_identity", "/ip/ipsec/peer": "ipsec_peer", "/ip/ipsec/policy": "ipsec_policy", "/ip/ipsec/mode-config": "ipsec_mode_config", "/ip/pool": "ip_pool", "/ip/firewall/nat": "ip_nat", "/ip/ipsec/policy/group": "ipsec_policy_group", "/ip/ipsec/proposal": "ipsec_proposal", "/ip/ipsec/profile": "ipsec_profile", "/certificate": "certificate" }
const fail = (code: string, message: string): never => { throw new McpError(code, message, code === "STATE_UNAVAILABLE" ? 502 : 409) }
const exactId = (value: unknown): value is string => typeof value === "string" && /^\*[a-z0-9]+$/i.test(value) && value.length <= 100
const idKey=(value:string)=>value.toLowerCase().replace(/^\*0+(?=[a-z0-9])/,"*")
@@ -131,6 +131,14 @@ export function planIpsecServerDelete(state: IpsecPeerDeleteState, removeCertifi
if (path === "/ip/pool") rows.sort((a, b) => descendants(path, a).length - descendants(path, b).length)
for (const row of rows) { commands.push({ path, id: row[".id"] }); objects.push({ kind: kinds[path], id: row[".id"] }) }
}
// Product proposal/profile go once nothing that stays references them (edges hold every resolved name or id reference).
for (const [path, consumerPath] of [["/ip/ipsec/proposal", "/ip/ipsec/policy"], ["/ip/ipsec/profile", "/ip/ipsec/peer"]] as const) {
for (const row of catalogs[path].filter(isReleasableIpsecCryptoRow)) {
const users = edges.filter(edge => edge.parentPath === path && edge.parent === row)
if (!users.length || users.some(edge => !owned.get(consumerPath)!.has(edge.row))) continue
protect(row); commands.push({ path, id: row[".id"] }); objects.push({ kind: kinds[path], id: row[".id"] })
}
}
const certs = owned.get("/certificate")!, covered = new Set<Row>()
const crlBlocks = (row: Row) => {
const issuer = edges.find(edge => edge.path === "/certificate" && edge.row === row)?.parent