74 lines
8.7 KiB
TypeScript
74 lines
8.7 KiB
TypeScript
import { z } from "zod"
|
|
import { randomUUID } from "node:crypto"
|
|
import { pool } from "../../db/index.js"
|
|
import { hasPermission } from "../../lib/permissions.js"
|
|
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
|
import { deleteIpsecPeerGuarded, readIpsecPeerDeleteState, ipsecPeerDeleteTarget, projectIpsecPeerDelete, ipsecPeerDeleteProof } from "../../services/ipsec-peer-delete.js"
|
|
import { effectiveMcpConnection } from "./store.js"
|
|
import { routerClient } from "./resources.js"
|
|
import { accessGeneration, fingerprint, 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"
|
|
|
|
const schema = z.object({ serverId: z.number().int().positive().safe(), peerId: z.string().regex(/^\*[a-z0-9]+$/i).max(100), force: z.boolean().default(false) }).strict()
|
|
const operation = "network.ipsec.peers.delete"
|
|
async function access(input: Record<string, unknown>, signal?: AbortSignal) {
|
|
if (signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение IPsec отменено", 409)
|
|
const principal = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string() }).strict().parse(input.principal)
|
|
const current = await effectiveMcpConnection(principal)
|
|
if (input.operationId !== operation || current.owner_id !== input.ownerId || !hasPermission(current.owner_permissions, "mm:network:write") || !hasPermission(current.policy.permissions, "mm:network:write") || !current.policy.scope.operationIds.includes(operation)) throw new McpError("PERMISSION_DENIED", "Допуск удаления IPsec отозван", 403)
|
|
if (!current.policy.scope.serverIds.includes(Number(input.serverId))) throw new McpError("SERVER_DENIED", "Сервер IPsec вне допуска", 403)
|
|
const request = schema.parse({ serverId: input.serverId, peerId: input.peerId, force: input.force })
|
|
if (fingerprint(request) !== input.requestProof || fingerprint(current.policy) !== input.policyProof || fingerprint(current.owner_permissions) !== input.ownerProof || await accessGeneration() !== input.generation) throw new McpError("RESET_REQUIRED", "Допуск или запрос IPsec изменился", 409)
|
|
if (signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение IPsec отменено", 409)
|
|
}
|
|
async function source(input: Record<string, unknown>, signal?: AbortSignal, allow: () => Promise<unknown> = async () => {}) {
|
|
const authorize = async () => { await allow(); await access(input, signal) }
|
|
await authorize()
|
|
const { server } = await routerClient(Number(input.serverId)), state = await readIpsecPeerDeleteState(server, authorize)
|
|
if (input.expectedSource !== undefined && input.expectedSource !== state.source) throw new McpError("STATE_CONFLICT", "Источник IPsec изменился после подготовки", 409)
|
|
await authorize()
|
|
return { server, state, authorize }
|
|
}
|
|
export function hasVerifiedIpsecPeerDeletion(candidate: unknown, 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> | null
|
|
return row.connection_id === (input.principal as { connectionId?: string } | undefined)?.connectionId && row.state === "verified" && fingerprint(row.intended_state) === fingerprint(redact({ kind: "service", service: operation, input })) && !!result && result.receiptId === input.receiptId && result.verified === true && result.historyRecorded === true && result.revisionRecorded === true && result.peerId === input.peerId && result.force === input.force && result.commandCount === 1 && result.completedCommands === 1 && result.afterProof === proof && proof === input.expectedAfterProof
|
|
}
|
|
export async function prepareIpsecPeerDeletion(serverId: number, peerId: string, context: ActionContext, force = false): Promise<ChangeEvidence> {
|
|
const request = schema.parse({ serverId, peerId, force })
|
|
const internal = { ...request, requestProof: fingerprint(request), principal: context.principal, ownerId: context.connection.owner_id, policyProof: fingerprint(context.connection.policy), ownerProof: fingerprint(context.connection.owner_permissions), generation: await accessGeneration(), operationId: operation, receiptId: randomUUID() }
|
|
const { state, authorize } = await source(internal, context.signal)
|
|
const { linked } = ipsecPeerDeleteTarget(state, peerId, force)
|
|
const objects: ChangeEvidence["objects"] = [{ kind: "server", id: String(serverId), serverId }, { kind: "ipsec_peer", id: peerId, serverId }]
|
|
for (const item of state.protections as { object_ref: { kind: string; id: string } }[]) objects.push({ kind: item.object_ref.kind, id: item.object_ref.id, serverId })
|
|
await authorize()
|
|
return { target: { scope: "servers", serverIds: [serverId] }, objects, snapshots: [], requiresHuman: true, mutationCost: 2, before: { proof: state.proof },
|
|
steps: [{ kind: "service", service: operation, input: { ...internal, expectedSource: state.source, expectedProof: state.proof, expectedAfterProof: await ipsecPeerDeleteProof(projectIpsecPeerDelete(state, peerId)), proofRevision: 2, beforeFingerprint: fingerprint({ proof: state.proof }) } }],
|
|
warnings: [`Одна native DELETE выбранного peer. Связанных identities: ${linked.length}; force=${force}. Identity, сертификаты, mode-config и политики сохраняются; force разрешает разрыв ссылок.`, "Удаление и managed-only история приложения учитываются отдельно. Потеря ответа останавливает операцию без повтора; совпадение конфигурации не подтверждает доставку ответа, историю или передачу трафика."] }
|
|
}
|
|
export function registerIpsecPeerDeleteActions(register: typeof add) {
|
|
const current = async (input: Record<string, unknown>) => ({ proof: (await source(input)).state.proof })
|
|
registerMcpService(operation, { current,
|
|
execute: async input => {
|
|
const before = await source(input)
|
|
return deleteIpsecPeerGuarded(before.server, String(input.peerId), input.force === true, String(input.expectedProof), async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }, { receiptId: String(input.receiptId) })
|
|
},
|
|
verify: async (input, result) => {
|
|
const latest = await source(input), candidate = { connection_id: (input.principal as { connectionId: string }).connectionId, state: "verified", intended_state: redact({ kind: "service", service: operation, input }), result }
|
|
return hasVerifiedIpsecPeerDeletion(candidate, input, latest.state.proof)
|
|
},
|
|
reconcile: async (input, allow) => {
|
|
if (input.proofRevision !== 2 || !z.string().uuid().safeParse(input.receiptId).success || typeof input.expectedProof !== "string" || !/^[a-f0-9]{64}$/.test(input.expectedProof) || typeof input.expectedAfterProof !== "string" || !/^[a-f0-9]{64}$/.test(input.expectedAfterProof)) throw new McpError("UNSUPPORTED_CAPABILITY", "Нет совместимого private proof; требуется ручная сверка", 409)
|
|
const latest = await source(input, undefined, allow)
|
|
const generic = (await pool.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", [(input.principal as { connectionId: string }).connectionId, input.receiptId])).rows
|
|
const verifiedFinal = generic.length === 1 && hasVerifiedIpsecPeerDeletion(generic[0], input, latest.state.proof)
|
|
const final = await source(input, undefined, allow)
|
|
if (final.state.proof !== latest.state.proof) throw new McpError("STATE_CONFLICT", "IPsec изменился во время сверки", 409)
|
|
return { matchesOriginalState: latest.state.proof === input.expectedProof, configurationMatchesDesiredState: latest.state.proof === input.expectedAfterProof, matchesDesiredState: verifiedFinal, verifiedFinalCheckpointAvailable: verifiedFinal, automaticReplay: false, forwardingVerified: false }
|
|
},
|
|
})
|
|
register("network.ipsec.peers.delete", "mm_ipsec_peer_remove_plan", "Удалить IPsec peer с точным force и проверкой сохранности конфигурации", "network", "mm:network:write", "write", "servers", schema, { version: 2, prepare: (input, context) => prepareIpsecPeerDeletion(Number(input.serverId), String(input.peerId), context, input.force === true) })
|
|
}
|