Files
MikrotikManager/backend/src/services/ipsec-existing-certificate-export.ts
T

185 lines
24 KiB
TypeScript

import { randomBytes } from "node:crypto"
import type { IpsecCertBundle } from "@mmapp/contracts/ipsec"
import { pool } from "../db/index.js"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { hasPermission } from "../lib/permissions.js"
import { effectiveMcpConnection, audit, transaction } from "../modules/mcp/store.js"
import { fingerprint, privateSecretFingerprint, McpError, decryptSecret } from "../modules/mcp/security.js"
import { MikrotikClient } from "./mikrotik.js"
import { ipsecPeerDeleteRows, ipsecPeerDeletePaths, ipsecPeerDeleteSourceProof } from "./ipsec-peer-delete.js"
import { ipsecUserUpdateValue } from "./ipsec-user-update.js"
import { sameWireguardEndpoint } from "./wireguard-source.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "./config-mutation-policy.js"
import { buildClientInstructions, buildSswanConfig } from "./ipsec-config.js"
import { planIpsecExistingCertificateExportSelection, type IpsecExistingCertificateExportSelection } from "./ipsec-existing-certificate-export-model.js"
import { IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED, IPSEC_EXISTING_CERTIFICATE_EXPORT_OPERATION, ipsecExistingCertificateExportAuthoritySchema, ipsecExistingCertificateExportSecretPurpose, normalizeIpsecExistingExportPassphrase, projectIpsecExistingCertificateExport, projectIpsecExistingCertificateCleanup, validateIpsecExistingCertificateExportState, type IpsecExistingCertificateExportAuthority, type IpsecExistingCertificateExportState } from "./ipsec-existing-certificate-export-model.js"
export async function ipsecExistingCertificateExportProof(state: IpsecExistingCertificateExportState) { return privateSecretFingerprint(fingerprint(ipsecUserUpdateValue(state)), "ipsec-existing-certificate-export-v1") }
type ExportReadControl = { signal?: AbortSignal; deadlineAt?: number }
export async function readIpsecExistingCertificateExportState(server: ServerRow, authorize: () => Promise<unknown>, control: ExportReadControl = {}) {
const deadlineAt = control.deadlineAt ?? Date.now() + 45000
const remaining = () => { control.signal?.throwIfAborted(); const ms = deadlineAt - Date.now(); if (ms <= 0) throw new McpError("READ_CANCELLED", "Общий срок приватного экспорта истёк", 409); return Math.min(ms, 10000) }
const source = async () => { remaining(); await authorize(); const fresh = await getServerRowById(server.id); remaining(); if (!fresh || !sameWireguardEndpoint(fresh, server)) throw new McpError("STATE_CONFLICT", "Источник приватного экспорта изменился", 409) }
const catalogs: Record<string, Record<string, string>[]> = {}, client = MikrotikClient.fromServer(server)
let bytes = 0
for (const path of [...ipsecPeerDeletePaths, "/file"]) {
await source(); catalogs[path] = ipsecPeerDeleteRows(await client.get(path, remaining(), control.signal, 1048576)); await source()
bytes += Buffer.byteLength(JSON.stringify(catalogs[path])); if (bytes > 1048576) throw new McpError("STATE_UNAVAILABLE", "Полный каталог экспорта превышает 1 МиБ", 502)
}
await source()
const protections = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) ORDER BY id LIMIT 1001", [String(server.id)])).rows
await source()
if (protections.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен бюджет защит экспорта", 502)
const state = { source: await ipsecPeerDeleteSourceProof(server), catalogs, protections, proof: "" }
validateIpsecExistingCertificateExportState(state)
return { ...state, proof: await ipsecExistingCertificateExportProof(state) }
}
export async function assertIpsecExistingCertificateExportAccess(authority: IpsecExistingCertificateExportAuthority, client: Pick<typeof pool, "query"> = pool) {
ipsecExistingCertificateExportAuthoritySchema.parse(authority)
const current = await effectiveMcpConnection(authority.principal, client), request = authority.request
if (Date.parse(authority.principal.credentialExpiresAt) <= Date.now() || current.owner_id !== authority.ownerId || current.owner_valid_until.getTime() <= Date.now() || current.policy.status !== "active" || current.policy.mode === "observer" || Date.parse(current.policy.expiresAt) <= Date.now() || !current.policy.scope.operationIds.includes(IPSEC_EXISTING_CERTIFICATE_EXPORT_OPERATION) || !current.policy.scope.serverIds.includes(request.serverId) || !hasPermission(current.owner_permissions, "mm:network:write") || !hasPermission(current.policy.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Нет отдельного актуального допуска экспорта существующего сертификата", 403)
if (current.generation !== authority.generation || fingerprint(current.owner_permissions) !== authority.ownerProof || fingerprint(current.policy) !== authority.policyProof || fingerprint(request) !== authority.requestProof || !request.privateKeyExport || (authority.role === "ca" && !request.caPrivateKeyExport)) throw new McpError("STATE_CONFLICT", "Owner, запрос, роль или допуск существующего экспорта изменились", 409)
const denied = (await client.query("SELECT 1 FROM mcp_protections WHERE object_ref->>'protection'='deny' AND (object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1)) LIMIT 1", [String(request.serverId)])).rows[0]
if (denied) throw new McpError("PROTECTED_OBJECT", "Экспорт существующего сертификата заблокирован защитой", 409)
}
export async function resolveIpsecExistingCertificateExportPassphrase(authority: IpsecExistingCertificateExportAuthority, authorize: () => Promise<unknown>) {
await authorize()
const request = authority.request
if (request.passphrase.kind === "generate") return { referenceProof: await privateSecretFingerprint(fingerprint({ kind: "generate", receiptId: authority.receiptId }), "ipsec-existing-export-reference-v1"), passphrase: undefined }
const rows = (await pool.query("SELECT purpose,server_id,created_by,xmin::text AS revision,CASE WHEN octet_length(ciphertext)<=32768 THEN ciphertext ELSE NULL END AS ciphertext FROM mcp_secrets WHERE id=$1 AND created_by=$2 LIMIT 2", [request.passphrase.secretRef, authority.ownerId])).rows
await authorize()
const row = rows[0]
if (rows.length !== 1 || row.created_by !== authority.ownerId || row.server_id !== request.serverId || row.purpose !== ipsecExistingCertificateExportSecretPurpose(request.serverId, request.selector) || typeof row.ciphertext !== "string") throw new McpError("SECRET_UNAVAILABLE", "Passphrase reference не принадлежит owner/server/target/purpose существующего экспорта", 409)
const passphrase = await decryptSecret(row.ciphertext).catch(() => { throw new McpError("SECRET_UNAVAILABLE", "Passphrase существующего экспорта недоступен", 409) })
if (passphrase.length < 8 || passphrase.length > 16384) throw new McpError("SECRET_UNAVAILABLE", "Формат passphrase reference не поддержан", 409)
await authorize()
return { passphrase, referenceProof: await privateSecretFingerprint(fingerprint({ id: request.passphrase.secretRef, ...row }), "ipsec-existing-export-reference-v1") }
}
export interface IpsecExistingCertificateExportReceipt { ok: true; verified: true; receiptId: string; certificateId: string; serverId: number; commandCount: 2; completedCommands: 2; confirmedWrites: 2; afterProof: string; automaticReplay: false; forwardingVerified: false; artifactId: string; downloadPath: string; humanDownloadOnly: true; ipsecContentReturned: false }
type Client = Pick<MikrotikClient, "post" | "delete" | "downloadOwnedFile">
export type IpsecExistingCertificateExportBinding = Pick<IpsecExistingCertificateExportAuthority, "receiptId" | "certificateId" | "certificateName" | "role" | "sourceProof" | "expectedProof" | "referenceProof" | "requestProof"> & { request: IpsecExistingCertificateExportSelection }
type ArtifactPublication = Pick<IpsecExistingCertificateExportReceipt, "artifactId" | "downloadPath" | "humanDownloadOnly" | "ipsecContentReturned">
type ExecutionReceipt = Omit<IpsecExistingCertificateExportReceipt, keyof ArtifactPublication>
export interface IpsecExistingCertificateExportTransportDependencies<A extends IpsecExistingCertificateExportBinding, P> {
server: (id: number) => Promise<ServerRow | undefined>; sourceProof: (server: ServerRow) => Promise<string>; access: (authority: A) => Promise<unknown>;
material: (authority: A, authorize: () => Promise<unknown>) => Promise<{ passphrase?: string; referenceProof: string }>;
read: (server: ServerRow, authorize: () => Promise<unknown>, control?: ExportReadControl) => Promise<IpsecExistingCertificateExportState>; proof: (state: IpsecExistingCertificateExportState) => Promise<string>; client: (server: ServerRow) => Client;
boundary: <T>(authority: A, work: () => Promise<T>) => Promise<T>; claim: (authority: A) => Promise<unknown>;
checkpoint: (authority: A, value: { completedCommands: number; afterProof: string; file?: { id: string; name: string; size: number } }) => Promise<unknown>;
publish: (authority: A, bundle: IpsecCertBundle, afterProof: string, authorize: () => Promise<unknown>) => Promise<P>;
generatePassphrase: () => string;
clock?: () => number;
}
export type IpsecExistingCertificateExportDependencies = IpsecExistingCertificateExportTransportDependencies<IpsecExistingCertificateExportAuthority, ArtifactPublication>
export class IpsecExistingCertificateExportExecutionError extends McpError {
constructor(code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", readonly confirmedWrites: number, readonly completedCommands: number) { super(code, "Экспорт существующего сертификата остановлен; повтор, fallback и автоматические обратные команды запрещены. Требуется сверка receipt и временного файла", 502) }
}
/** MCP transport wrapper preserves the persisted authority and receipt shape. */
export function createIpsecExistingCertificateExportFoundation(deps: IpsecExistingCertificateExportDependencies) {
const execute = createIpsecExistingCertificateExportExecutor(deps, raw => ipsecExistingCertificateExportAuthoritySchema.parse(raw))
return async (raw: unknown, options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<IpsecExistingCertificateExportReceipt> => {
const { publication, ...receipt } = await execute(raw, options)
return { ...receipt, ...publication }
}
}
/** One native algorithm for independently authenticated transports. Parsing,
* durable claims and publication remain mandatory trusted I/O dependencies;
* this injectable core has no default activation, actor or MCP principal. */
export function createIpsecExistingCertificateExportExecutor<A extends IpsecExistingCertificateExportBinding, P>(deps: IpsecExistingCertificateExportTransportDependencies<A, P>, parseAuthority: (raw: unknown) => A) {
return async (raw: unknown, options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<ExecutionReceipt & { publication: P }> => {
const authority = parseAuthority(raw)
if (fingerprint(authority.request) !== authority.requestProof) throw new McpError("STATE_CONFLICT", "Запрос экспорта не соответствует sealed authority", 409)
const timeoutMs = options.timeoutMs ?? 180000
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 180000) throw new McpError("INVALID_INPUT", "Некорректный общий срок приватного экспорта", 400)
const clock = deps.clock ?? Date.now
const deadlineAt = clock() + timeoutMs, timerSignal = AbortSignal.timeout(timeoutMs), signal = options.signal ? AbortSignal.any([options.signal, timerSignal]) : timerSignal
const remaining = (limit: number) => { signal.throwIfAborted(); const ms = deadlineAt - clock(); if (ms <= 0) throw new McpError("READ_CANCELLED", "Общий срок экспорта истёк", 409); return Math.min(ms, limit) }
const bounded = async <T>(work: () => Promise<T>): Promise<T> => { remaining(timeoutMs); 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]); remaining(timeoutMs); return value } finally { signal.removeEventListener("abort", abort) } }
let confirmedWrites = 0, completedCommands = 0, nativeAttempted = false
const stopped = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED") => new IpsecExistingCertificateExportExecutionError(code, confirmedWrites, completedCommands)
return bounded(() => deps.boundary(authority, async () => {
const access = async () => { await bounded(() => deps.access(authority)) }
await access()
const material = await bounded(() => deps.material(authority, access))
if (material.referenceProof !== authority.referenceProof) throw new McpError("STATE_CONFLICT", "Passphrase reference экспорта изменился", 409)
const passphrase = normalizeIpsecExistingExportPassphrase(material.passphrase, deps.generatePassphrase)
const source = async () => {
await access()
const current = await bounded(() => deps.server(authority.request.serverId))
if (!current || await bounded(() => deps.sourceProof(current)) !== authority.sourceProof) throw new McpError("STATE_CONFLICT", "Источник экспорта изменился", 409)
if ((await bounded(() => deps.material(authority, access))).referenceProof !== authority.referenceProof) throw new McpError("STATE_CONFLICT", "Passphrase reference изменился до native запроса", 409)
}
await source(); const server = await bounded(() => deps.server(authority.request.serverId))
if (!server) throw new McpError("STATE_CONFLICT", "Сервер экспорта отсутствует", 409)
const read = () => bounded(() => deps.read(server, source, { signal, deadlineAt }))
let state = await read()
if (state.source !== authority.sourceProof || state.proof !== authority.expectedProof) throw new McpError("STATE_CONFLICT", "Полное состояние экспорта изменилось", 409)
const { serverId, selector, privateKeyExport, caPrivateKeyExport } = authority.request
const plan = planIpsecExistingCertificateExportSelection(state, server, { serverId, selector, privateKeyExport, caPrivateKeyExport }, authority.receiptId)
if (plan.certificateId !== authority.certificateId || plan.certificateName !== authority.certificateName || plan.role !== authority.role) throw new McpError("STATE_CONFLICT", "Target сертификата или роль изменились", 409)
await source(); await bounded(() => deps.claim(authority))
const client = deps.client(server)
const fence = async () => { const current = await read(); if (current.proof !== state.proof) throw new McpError("STATE_CONFLICT", "Состояние экспорта изменилось после durable intent", 409); await source() }
let dispatched = false, exportFences = 0, cleanupFences = 0, duplicateFence = false
try { await bounded(() => client.post("/certificate/export-certificate", { name: plan.certificateName, type: "pkcs12", "file-name": plan.exportPrefix, "export-passphrase": passphrase }, remaining(60000), signal, async () => { if (++exportFences !== 1) { duplicateFence = true; throw new McpError("VERIFICATION_FAILED", "Повтор export dispatch fence запрещён", 502) }; await fence(); if (duplicateFence || exportFences !== 1) throw new McpError("VERIFICATION_FAILED", "Export fence отозван параллельным callback", 502); dispatched = true; nativeAttempted = true })); if (!dispatched || exportFences !== 1) throw stopped("VERIFICATION_FAILED"); confirmedWrites++ }
catch (error) { if (duplicateFence || error instanceof IpsecExistingCertificateExportExecutionError) throw stopped("VERIFICATION_FAILED"); if (!dispatched && error instanceof McpError) throw error; throw stopped("MUTATION_OUTCOME_UNKNOWN") }
let file: { id: string; name: string; size: number }
let afterExport: IpsecExistingCertificateExportState
try { afterExport = await read() } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN") }
try { const expected = projectIpsecExistingCertificateExport(state, plan.filename, afterExport); if (await bounded(() => deps.proof(expected.projected)) !== afterExport.proof) throw Error("whole state mismatch"); file = expected.file; state = afterExport; completedCommands++ }
catch { throw stopped("VERIFICATION_FAILED") }
try { await source(); await bounded(() => deps.checkpoint(authority, { completedCommands, afterProof: state.proof, file })) } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN") }
const assertOwned = async () => { await fence() }
let content: Buffer | undefined
try {
try {
await assertOwned()
await bounded(async () => {
const bytes = await client.downloadOwnedFile(file, { authorize: assertOwned, signal, timeoutMs: remaining(30000) })
// A timed-out download may still resolve. Its buffer must be cleared
// here too, after the outer finally has already finished.
if (signal.aborted || clock() >= deadlineAt) { bytes.fill(0); remaining(30000) }
content = bytes
})
if (!content || content.length !== file.size) throw Error("incomplete private file")
await assertOwned()
} catch { throw stopped("MUTATION_OUTCOME_UNKNOWN") }
if (!content) throw stopped("MUTATION_OUTCOME_UNKNOWN")
dispatched = false
try { await bounded(() => client.delete(`/file/${encodeURIComponent(file.id)}`, remaining(10000), async () => { if (++cleanupFences !== 1) { duplicateFence = true; throw new McpError("VERIFICATION_FAILED", "Повтор cleanup dispatch fence запрещён", 502) }; await fence(); if (duplicateFence || cleanupFences !== 1) throw new McpError("VERIFICATION_FAILED", "Cleanup fence отозван параллельным callback", 502); projectIpsecExistingCertificateCleanup(state, file); dispatched = true })); if (!dispatched || cleanupFences !== 1) throw stopped("VERIFICATION_FAILED"); confirmedWrites++ }
catch (error) { if (duplicateFence || error instanceof IpsecExistingCertificateExportExecutionError || (!dispatched && error instanceof McpError)) throw stopped("VERIFICATION_FAILED"); throw stopped("MUTATION_OUTCOME_UNKNOWN") }
let afterCleanup: IpsecExistingCertificateExportState
try { afterCleanup = await read() } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN") }
try { if (await bounded(() => deps.proof(projectIpsecExistingCertificateCleanup(state, file))) !== afterCleanup.proof || afterCleanup.proof !== authority.expectedProof) throw Error("cleanup mismatch"); state = afterCleanup; completedCommands++ }
catch { throw stopped("VERIFICATION_FAILED") }
try { await source(); await bounded(() => deps.checkpoint(authority, { completedCommands, afterProof: state.proof })) } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN") }
const p12B64 = content.toString("base64")
const bundle: IpsecCertBundle = { user: plan.userName, serverEndpoint: plan.serverEndpoint, filename: plan.filename, contentB64: p12B64, mime: "application/x-pkcs12", passphrase, sswanFilename: `${plan.certificateName}.sswan`, sswanContent: buildSswanConfig({ name: `IKEv2 ${plan.serverEndpoint}`, serverEndpoint: plan.serverEndpoint, serverId: plan.serverEndpoint, p12B64 }), instructions: buildClientInstructions({ userName: plan.userName, serverEndpoint: plan.serverEndpoint, p12Filename: plan.filename, passphrase, dns: plan.dns }) }
try { await fence(); const publication = await bounded(() => deps.publish(authority, bundle, state.proof, source)); await fence(); return { ok: true, verified: true, receiptId: authority.receiptId, certificateId: authority.certificateId, serverId: server.id, commandCount: 2, completedCommands: 2, confirmedWrites: 2, afterProof: state.proof, automaticReplay: false, forwardingVerified: false, publication } as const }
catch { throw stopped("MUTATION_OUTCOME_UNKNOWN") }
} finally { content?.fill(0) }
})).catch(error => { if (signal.aborted) { if (nativeAttempted || confirmedWrites) throw stopped("MUTATION_OUTCOME_UNKNOWN"); throw new McpError("READ_CANCELLED", "Экспорт отменён или общий срок истёк до native отправки", 409) }; throw error })
}
}
export async function claimIpsecExistingCertificateExport(authority: IpsecExistingCertificateExportAuthority) {
await assertVerifiedConfigurationAccess(); await assertIpsecExistingCertificateExportAccess(authority)
await transaction(async client => {
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`ipsec-existing-export:${authority.receiptId}`])
await assertIpsecExistingCertificateExportAccess(authority, client)
const rows = (await client.query("SELECT s.intended_state 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 o.state='running' AND p.operation_id=$2 AND p.approved_by IS NOT NULL AND s.state='intent' AND s.intended_state->>'service'=$2 AND s.intended_state->'input'->>'receiptId'=$3 LIMIT 2", [authority.principal.connectionId, IPSEC_EXISTING_CERTIFICATE_EXPORT_OPERATION, authority.receiptId])).rows
if (rows.length !== 1 || fingerprint(rows[0].intended_state.input) !== authority.inputProof || (await client.query("SELECT 1 FROM mcp_audit WHERE connection_id=$1 AND action='ipsec.existing.export.claim' AND payload->>'receiptId'=$2 LIMIT 1", [authority.principal.connectionId, authority.receiptId])).rows.length) throw new McpError("STATE_CONFLICT", "Нет единственного human-approved intent или receipt уже использован; повтор запрещён", 409)
await audit(client, authority.ownerId, "ipsec.existing.export.claim", authority.principal.connectionId, { receiptId: authority.receiptId, inputProof: authority.inputProof })
})
}
/** The fixed activation gate is independent of request flags. A live verified
* plan context is required before locks, configuration audit or native I/O. */
export async function exportIpsecExistingCertificateGuarded(authority: IpsecExistingCertificateExportAuthority, publish: IpsecExistingCertificateExportDependencies["publish"], options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<IpsecExistingCertificateExportReceipt> {
if (!IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED) throw new McpError("APPROVAL_REQUIRED", "Экспорт существующих сертификатов/CA выключен", 409)
await assertVerifiedConfigurationAccess()
return createIpsecExistingCertificateExportFoundation({ server: getServerRowById, sourceProof: ipsecPeerDeleteSourceProof, access: async value => { await assertVerifiedConfigurationAccess(); await assertIpsecExistingCertificateExportAccess(value) }, material: resolveIpsecExistingCertificateExportPassphrase, read: readIpsecExistingCertificateExportState, proof: ipsecExistingCertificateExportProof, client: MikrotikClient.fromServer,
boundary: (value, work) => withApplicationMutationLock(() => withConfigMutationLock([value.request.serverId], () => executeGuardedApplicationWrite({ kind: "certificate", id: value.certificateId }, [value.request.serverId], work))), claim: claimIpsecExistingCertificateExport,
checkpoint: (value, progress) => audit(pool, value.ownerId, "ipsec.existing.export.checkpoint", value.principal.connectionId, { receiptId: value.receiptId, inputProof: value.inputProof, ...progress }), publish, generatePassphrase: () => randomBytes(24).toString("base64url"),
})(authority, options)
}