Files
MikrotikManager/backend/src/modules/mcp/ipsec-existing-certificate-export-actions.ts
T

143 lines
15 KiB
TypeScript

import { randomUUID } from "node:crypto"
import { z } from "zod"
import type { ServerRow } from "../servers/repository/servers-repository.js"
import type { ActionContext, ChangeEvidence } from "./action-types.js"
import type { McpServiceHandler } from "./service-registry.js"
import { hasPermission } from "../../lib/permissions.js"
import { fingerprint, McpError, redact } from "./security.js"
import { ipsecExistingCertificateExportAuthoritySchema, ipsecExistingCertificateExportRequestSchema, IPSEC_EXISTING_CERTIFICATE_EXPORT_OPERATION as operation, planIpsecExistingCertificateExport, type IpsecExistingCertificateExportAuthority as Authority, type IpsecExistingCertificateExportState as State } from "../../services/ipsec-existing-certificate-export-model.js"
export const ipsecExistingCertificateExportActionSchema = ipsecExistingCertificateExportRequestSchema
const bindingSchema = ipsecExistingCertificateExportAuthoritySchema.omit({ inputProof: true }).extend({ deadlineAt: z.number().int().positive() }).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(262144) }).strict()
const protectionSchema = z.array(z.object({ object_ref: z.object({ kind: z.string().min(1), id: z.string().min(1), protection: z.string().optional() }).passthrough() }).strict()).max(1000)
const receiptSchema = z.object({ ok: z.literal(true), verified: z.literal(true), receiptId: z.string().uuid(), certificateId: z.string(), serverId: z.number().int().positive(), commandCount: z.literal(2), completedCommands: z.literal(2), confirmedWrites: z.literal(2), afterProof: z.string().regex(/^[a-f0-9]{64}$/), automaticReplay: z.literal(false), forwardingVerified: z.literal(false), artifactId: z.string().uuid(), downloadPath: z.string(), humanDownloadOnly: z.literal(true), ipsecContentReturned: z.literal(false), expiresInSeconds: z.literal(900), bytes: z.number().int().positive().max(1048576), sha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict()
/** No production defaults or registration: importing this factory cannot activate
* existing-client/server/CA key export. Dependencies are an explicit boundary. */
export interface IpsecExistingCertificateExportAdapterDependencies {
connection: (principal: Authority["principal"]) => Promise<ActionContext["connection"]>
server: (id: number) => Promise<ServerRow | undefined>
sourceProof: (server: ServerRow) => Promise<string>
read: (server: ServerRow, authorize: () => Promise<unknown>, control: { signal: AbortSignal; deadlineAt: number }) => Promise<State>
material: (authority: Authority, authorize: () => Promise<unknown>) => Promise<{ referenceProof: string }>
seal: (value: string) => Promise<string>
open: (value: string) => Promise<string>
execute: (authority: Authority, options: { signal: AbortSignal; timeoutMs: number }) => Promise<unknown>
verifyArtifact: (id: string, authority: Authority, afterProof: string) => Promise<boolean>
query: (sql: string, values: unknown[]) => Promise<Record<string, unknown>[]>
verifiedAccess: () => Promise<unknown>
clock?: () => number
}
const conflict = () => new McpError("STATE_CONFLICT", "Допуск, источник, клиент или passphrase reference экспорта изменились", 409)
export function createIpsecExistingCertificateExportAdapter(deps: IpsecExistingCertificateExportAdapterDependencies) {
const now = deps.clock ?? Date.now
const control = (deadlineAt: number, external?: AbortSignal) => {
const remaining = deadlineAt - now()
if (remaining <= 0) throw new McpError("READ_CANCELLED", "Срок плана приватного экспорта истёк", 409)
const timer = AbortSignal.timeout(Math.min(remaining, 180000))
const signal = external ? AbortSignal.any([external, timer]) : timer
const check = () => { signal.throwIfAborted(); if (now() >= deadlineAt) throw new McpError("READ_CANCELLED", "Срок экспорта истёк", 409) }
const run = async <T>(work: () => Promise<T>) => {
check(); let abort!: () => void
const cancelled = new Promise<never>((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }) })
try { const value = await Promise.race([work(), cancelled]); check(); return value } finally { signal.removeEventListener("abort", abort) }
}
return { signal, deadlineAt, check, run }
}
const access = async (binding: Binding) => {
const c = await deps.connection(binding.principal)
if (Date.parse(binding.principal.credentialExpiresAt) <= now() || c.owner_id !== binding.ownerId || c.owner_valid_until.getTime() <= now() || c.policy.status !== "active" || c.policy.mode === "observer" || Date.parse(c.policy.expiresAt) <= now() || !c.policy.scope.serverIds.includes(binding.request.serverId) || !c.policy.scope.operationIds.includes(operation) || !hasPermission(c.owner_permissions, "mm:network:write") || !hasPermission(c.policy.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Нет актуального допуска приватного экспорта", 403)
if (c.generation !== binding.generation || fingerprint(c.policy) !== binding.policyProof || fingerprint(c.owner_permissions) !== binding.ownerProof || fingerprint(binding.request) !== binding.requestProof) throw conflict()
}
// Persisted intended_state is redacted. Derive its exact proof after sealing;
// the sealed binding deliberately contains no proof of its own ciphertext.
const authority = (binding: Binding, input: Record<string, unknown>): Authority => {
const { deadlineAt: _deadlineAt, ...value } = binding
return ipsecExistingCertificateExportAuthoritySchema.parse({ ...value, inputProof: fingerprint(redact(input)) })
}
const unpack = async (raw: Record<string, unknown>, signal?: AbortSignal) => {
const input = inputSchema.parse(raw), opening = control(now() + 45000, signal)
const binding = bindingSchema.parse(JSON.parse(await opening.run(() => deps.open(input.bindingCiphertext))))
if (binding.request.serverId !== input.serverId || binding.receiptId !== input.receiptId) throw conflict()
return { input, binding, authority: authority(binding, input) }
}
const source = async (binding: Binding, a: Authority, c: ReturnType<typeof control>, external: () => Promise<unknown> = async () => {}, compareReference = true) => {
const authorize = async () => { c.check(); await c.run(external); await c.run(() => access(binding)) }
const check = async () => {
await authorize()
const fresh = await c.run(() => deps.server(binding.request.serverId))
if (!fresh || await c.run(() => deps.sourceProof(fresh)) !== binding.sourceProof) throw conflict()
const material = await c.run(() => deps.material(a, authorize))
if (compareReference && material.referenceProof !== binding.referenceProof) throw conflict()
await authorize()
return { server: fresh, material }
}
const { server, material } = await check()
const state = await c.run(() => deps.read(server, check, { signal: c.signal, deadlineAt: c.deadlineAt }))
await check()
if (state.source !== binding.sourceProof) throw conflict()
const protections = protectionSchema.safeParse(state.protections)
if (!protections.success) throw new McpError("STATE_UNAVAILABLE", "Каталог защит приватного экспорта не подтверждён", 502)
if (protections.data.some(row => row.object_ref.protection === "deny")) throw new McpError("PROTECTED_OBJECT", "Приватный экспорт заблокирован защитой", 409)
return { server, state, material, protections: protections.data }
}
const receipt = (raw: unknown, b: Binding, proof: string) => {
const parsed = receiptSchema.safeParse(raw)
if (!parsed.success) return undefined
const r = parsed.data
return r.receiptId === b.receiptId && r.serverId === b.request.serverId && r.certificateId === b.certificateId && r.afterProof === proof && proof === b.expectedProof && r.downloadPath === `/api/mcp/artifacts/${r.artifactId}` ? r : undefined
}
const prepare = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence> => {
const request = ipsecExistingCertificateExportActionSchema.parse(raw), deadlineAt = now() + 180000, c = control(deadlineAt, context.signal)
const b: Binding = bindingSchema.parse({ principal: context.principal, ownerId: context.connection.owner_id, ownerProof: fingerprint(context.connection.owner_permissions), policyProof: fingerprint(context.connection.policy), generation: context.connection.generation, request, receiptId: randomUUID(), certificateId: "*0", certificateName: "pending", role: "other", sourceProof: "0".repeat(64), expectedProof: "0".repeat(64), referenceProof: "0".repeat(64), requestProof: fingerprint(request), proofRevision: 1, deadlineAt })
await c.run(() => access(b))
const server = await c.run(() => deps.server(request.serverId)); if (!server) throw conflict()
b.sourceProof = await c.run(() => deps.sourceProof(server))
const provisional = authority(b, {}), before = await source(b, provisional, c, undefined, false)
b.referenceProof = before.material.referenceProof
const plan = planIpsecExistingCertificateExport(before.state, server, request, b.receiptId)
b.certificateId = plan.certificateId; b.certificateName = plan.certificateName; b.role = plan.role; b.expectedProof = before.state.proof
if ((await source(b, authority(b, {}), c)).state.proof !== b.expectedProof) throw conflict()
const input = inputSchema.parse({ serverId: request.serverId, receiptId: b.receiptId, bindingCiphertext: await c.run(() => deps.seal(JSON.stringify(b))) })
await c.run(() => access(b))
return { target: { scope: "servers", serverIds: [request.serverId] }, objects: [{ kind: "server", id: String(request.serverId), serverId: request.serverId }, { kind: "certificate", id: plan.certificateId, serverId: request.serverId }, ...plan.companions.map(ref => ({ ...ref, serverId: request.serverId })), ...before.protections.map(row => ({ kind: row.object_ref.kind, id: row.object_ref.id, serverId: request.serverId }))], snapshots: [], before: { proof: b.expectedProof }, requiresHuman: true, mutationCost: 2, validUntil: new Date(deadlineAt).toISOString(), steps: [{ kind: "service", service: operation, input }], warnings: ["Подтверждение разрешает экспорт закрытого ключа выбранного существующего сертификата, чтение PKCS12 и удаление точного временного файла. Две native-команды без повторов и fallback.", ...(plan.role === "ca" ? ["Выбран закрытый ключ CA: отдельное caPrivateKeyExport обязательно; CREATE-клиент approval его не покрывает."] : []), "Приватный пакет доступен только вошедшему владельцу с network-write на 15 минут. Модель получает только квитанцию; готовность передачи трафика не подтверждается."] }
}
const service: McpServiceHandler = {
current: async raw => { const x = await unpack(raw); return { proof: (await source(x.binding, x.authority, control(x.binding.deadlineAt))).state.proof } },
execute: async (raw, context) => {
const signal = context && "signal" in context ? context.signal : undefined
const x = await unpack(raw, signal), c = control(x.binding.deadlineAt, signal)
const before = await source(x.binding, x.authority, c)
const plan = planIpsecExistingCertificateExport(before.state, before.server, x.binding.request, x.binding.receiptId)
if (before.state.proof !== x.binding.expectedProof || plan.certificateId !== x.binding.certificateId || plan.certificateName !== x.binding.certificateName || plan.role !== x.binding.role) throw conflict()
await c.run(deps.verifiedAccess)
if ((await source(x.binding, x.authority, c)).state.proof !== x.binding.expectedProof) throw conflict()
// Executor remains responsible for durable intent/claim and per-dispatch fences.
const result = await c.run(() => deps.execute(x.authority, { signal: c.signal, timeoutMs: Math.min(180000, x.binding.deadlineAt - now()) }))
const after = await source(x.binding, x.authority, c), r = receipt(result, x.binding, after.state.proof)
if (!r || !await c.run(() => deps.verifyArtifact(r.artifactId, x.authority, r.afterProof))) throw new McpError("VERIFICATION_FAILED", "Приватный экспорт не подтверждён точной квитанцией", 502)
if ((await source(x.binding, x.authority, c)).state.proof !== r.afterProof) throw conflict()
return r
},
verify: async (raw, result) => {
const x = await unpack(raw), c = control(x.binding.deadlineAt), after = await source(x.binding, x.authority, c), r = receipt(result, x.binding, after.state.proof)
if (!r || !await c.run(() => deps.verifyArtifact(r.artifactId, x.authority, r.afterProof))) return false
return (await source(x.binding, x.authority, c)).state.proof === r.afterProof
},
reconcile: async (raw, external) => {
const x = await unpack(raw), c = control(x.binding.deadlineAt), latest = await source(x.binding, x.authority, c, external)
const rows = await c.run(() => 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 JOIN mcp_plans p ON p.id=o.plan_id WHERE o.connection_id=$1 AND p.operation_id=$2 AND p.approved_by IS NOT NULL AND o.state='applied' AND s.intended_state->'input'->>'receiptId'=$3 LIMIT 2", [x.binding.principal.connectionId, operation, x.binding.receiptId]))
const row = rows[0], r = receipt(row?.result, x.binding, latest.state.proof)
const exact = rows.length === 1 && row.connection_id === x.binding.principal.connectionId && row.state === "verified" && fingerprint(row.intended_state) === fingerprint(redact({ kind: "service", service: operation, input: x.input }))
const desired = exact && !!r && await c.run(() => deps.verifyArtifact(r.artifactId, x.authority, r.afterProof))
if ((await source(x.binding, x.authority, c, external)).state.proof !== latest.state.proof) throw conflict()
return { matchesOriginalState: latest.state.proof === x.binding.expectedProof, matchesDesiredState: desired, automaticReplay: false, forwardingVerified: false }
},
}
return { prepare, service }
}