Files
MikrotikManager/backend/src/services/ipsec-server-delete-model.test.ts
T
DenozordecandClaude Opus 5.5 d02a019b3b 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]>
2026-11-21 17:01:14 +07:00

148 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ipsecExternalPoolDependencyPaths } from "./ipsec-pool-dependencies.js"
import assert from "node:assert/strict"
import { planIpsecServerDelete as plan, projectIpsecServerDelete as project } from "./ipsec-server-delete-model.js"
import type { IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
const marker = "MikrotikManager:ipsec"
const paths = [...ipsecExternalPoolDependencyPaths,"/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"]
function base(): IpsecPeerDeleteState {
return { source: "source", proof: "proof", protections: [{ object_ref: { kind: "server", id: "1" } }], catalogs: { ...Object.fromEntries(paths.map(path => [path, []])),
"/ip/ipsec/identity": [{ ".id": "*i", peer: "ike", "mode-config": "ipsec-vpn", certificate: "ipsec-server", "remote-certificate": "ipsec-user-a", "policy-template-group": "mmapp-ipsec-vpn", comment: marker, opaque: "identity" }],
"/ip/ipsec/peer": [{ ".id": "*p", name: "ike", certificate: "ipsec-server", profile: "profile", comment: marker }],
"/ip/ipsec/policy": [{ ".id": "*y", peer: "ike", group: "mmapp-ipsec-vpn", proposal: "proposal", comment: marker }],
"/ip/ipsec/mode-config": [{ ".id": "*m", name: "ipsec-vpn", "address-pool": "pool" }],
"/ip/pool": [{ ".id": "*l", name: "pool", comment: marker }],
"/ip/firewall/nat": [{ ".id": "*n", comment: marker, opaque: "nat" }],
"/ip/ipsec/policy/group": [{ ".id": "*g", name: "mmapp-ipsec-vpn" }, { ".id": "*d", name: "default", default: "true" }],
"/ip/ipsec/profile": [{ ".id": "*f", name: "profile", comment: marker, opaque: "keep-profile" }],
"/ip/ipsec/proposal": [{ ".id": "*o", name: "proposal", comment: marker, opaque: "keep-proposal" }],
"/certificate": [{ ".id": "*a", name: "ipsec-ca", authority: "true", crl: "false" }, { ".id": "*s", name: "ipsec-server", ca: "ipsec-ca" }, { ".id": "*c", name: "ipsec-user-a", ca: "ipsec-ca" }],
} }
}
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"], ["/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)
// 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, 9)
assert(!keepCerts.objects.some(o => o.kind === "certificate"))
assert.deepEqual(keepCerts.commands.reduce(project, s).catalogs["/certificate"], s.catalogs["/certificate"])
const mixed = base()
mixed.catalogs["/ip/ipsec/peer"].push({ ".id": "*foreign", name: "foreign", profile: "profile", opaque: "unknown vendor value" })
mixed.catalogs["/ip/ipsec/identity"].push({ ".id": "*fi", peer: "foreign", opaque: "foreign secret" })
mixed.catalogs["/ip/firewall/nat"].push({ ".id": "*fn", comment: "foreign", vendor: "retained" })
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" }],
["/ip/ipsec/peer", { ".id": "*foreign", name: "foreign", certificate: "*s" }],
["/ip/ipsec/identity", { ".id": "*foreign", peer: "*p" }],
["/ip/ipsec/policy", { ".id": "*foreign", peer: " *p " }],
["/certificate", { ".id": "*foreign", name: "foreign", ca: "*a" }],
["/ip/pool", { ".id": "*foreign", name: "foreign", "next-pool": "*l" }],
] as [string, Record<string, string>][]) {
const conflict = base(); conflict.catalogs[path].push(row)
assert.throws(() => plan(conflict, true), /чужой/)
}
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, 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"))
assert.deepEqual(plan(runtime, true).commands.reduce(project, runtime).catalogs["/ip/ipsec/policy"], [runtime.catalogs["/ip/ipsec/policy"][1]])
for (const mutation of [
(state: IpsecPeerDeleteState) => { state.catalogs["/ip/ipsec/peer"].push({ ".id": "*x", name: " ike " }) },
(state: IpsecPeerDeleteState) => { state.catalogs["/ip/ipsec/peer"].push({ ".id": "*P", name: "different" }) },
(state: IpsecPeerDeleteState) => { state.catalogs["/ip/ipsec/peer"].push({ ".id": "*x", name: "*p" }) },
(state: IpsecPeerDeleteState) => { delete state.catalogs["/ip/pool"] },
(state: IpsecPeerDeleteState) => { state.catalogs["/certificate"][1].ca = "missing-ca" },
(state: IpsecPeerDeleteState) => { state.catalogs["/certificate"][0].ca = "ipsec-server" },
(state: IpsecPeerDeleteState) => { state.catalogs["/ip/ipsec/identity"][0].certificate = "ipsec-server,,ipsec-ca" },
]) { const invalid = base(); mutation(invalid); assert.throws(() => plan(invalid, true)) }
for (const flag of ["dynamic", "builtin", "default"]) for (const value of ["yes", "unknown", ""]) {
const protectedState = base(); protectedState.catalogs["/ip/firewall/nat"][0][flag] = value
assert.throws(() => plan(protectedState, true), /Системный/)
}
const crl = base(); crl.catalogs["/certificate"][0].crl = "true"
const crlPlan = plan(crl, true), cascade = crlPlan.commands.find(c => c.path === "/certificate")!
assert.deepEqual(cascade, { path: "/certificate", id: "*a", cascadeIds: ["*s", "*c"] })
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, 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"
const nestedCascade = plan(nested, true).commands.find(c => c.cascadeIds)!
assert.deepEqual(nestedCascade.cascadeIds, ["*s", "*c", "*inter"])
const foreignCrl = base()
foreignCrl.catalogs["/certificate"][0].name = "foreign-ca"
foreignCrl.catalogs["/certificate"][0].crl = "true"
for (const row of foreignCrl.catalogs["/certificate"].slice(1)) row.ca = "foreign-ca"
assert.throws(() => plan(foreignCrl, true), /чужим CA с CRL/)
const unknownCrl = base(); unknownCrl.catalogs["/certificate"][0].crl = "perhaps"
assert.throws(() => plan(unknownCrl, true), /Неоднозначный CRL/)
const foreignNested = structuredClone(nested)
foreignNested.catalogs["/certificate"].push({ ".id": "*foreign", name: "foreign", ca: "*inter" })
assert.throws(() => plan(foreignNested, true), /чужой/)
const empty = { source: "source", proof: "proof", protections: [], catalogs: Object.fromEntries(paths.map(path => [path, []])) }
assert.deepEqual(plan(empty, true).commands, [])
assert.deepEqual(plan(empty, false).objects, [])
assert.throws(() => project(s, { path: "/certificate", id: "*missing" }), /не подтверждены/)
assert.throws(() => project(s, { path: "/certificate", id: "*a", cascadeIds: ["*a"] }), /не подтверждены/)
assert.throws(() => project(crl, { path: "/certificate", id: "*a", cascadeIds: ["*s"] }), /манифестом/)
assert.throws(() => project(crl, { path: "/certificate", id: "*a" }), /манифестом/)
const foreignExpanded = base()
foreignExpanded.catalogs["/certificate"].push({ ".id": "*foreign", name: "foreign" })
assert.throws(() => project(foreignExpanded, { path: "/certificate", id: "*a", cascadeIds: ["*s", "*c", "*foreign"] }), /манифестом/)
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, 12)
const notCa = base(); notCa.catalogs["/certificate"][0].authority = "false"
assert.throws(() => plan(notCa, true), /CA-издатель/)
const poolChain = base()
poolChain.catalogs["/ip/pool"].push({ ".id": "*backup", name: "backup", comment: marker })
poolChain.catalogs["/ip/pool"][0]["next-pool"] = "*backup"
assert.deepEqual(plan(poolChain, false).commands.filter(c => c.path === "/ip/pool").map(c => c.id), ["*l", "*backup"])
assert.deepEqual(project(crl, cascade).catalogs["/ip/ipsec/identity"], crl.catalogs["/ip/ipsec/identity"])
console.log("ipsec server delete model tests passed")
const runtimeGhost = base()
runtimeGhost.catalogs["/ip/ipsec/policy"].push({".id":"*ghost",dynamic:"true",peer:"vanished-runtime-peer",group:"vanished-runtime-group",comment:marker})
assert.deepEqual(plan(runtimeGhost,true).commands,full.commands)
// v2 never treats an absent/unsupported external pool catalog as empty.
for(const path of ipsecExternalPoolDependencyPaths){const missing=base();delete missing.catalogs[path];assert.throws(()=>plan(missing,false))}
for(const path of ipsecExternalPoolDependencyPaths)for(const alias of ["pool","*L","*000l"]){
const foreign=base();foreign.catalogs[path].push({".id":"*consumer",name:"consumer",disabled:"true",...(path.startsWith("/ppp/")?{"remote-address":alias}:{"address-pool":alias})});assert.throws(()=>plan(foreign,false),/пула|pool/)
}
const unknownExternal=base();unknownExternal.catalogs["/ppp/profile"].push({".id":"*consumer","remote-address":"192.0.2.1",opaque:"NEVER_EXTERNAL_OPAQUE"});
assert.ok(plan(unknownExternal,false).companions.some(ref=>ref.kind==="ppp_profile"&&ref.id==="*consumer"))
const indirectExternal=base();indirectExternal.catalogs["/ip/pool"].push({".id":"*fallback",name:"fallback",comment:marker});indirectExternal.catalogs["/ip/pool"][0]["next-pool"]="fallback";indirectExternal.catalogs["/ppp/secret"].push({".id":"*consumer","remote-address":"pool"});assert.throws(()=>plan(indirectExternal,false),/пула|pool/)