Files
MikrotikManager/backend/src/modules/mcp/ipsec-server-delete-actions.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

126 lines
14 KiB
TypeScript

import { randomUUID } from "node:crypto"
import { z } from "zod"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
import { ipsecPeerDeleteSourceProof } from "../../services/ipsec-peer-delete.js"
import { planIpsecServerDelete } from "../../services/ipsec-server-delete-model.js"
import { deleteIpsecServerGuarded, readIpsecServerDeleteState, ipsecServerDeleteStageProofs } from "../../services/ipsec-server-delete.js"
import { routerClient } from "./resources.js"
import { effectiveMcpConnection, audit } from "./store.js"
import { encryptSecret, decryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js"
import { registerMcpService } from "./service-registry.js"
import type { ActionContext, ChangeEvidence } from "./action-types.js"
import type { add } from "./actions.js"
import type { McpServiceHandler } from "./service-registry.js"
const operation = "network.ipsec.server.delete", hash = z.string().regex(/^[a-f0-9]{64}$/)
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", "/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,
requestProof: hash, manifestProof: hash, commands: z.array(command).max(1000), objects: z.array(objectRef).max(3000), stageProofs: z.array(hash).min(1).max(1001),
commandCount: z.number().int().min(0).max(1000), affectedObjects: z.number().int().min(0).max(3000), receiptId: z.string().uuid(), proofRevision: z.literal(2),
}).strict()
type Binding = z.infer<typeof bindingSchema>
const inputSchema = z.object({ serverId: z.number().int().positive().safe(), receiptId: z.string().uuid(), bindingCiphertext: z.string().min(1).max(2097152) }).strict()
const production = {
connection: effectiveMcpConnection, router: routerClient, read: readIpsecServerDeleteState, sourceProof: ipsecPeerDeleteSourceProof,
plan: planIpsecServerDelete, stages: ipsecServerDeleteStageProofs, remove: deleteIpsecServerGuarded, seal: encryptSecret, open: decryptSecret, verifiedAccess: assertVerifiedConfigurationAccess,
manifestProof: async (value: unknown) => privateSecretFingerprint(fingerprint(value), "ipsec-server-delete-manifest-v2"),
query: async (sql: string, values: unknown[]) => (await pool.query(sql, values)).rows as Record<string, unknown>[],
checkpoint: async (ownerId: string, connectionId: string, value: unknown) => audit(pool, ownerId, "ipsec.server.delete.checkpoint", connectionId, value),
}
const conflict = () => new McpError("STATE_CONFLICT", "Манифест удаления IPsec, источник или допуск изменились", 409)
const manifest = (value: Pick<Binding, "commands" | "objects" | "removeCertificates">) => ({ commands: value.commands, objects: value.objects, removeCertificates: value.removeCertificates })
export function hasVerifiedIpsecServerDelete(candidate: unknown, binding: Binding, input: Record<string, unknown>, proof: string): boolean {
if (!candidate || typeof candidate !== "object") return false
const row = candidate as Record<string, unknown>, result = row.result as Record<string, unknown> | undefined
return row.connection_id === binding.principal.connectionId && row.state === "verified" && fingerprint(row.intended_state) === fingerprint(redact({ kind: "service", service: operation, input })) && !!result &&
result.ok === true && result.verified === true && result.receiptId === binding.receiptId && result.removeCertificates === binding.removeCertificates && result.commandCount === binding.commandCount && result.completedCommands === binding.commandCount && result.confirmedWrites === binding.commandCount && result.affectedObjects === binding.affectedObjects &&
result.historyRecorded === true && result.revisionRecorded === true && result.afterProof === proof && proof === binding.stageProofs.at(-1) && result.forwardingVerified === false && result.automaticReplay === false
}
/** Whole-server removal has one server-sealed immutable manifest and no replay.
* All native commands, indirect CA removals and history consume the budget. */
export function createIpsecServerDeleteAdapter(overrides: Partial<typeof production> = {}) {
const deps = { ...production, ...overrides }
const authorize = async (binding: Binding, signal?: AbortSignal, external: () => Promise<unknown> = async () => {}) => {
signal?.throwIfAborted(); await external()
const current = await deps.connection(binding.principal)
if (Date.parse(binding.principal.credentialExpiresAt) <= Date.now() || current.owner_id !== binding.ownerId || current.policy.status !== "active" || current.policy.mode === "observer" || current.owner_valid_until.getTime() <= Date.now() || Date.parse(current.policy.expiresAt) <= Date.now() || !current.policy.scope.operationIds.includes(operation) || !current.policy.scope.serverIds.includes(binding.serverId) || !hasPermission(current.owner_permissions, "mm:network:write") || !hasPermission(current.policy.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Нет актуального допуска удаления сервера IPsec", 403)
if (current.generation !== binding.generation || fingerprint(current.policy) !== binding.policyProof || fingerprint(current.owner_permissions) !== binding.ownerProof || fingerprint({ serverId: binding.serverId, removeCertificates: binding.removeCertificates }) !== binding.requestProof) throw conflict()
signal?.throwIfAborted()
}
const request = async (raw: Record<string, unknown>) => {
const input = inputSchema.parse(raw), binding = bindingSchema.parse(JSON.parse(await deps.open(input.bindingCiphertext)))
if (input.serverId !== binding.serverId || input.receiptId !== binding.receiptId || binding.commandCount !== binding.commands.length || binding.affectedObjects !== binding.commands.reduce((sum, cmd) => sum + 1 + (cmd.cascadeIds?.length ?? 0), 0) || binding.stageProofs.length !== binding.commandCount + 1 || binding.stageProofs[0] !== binding.expectedProof || await deps.manifestProof(manifest(binding)) !== binding.manifestProof) throw conflict()
return binding
}
const source = async (binding: Binding, signal?: AbortSignal, external?: () => Promise<unknown>) => {
const check = () => authorize(binding, signal, external)
await check()
const { server } = await deps.router(binding.serverId)
if (await deps.sourceProof(server) !== binding.sourceProof) throw conflict()
const state = await deps.read(server, check)
if (state.source !== binding.sourceProof) throw conflict()
await check(); return { server, state, check }
}
const prepare = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence> => {
const value = ipsecServerDeleteActionSchema.parse(raw)
const binding: Binding = bindingSchema.parse({ ...value, operation, principal: context.principal, ownerId: context.connection.owner_id, ownerProof: fingerprint(context.connection.owner_permissions), policyProof: fingerprint(context.connection.policy), generation: context.connection.generation, sourceProof: "0".repeat(64), expectedProof: "0".repeat(64), requestProof: fingerprint(value), manifestProof: "0".repeat(64), commands: [], objects: [], stageProofs: ["0".repeat(64)], commandCount: 0, affectedObjects: 0, receiptId: randomUUID(), proofRevision: 2 })
await authorize(binding, context.signal)
const { server } = await deps.router(value.serverId)
binding.sourceProof = await deps.sourceProof(server)
const before = await source(binding, context.signal), plan = deps.plan(before.state, value.removeCertificates)
binding.expectedProof = before.state.proof; binding.commands = plan.commands; binding.objects = plan.objects
binding.commandCount = plan.commands.length; binding.affectedObjects = plan.commands.reduce((sum, cmd) => sum + 1 + (cmd.cascadeIds?.length ?? 0), 0)
binding.stageProofs = await deps.stages(before.state, plan.commands)
if (binding.stageProofs.length !== binding.commandCount + 1 || binding.stageProofs[0] !== binding.expectedProof) throw conflict()
binding.manifestProof = await deps.manifestProof(manifest(binding))
const objects: ChangeEvidence["objects"] = [{ kind: "server", id: String(value.serverId), serverId: value.serverId }, { kind: "ipsec_server", id: String(value.serverId), serverId: value.serverId }, ...plan.objects.map(ref => ({ ...ref, serverId: value.serverId })), ...plan.companions.map(ref => ({ ...ref, serverId: value.serverId }))]
for (const protection of before.state.protections as Array<{ object_ref: { kind: string; id: string } }>) objects.push({ kind: protection.object_ref.kind, id: protection.object_ref.id, serverId: value.serverId })
if ((await source(binding, context.signal)).state.proof !== binding.expectedProof) throw conflict()
const summary = [...new Set(plan.objects.map(ref => ref.kind))].map(kind => `${kind}: ${plan.objects.filter(ref => ref.kind === kind).length}`).join(", ") || "нет управляемых объектов"
const cascades = plan.commands.filter(cmd => cmd.cascadeIds?.length).map(cmd => `${cmd.id}: ${cmd.cascadeIds!.join(", ")}`).join("; ")
return { target: { scope: "servers", serverIds: [value.serverId] }, objects, snapshots: [], requiresHuman: true, mutationCost: binding.affectedObjects + 1, before: { proof: before.state.proof },
steps: [{ kind: "service", service: operation, input: { serverId: value.serverId, receiptId: binding.receiptId, bindingCiphertext: await deps.seal(JSON.stringify(binding)) } }],
warnings: [`Необратимое удаление управляемой конфигурации IPsec: ${summary}. Native DELETE: ${binding.commandCount}; затронутых объектов: ${binding.affectedObjects}; затем обязательная managed-only история.`, `Сертификаты: ${value.removeCertificates ? "удаляются по точному манифесту" : "сохраняются"}. CA cascade: ${cascades || "нет"}. Profiles и proposals сохраняются.`, "Каждый объект, включая косвенно удаляемые сертификаты, входит в бюджет и проверку защит. После каждой команды требуется точный whole-state read-back; пустой манифест записывает только историю.", "При потере ответа или изменении сторонней конфигурации операция останавливается без повтора и автоматического отката. Сетевая передача и поведение настоящего CHR отдельно не подтверждаются. Native IPv4 pool graph не доказывает внешние динамические RADIUS Framed-Pool assignments."] }
}
const service: McpServiceHandler = {
current: async input => ({ proof: (await source(await request(input))).state.proof }),
execute: async input => {
const binding = await request(input), before = await source(binding)
if (before.state.proof !== binding.expectedProof) throw conflict()
const plan = deps.plan(before.state, binding.removeCertificates)
if (await deps.manifestProof({ commands: plan.commands, objects: plan.objects, removeCertificates: binding.removeCertificates }) !== binding.manifestProof || fingerprint(await deps.stages(before.state, plan.commands)) !== fingerprint(binding.stageProofs)) throw conflict()
const check = async () => { await deps.verifiedAccess(); await before.check() }
await check()
return deps.remove(before.server, binding.removeCertificates, binding.expectedProof, check, { receiptId: binding.receiptId, checkpoint: async value => { await check(); await deps.checkpoint(binding.ownerId, binding.principal.connectionId, { ...value, inputProof: fingerprint(redact(input)), manifestProof: binding.manifestProof }) } })
},
verify: async (input, result) => {
const binding = await request(input), after = await source(binding)
return hasVerifiedIpsecServerDelete({ connection_id: binding.principal.connectionId, state: "verified", intended_state: redact({ kind: "service", service: operation, input }), result }, binding, input, after.state.proof)
},
reconcile: async (input, external) => {
const binding = await request(input), latest = await source(binding, undefined, external)
await latest.check()
const rows = await deps.query("SELECT o.connection_id,s.state,s.intended_state,s.result FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id WHERE o.connection_id=$1 AND s.intended_state->'input'->>'receiptId'=$2 LIMIT 2", [binding.principal.connectionId, binding.receiptId])
const verified = rows.length === 1 && hasVerifiedIpsecServerDelete(rows[0], binding, input, latest.state.proof)
if ((await source(binding, undefined, external)).state.proof !== latest.state.proof) throw conflict()
return { matchesOriginalState: latest.state.proof === binding.expectedProof, matchesDesiredState: verified, automaticReplay: false, forwardingVerified: false }
},
}
return { prepare, service }
}
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: 3, prepare: adapter.prepare })
}