diff --git a/backend/src/modules/mcp/ipsec-server-delete-acceptance.ts b/backend/src/modules/mcp/ipsec-server-delete-acceptance.ts index 32f063e1..6c6829c2 100644 --- a/backend/src/modules/mcp/ipsec-server-delete-acceptance.ts +++ b/backend/src/modules/mcp/ipsec-server-delete-acceptance.ts @@ -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 diff --git a/backend/src/modules/mcp/ipsec-server-delete-actions.ts b/backend/src/modules/mcp/ipsec-server-delete-actions.ts index 4634ad72..e61c6371 100644 --- a/backend/src/modules/mcp/ipsec-server-delete-actions.ts +++ b/backend/src/modules/mcp/ipsec-server-delete-actions.ts @@ -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 { - 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) => 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 + 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() + 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) { diff --git a/backend/src/services/ipsec-config.ts b/backend/src/services/ipsec-config.ts index b63501bb..1c799ad4 100644 --- a/backend/src/services/ipsec-config.ts +++ b/backend/src/services/ipsec-config.ts @@ -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: `*` for configuration rows; RouterOS 7.24 `/file` rows use case-sensitive `**` ids * whose length follows the file path (stand probe 2026-11-21). */ diff --git a/backend/src/services/ipsec-server-delete-model.test.ts b/backend/src/services/ipsec-server-delete-model.test.ts index 175ae9f2..4d72e1c5 100644 --- a/backend/src/services/ipsec-server-delete-model.test.ts +++ b/backend/src/services/ipsec-server-delete-model.test.ts @@ -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() diff --git a/backend/src/services/ipsec-server-delete-model.ts b/backend/src/services/ipsec-server-delete-model.ts index 17f3cdf8..d901705c 100644 --- a/backend/src/services/ipsec-server-delete-model.ts +++ b/backend/src/services/ipsec-server-delete-model.ts @@ -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 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 = { "/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 = { "/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() const crlBlocks = (row: Row) => { const issuer = edges.find(edge => edge.path === "/certificate" && edge.row === row)?.parent