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

158 lines
15 KiB
TypeScript

import { createHash, randomUUID, timingSafeEqual } from "node:crypto"
import { z } from "zod"
import type { PoolClient } from "pg"
import type { IpsecCertBundle } from "@mmapp/contracts/ipsec"
import { pool } from "../db/index.js"
import { hasPermission, type AuthUser } from "../lib/permissions.js"
import { getServerRowById } from "../modules/servers/repository/servers-repository.js"
import { ipsecPeerDeleteSourceProof } from "./ipsec-peer-delete.js"
import { readIpsecExistingCertificateExportState, assertIpsecExistingCertificateExportAccess } from "./ipsec-existing-certificate-export.js"
import { assertLogArtifactBudget } from "../modules/mcp/log-artifacts.js"
import { assertPortalClaimsCurrent } from "../modules/mcp/portal-revocation.js"
import { connectionWrite } from "../modules/mcp/store.js"
import { decryptSecret, encryptSecret, fingerprint, privateSecretFingerprint, McpError } from "../modules/mcp/security.js"
const digest = z.string().regex(/^[a-f0-9]{64}$/)
import { IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED, ipsecExistingCertificateExportAuthoritySchema, type IpsecExistingCertificateExportAuthority } from "./ipsec-existing-certificate-export-model.js"
function activation() { if (!IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED) throw new McpError("APPROVAL_REQUIRED", "Выдача существующих IPsec сертификатов/CA через портал выключена", 409) }
export const ipsecExistingCertificateExportArtifactScopeSchema = z.object({ version: z.literal(1), kind: z.literal("ipsec-existing-certificate-bundle"), authority: ipsecExistingCertificateExportAuthoritySchema, afterProof: digest, bytes: z.number().int().positive().max(1048576), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
const scopeSchema = ipsecExistingCertificateExportArtifactScopeSchema
type Header = { id: string; connection_id: string; filename: string; media_type: string; expires_at: Date }
type Meta = Header & { access_scope: z.infer<typeof scopeSchema>; encrypted_bytes: number }
const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex")
const sign = (value: unknown) => privateSecretFingerprint(fingerprint(value), "ipsec-existing-certificate-bundle-artifact-v1")
const signed = (header: Header, scope: Omit<Meta["access_scope"], "proof">) => ({ id: header.id, connection_id: header.connection_id, filename: header.filename, media_type: header.media_type, expires_at: header.expires_at.toISOString(), scope })
const fail = (message: string, code = "ARTIFACT_INVALID") => new McpError(code, message, 409)
export const ipsecExistingCertificateExportArtifactReceipt = (header: Pick<Header, "id">, scope: Pick<Meta["access_scope"], "bytes" | "sha256">) => ({ artifactId: header.id, downloadPath: `/api/mcp/artifacts/${header.id}`, expiresInSeconds: 900, bytes: scope.bytes, sha256: scope.sha256, humanDownloadOnly: true as const, ipsecContentReturned: false as const })
type ArtifactClient = Pick<PoolClient, "query">
export interface IpsecExistingCertificateExportArtifactStoreDependencies {
query(sql: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>
transaction<T>(work: (client: ArtifactClient) => Promise<T>): Promise<T>
access(authority: IpsecExistingCertificateExportAuthority, client?: ArtifactClient): Promise<unknown>
source(authority: IpsecExistingCertificateExportAuthority, authorize: () => Promise<unknown>): Promise<{ proof: string }>
checkClaims(actor: AuthUser): Promise<unknown>
/** Mandatory trusted admission. Production always uses the closed gate. */
authorizeExport(): void | Promise<void>
}
async function access(authority: IpsecExistingCertificateExportAuthority, client: Pick<typeof pool, "query"> = pool) { await assertIpsecExistingCertificateExportAccess(authority, client) }
async function source(authority: IpsecExistingCertificateExportAuthority, authorize: () => Promise<unknown> = async () => {}) {
const check = async () => { await authorize(); await access(authority) }
await check()
const server = await getServerRowById(authority.request.serverId)
if (!server || await ipsecPeerDeleteSourceProof(server) !== authority.sourceProof) throw fail("Источник пакета IPsec изменился", "STATE_CONFLICT")
return readIpsecExistingCertificateExportState(server, check)
}
/** Constructing a store performs no I/O and grants no admission. Crypto, its
* purpose-separated HMAC domain, storage budgets and human policy stay fixed. */
export function createIpsecExistingCertificateExportArtifactStore(deps: IpsecExistingCertificateExportArtifactStoreDependencies) {
async function create(authority: IpsecExistingCertificateExportAuthority, bundle: IpsecCertBundle, afterProof: string, authorize: () => Promise<unknown>) {
await deps.authorizeExport()
ipsecExistingCertificateExportAuthoritySchema.parse(authority)
if (afterProof !== authority.expectedProof) throw fail("Proof пакета IPsec не совпал с допуском", "STATE_CONFLICT")
await authorize(); await deps.access(authority)
const content = Buffer.from(JSON.stringify(bundle))
try {
if (!content.length || content.length > 1048576) throw fail("Приватный пакет IPsec превышает предел", "EXPORT_LIMIT")
const ciphertext = await encryptSecret(content.toString("base64"))
if (!content.length || content.length > 1048576 || Buffer.byteLength(ciphertext) > 2097152) throw fail("Приватный пакет IPsec превышает предел", "EXPORT_LIMIT")
if ((await deps.source(authority, authorize)).proof !== afterProof) throw fail("IPsec изменился перед сохранением пакета", "STATE_CONFLICT")
const header: Header = { id: randomUUID(), connection_id: authority.principal.connectionId, filename: "ipsec-existing-certificate-bundle.json", media_type: "application/json", expires_at: new Date(Date.now() + 900000) }
const unsigned = { version: 1 as const, kind: "ipsec-existing-certificate-bundle" as const, authority, afterProof, bytes: content.length, sha256: hash(content), encryptedSha256: hash(ciphertext) }
const scope = scopeSchema.parse({ ...unsigned, proof: await sign(signed(header, unsigned)) })
await deps.transaction(async client => {
await authorize()
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [header.connection_id]); await deps.access(authority, client)
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('mcp-log-artifact-storage',0))")
await client.query("DELETE FROM mcp_artifacts WHERE expires_at<=now()")
const usage = (await client.query("SELECT count(*) FILTER(WHERE connection_id=$1)::text AS files,COALESCE(sum(octet_length(ciphertext)) FILTER(WHERE connection_id=$1),0)::text AS own_bytes,COALESCE(sum(octet_length(ciphertext)),0)::text AS total_bytes FROM mcp_artifacts", [header.connection_id])).rows[0]
assertLogArtifactBudget(BigInt(usage.files), BigInt(usage.own_bytes), BigInt(usage.total_bytes), Buffer.byteLength(ciphertext))
await authorize()
await client.query("INSERT INTO mcp_artifacts(id,connection_id,filename,media_type,ciphertext,access_scope,expires_at) VALUES($1,$2,$3,$4,$5,$6::jsonb,$7)", [header.id, header.connection_id, header.filename, header.media_type, ciphertext, JSON.stringify(scope), header.expires_at])
await authorize()
})
await authorize(); await deps.access(authority)
return ipsecExistingCertificateExportArtifactReceipt(header, scope)
} finally { content.fill(0) } // JS strings passed to crypto cannot be erased here.
}
async function meta(id: string): Promise<Meta> {
if (!z.string().uuid().safeParse(id).success) throw fail("Некорректный ID пакета IPsec")
const row = (await deps.query("SELECT id,connection_id,filename,media_type,expires_at,CASE WHEN octet_length(access_scope::text)<=32768 THEN access_scope ELSE NULL END AS access_scope,octet_length(ciphertext)::int AS encrypted_bytes FROM mcp_artifacts WHERE id=$1 AND expires_at>now() AND octet_length(filename)<=1024 AND octet_length(media_type)<=200", [id])).rows[0] as Meta | undefined
if (!row) throw new McpError("NOT_FOUND", "Пакет IPsec отсутствует или срок истёк", 404)
const scope = scopeSchema.safeParse(row.access_scope)
if (!scope.success || row.id !== id || row.filename !== "ipsec-existing-certificate-bundle.json" || row.media_type !== "application/json" || !(row.expires_at instanceof Date) || !Number.isFinite(row.expires_at.getTime()) || row.expires_at.getTime() <= Date.now() || !Number.isSafeInteger(row.encrypted_bytes) || row.encrypted_bytes <= 0 || row.encrypted_bytes > 2097152) throw fail("Метаданные пакета IPsec не подтверждены")
const { proof, ...unsigned } = scope.data
if (row.connection_id !== unsigned.authority.principal.connectionId || !timingSafeEqual(Buffer.from(proof, "hex"), Buffer.from(await sign(signed(row, unsigned)), "hex"))) throw fail("Подпись пакета IPsec не совпала")
return { ...row, access_scope: scope.data }
}
async function checkpoint(row: Meta) {
const scope = row.access_scope
const rows = (await deps.query("SELECT 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 o.state='applied' AND p.operation_id='network.ipsec.existing-certificates.export' AND p.approved_by IS NOT NULL AND s.state='verified' AND s.intended_state->>'kind'='service' AND s.intended_state->>'service'='network.ipsec.existing-certificates.export' AND s.result->>'artifactId'=$2 LIMIT 2", [row.connection_id, row.id])).rows as { intended_state?: { input?: unknown }; result?: Record<string, unknown> }[]
const candidate = rows[0], input = candidate?.intended_state?.input, result = candidate?.result
if (rows.length !== 1 || fingerprint(input) !== scope.authority.inputProof || !result || result.receiptId !== scope.authority.receiptId || result.serverId !== scope.authority.request.serverId || result.certificateId !== scope.authority.certificateId || result.verified !== true || result.ok !== true || result.commandCount !== 2 || result.completedCommands !== 2 || result.confirmedWrites !== 2 || result.afterProof !== scope.afterProof || result.automaticReplay !== false || result.forwardingVerified !== false || Object.entries(ipsecExistingCertificateExportArtifactReceipt(row, scope)).some(([key, value]) => result[key] !== value)) throw fail("Нет точной проверенной квитанции приватного экспорта IPsec", "STATE_CONFLICT")
}
function human(actor: AuthUser, ownerId: string) {
if (!actor || actor.id !== ownerId || !Array.isArray(actor.apps) || !actor.apps.includes("mm") || !Array.isArray(actor.permissions) ||
!hasPermission(actor.permissions, "mm:network:write") || (actor.expiresAt !== undefined && actor.expiresAt <= Date.now())) {
throw new McpError("PERMISSION_DENIED", "Пакет IPsec доступен только владельцу", 403)
}
}
async function verify(id: string, authority: IpsecExistingCertificateExportAuthority, afterProof: string) {
await deps.authorizeExport()
const row = await meta(id), scope = row.access_scope
await deps.access(authority)
if (fingerprint(authority) !== fingerprint(scope.authority) || scope.afterProof !== afterProof) return false
const payload = (await deps.query("SELECT ciphertext FROM mcp_artifacts WHERE id=$1 AND access_scope->>'proof'=$2 AND expires_at>now() AND octet_length(ciphertext)<=2097152", [id, scope.proof])).rows[0]
await deps.access(authority)
return !!payload && typeof payload.ciphertext === "string" && hash(payload.ciphertext) === scope.encryptedSha256 && (await deps.source(authority, async () => { await deps.access(authority) })).proof === afterProof
}
async function metadata(id: string, actor: AuthUser, checkClaims = deps.checkClaims) {
await deps.authorizeExport()
const row = await meta(id), scope = row.access_scope
await checkClaims(actor)
human(actor, scope.authority.ownerId)
await deps.access(scope.authority); await checkpoint(row)
await checkClaims(actor); human(actor, scope.authority.ownerId)
if (row.expires_at.getTime() <= Date.now()) throw fail("Срок пакета IPsec истёк")
return scope
}
async function read(id: string, actor: AuthUser, checkClaims = deps.checkClaims, signal?: AbortSignal) {
await deps.authorizeExport()
const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(45000)]) : AbortSignal.timeout(45000)
const row = await meta(id), scope = row.access_scope
const authorize = async () => { bounded.throwIfAborted(); await checkClaims(actor); human(actor, scope.authority.ownerId); await deps.access(scope.authority); await checkpoint(row); if (row.expires_at.getTime() <= Date.now()) throw fail("Срок пакета IPsec истёк") }
await authorize()
if ((await deps.source(scope.authority, authorize)).proof !== scope.afterProof) throw fail("IPsec изменился после создания пакета", "STATE_CONFLICT")
const payload = (await deps.query("SELECT ciphertext FROM mcp_artifacts WHERE id=$1 AND access_scope->>'proof'=$2 AND expires_at>now() AND octet_length(ciphertext)<=2097152", [id, scope.proof])).rows[0]
await authorize()
if (!payload || typeof payload.ciphertext !== "string" || hash(payload.ciphertext) !== scope.encryptedSha256) throw fail("Шифротекст пакета IPsec изменился")
let content: Buffer
try { content = Buffer.from(await decryptSecret(payload.ciphertext), "base64") } catch { throw fail("Пакет IPsec не расшифрован") }
let delivered = false
try {
if (content.length !== scope.bytes || hash(content) !== scope.sha256) throw fail("Размер или SHA-256 пакета IPsec не совпал")
if ((await deps.source(scope.authority, authorize)).proof !== scope.afterProof) throw fail("IPsec изменился при выдаче пакета", "STATE_CONFLICT")
await authorize()
delivered = true
return { filename: row.filename, mediaType: row.media_type, content }
} finally { if (!delivered) content.fill(0) }
}
return { create, verify, metadata, read }
}
const defaultStore = createIpsecExistingCertificateExportArtifactStore({ query: (sql, values) => pool.query(sql, values), transaction: connectionWrite,
access, source, checkClaims: assertPortalClaimsCurrent, authorizeExport: activation })
export async function createIpsecExistingCertificateExportArtifact(authority: IpsecExistingCertificateExportAuthority, bundle: IpsecCertBundle, afterProof: string, authorize: () => Promise<unknown>) {
activation(); return defaultStore.create(authority, bundle, afterProof, authorize)
}
export async function verifyIpsecExistingCertificateExportArtifact(id: string, authority: IpsecExistingCertificateExportAuthority, afterProof: string) {
activation(); return defaultStore.verify(id, authority, afterProof)
}
export async function humanIpsecExistingCertificateExportMetadata(id: string, actor: AuthUser, checkClaims = assertPortalClaimsCurrent) {
activation(); return defaultStore.metadata(id, actor, checkClaims)
}
export async function readHumanIpsecExistingCertificateExportArtifact(id: string, actor: AuthUser, checkClaims = assertPortalClaimsCurrent, signal?: AbortSignal) {
activation(); return defaultStore.read(id, actor, checkClaims, signal)
}