163 lines
16 KiB
TypeScript
163 lines
16 KiB
TypeScript
import { createHash, randomUUID, timingSafeEqual } from "node:crypto"
|
|
import { z } from "zod"
|
|
import type { PoolClient } from "pg"
|
|
import { pool } from "../../db/index.js"
|
|
import { hasPermission, type AuthUser } from "../../lib/permissions.js"
|
|
import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
|
import { readIxLinuxClient } from "../../services/internet-exchange-execution.js"
|
|
import { IxConflict } from "../../services/internet-exchange-plan.js"
|
|
import { readIxSegment } from "../../services/internet-exchange-store.js"
|
|
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
|
import { assertLogArtifactBudget } from "./log-artifacts.js"
|
|
import { assertPortalClaimsCurrent } from "./portal-revocation.js"
|
|
import { connectionWrite, effectiveMcpConnection, type McpPrincipal } from "./store.js"
|
|
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError, privateSecretFingerprint, redact } from "./security.js"
|
|
|
|
const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576
|
|
const digest = z.string().regex(/^[a-f0-9]{64}$/)
|
|
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict()
|
|
export const mcpWireguardExportRequestSchema = wireguardExportRequestSchema.extend({
|
|
ixSegmentId: z.string().uuid().optional().describe("Для готового конфига Linux из IX укажите ID сегмента и формат peer-conf"),
|
|
}).refine(request => !request.ixSegmentId || request.format === "peer-conf" && !request.peerId && !request.includePrivateKey,
|
|
"Для клиента IX укажите peer-conf и имя интерфейса клиента. Его управляемый ключ будет включён в файл.")
|
|
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: mcpWireguardExportRequestSchema }).strict()
|
|
export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema>
|
|
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest,
|
|
bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
|
|
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), "wireguard-export-artifact-v1")
|
|
const signed = (header: Header, scope: Omit<z.infer<typeof scopeSchema>, "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 async function assertWireguardExportAccess(raw: unknown, client: Pick<PoolClient, "query"> = pool) {
|
|
const authority = wireguardExportAuthoritySchema.parse(raw), connection = await effectiveMcpConnection(authority.principal, client)
|
|
if (connection.owner_id !== authority.ownerId || !hasPermission(connection.owner_permissions,"mm:network:write") || !hasPermission(connection.policy.permissions,"mm:network:write") || !connection.policy.scope.operationIds.includes("network.wireguard.export") || !connection.policy.scope.serverIds.includes(authority.request.serverId)) throw new McpError("PERMISSION_DENIED","Нет допуска к экспорту WireGuard",403)
|
|
if (fingerprint(connection.policy) !== authority.policyProof || await accessGeneration() !== authority.generation) throw fail("Допуск изменился; подготовьте скачивание заново","RESET_REQUIRED")
|
|
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) OR (object_ref->>'kind' IN ('wireguard','wireguard-export') AND object_ref->>'id'=$2)) LIMIT 1",[String(authority.request.serverId),authority.request.interfaceName])).rows[0]
|
|
if(denied)throw fail("Экспорт WireGuard заблокирован защитой объекта","PROTECTED_OBJECT")
|
|
return { connection, serverIds: [authority.request.serverId] }
|
|
}
|
|
|
|
async function protectionProof(authority: WireguardExportAuthority, client: Pick<PoolClient, "query"> = pool) {
|
|
const rows = (await client.query("SELECT id,xmin::text AS revision,CASE WHEN octet_length(object_ref::text)<=32768 THEN object_ref ELSE NULL END AS object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) OR (object_ref->>'kind' IN ('wireguard','wireguard-export') AND object_ref->>'id'=$2) ORDER BY id LIMIT 1001", [String(authority.request.serverId),authority.request.interfaceName])).rows
|
|
if (rows.length>1000 || rows.some(row=>!row.object_ref)) throw fail("Каталог защит экспорта превышает предел", "LIMIT_EXCEEDED")
|
|
return sign({protections:rows})
|
|
}
|
|
export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) {
|
|
await authorize(); await assertWireguardExportAccess(authority)
|
|
const protections=await protectionProof(authority)
|
|
const check = async () => {
|
|
signal?.throwIfAborted()
|
|
await authorize(); await assertWireguardExportAccess(authority)
|
|
if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT")
|
|
}
|
|
const { ixSegmentId, ...request } = authority.request
|
|
if (ixSegmentId) {
|
|
await check()
|
|
const segment = await readIxSegment(ixSegmentId)
|
|
if (!segment) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
|
const access = await readIxLinuxClient(segment, request.serverId, request.interfaceName, "wireguard").catch(error => {
|
|
if (error instanceof IxConflict) throw new McpError(error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
|
|
throw error
|
|
})
|
|
await check()
|
|
const proof = await sign({ protections, ixSegmentId, request, access })
|
|
return { filename: access.filename, content: Buffer.from(access.template), protectionProof: protections, proof }
|
|
}
|
|
const source=await readWireguardExport(request, { signal, authorize: check })
|
|
return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})}
|
|
}
|
|
|
|
const receipt = (header: Header, scope: Pick<z.infer<typeof scopeSchema>, "bytes" | "sha256">) => ({artifactId:header.id,downloadPath:`/api/mcp/artifacts/${header.id}`,expiresInSeconds:900,bytes:scope.bytes,sha256:scope.sha256,humanDownloadOnly:true,wireguardContentReturned:false,configurationApplied:false})
|
|
|
|
export async function createWireguardExportArtifact(authority: WireguardExportAuthority, expectedProof: string) {
|
|
const authorize = assertVerifiedConfigurationAccess
|
|
return executeGuardedApplicationWrite({kind:"wireguard-export",id:authority.request.interfaceName},(await assertWireguardExportAccess(authority)).serverIds,async()=>{
|
|
const source = await readWireguardExportSource(authority,authorize)
|
|
if (source.proof!==expectedProof) throw fail("Экспорт WireGuard изменился после подтверждения","STATE_CONFLICT")
|
|
const ciphertext = await encryptSecret(source.content.toString("base64"))
|
|
if(Buffer.byteLength(ciphertext)>MAX_CIPHER) throw fail("Зашифрованный пакет превышает предел","EXPORT_LIMIT")
|
|
const header: Header = { id: randomUUID(), connection_id: authority.principal.connectionId, filename: source.filename, media_type: "application/octet-stream", expires_at: new Date(Date.now()+900000) }
|
|
const access = { version: 1 as const, kind: "wireguard-export" as const, authority, sourceProof: source.proof, bytes: source.content.length, sha256: hash(source.content), encryptedSha256: hash(ciphertext) }
|
|
const scope = scopeSchema.parse({...access,proof:await sign(signed(header,access))})
|
|
await authorize()
|
|
if ((await readWireguardExportSource(authority,authorize)).proof!==source.proof) throw fail("Конфигурация изменилась во время формирования пакета","STATE_CONFLICT")
|
|
await connectionWrite(async client=>{
|
|
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE",[header.connection_id])
|
|
await assertWireguardExportAccess(authority,client)
|
|
if(await protectionProof(authority,client)!==source.protectionProof) throw fail("Защиты экспорта изменились перед сохранением", "STATE_CONFLICT")
|
|
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 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 assertWireguardExportAccess(authority)
|
|
return receipt(header,access)
|
|
})
|
|
}
|
|
|
|
async function loadMeta(id: string): Promise<Meta> {
|
|
const row = (await pool.query<Meta>("/* MCP WireGuard artifact metadata */ 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]
|
|
if (!row) throw new McpError("NOT_FOUND","Пакет отсутствует или срок истёк",404)
|
|
const scope = scopeSchema.safeParse(row.access_scope)
|
|
if (!scope.success || !(row.expires_at instanceof Date) || !Number.isFinite(row.expires_at.getTime()) || !Number.isSafeInteger(row.encrypted_bytes) || row.encrypted_bytes>MAX_CIPHER) throw fail("Метаданные пакета не подтверждены")
|
|
const {proof,...access} = scope.data, expected = await sign(signed(row,access))
|
|
if (!timingSafeEqual(Buffer.from(proof,"hex"),Buffer.from(expected,"hex")) || row.connection_id!==access.authority.principal.connectionId) throw fail("Подпись пакета не совпала")
|
|
return {...row,access_scope:scope.data}
|
|
}
|
|
async function assertVerifiedCheckpoint(meta: Meta) {
|
|
const scope=meta.access_scope
|
|
const step={kind:"service",service:"network.wireguard.export",input:{authority:scope.authority,expectedProof:scope.sourceProof,beforeFingerprint:fingerprint({proof:scope.sourceProof})}}
|
|
const matches=(await pool.query("SELECT s.operation_id 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.wireguard.export' AND p.approved_by IS NOT NULL AND s.state='verified' AND s.intended_state=$2::jsonb AND s.result=$3::jsonb LIMIT 2",[meta.connection_id,JSON.stringify(redact(step)),JSON.stringify(receipt(meta,scope))])).rows
|
|
if(matches.length!==1)throw fail("Нет точной проверенной квитанции человеческого экспорта", "STATE_CONFLICT")
|
|
}
|
|
export async function verifyWireguardExportArtifact(id: string, authority: WireguardExportAuthority, sourceProof: string) {
|
|
const meta=await loadMeta(id)
|
|
await assertWireguardExportAccess(authority)
|
|
if(fingerprint(meta.access_scope.authority)!==fingerprint(authority) || meta.access_scope.sourceProof!==sourceProof)return false
|
|
const payload=(await pool.query<{ciphertext:string}>("SELECT ciphertext FROM mcp_artifacts WHERE id=$1 AND access_scope->>'proof'=$2 AND expires_at>now() AND octet_length(ciphertext)<=2097152",[id,meta.access_scope.proof])).rows[0]
|
|
await assertWireguardExportAccess(authority)
|
|
return !!payload && hash(payload.ciphertext)===meta.access_scope.encryptedSha256 && (await readWireguardExportSource(authority)).proof===sourceProof
|
|
}
|
|
/** Receipt listing validates sealed metadata and access without reading source or artifact payload. */
|
|
export async function humanWireguardExportMetadata(id: string, actor: AuthUser, checkClaims = assertPortalClaimsCurrent) {
|
|
const meta = await loadMeta(id), scope = meta.access_scope
|
|
await checkClaims(actor)
|
|
if (actor.id !== scope.authority.ownerId || !hasPermission(actor.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Файл доступен только владельцу", 403)
|
|
await assertWireguardExportAccess(scope.authority)
|
|
await assertVerifiedCheckpoint(meta)
|
|
return scope
|
|
}
|
|
export async function readHumanWireguardExportArtifact(id: string, actor: AuthUser, checkClaims = assertPortalClaimsCurrent, signal?:AbortSignal) {
|
|
const deadline=AbortSignal.timeout(45000),bounded=signal?AbortSignal.any([signal,deadline]):deadline
|
|
bounded.throwIfAborted()
|
|
const meta=await loadMeta(id), scope=meta.access_scope
|
|
const authorize=async()=>{
|
|
bounded.throwIfAborted()
|
|
await checkClaims(actor)
|
|
if(actor.id!==scope.authority.ownerId || !hasPermission(actor.permissions,"mm:network:write")) throw new McpError("PERMISSION_DENIED","Экспорт WireGuard доступен только владельцу с правом управления сетью",403)
|
|
await assertWireguardExportAccess(scope.authority)
|
|
await assertVerifiedCheckpoint(meta)
|
|
if(meta.expires_at.getTime()<=Date.now()) throw fail("Срок пакета истёк")
|
|
}
|
|
await authorize()
|
|
if((await readWireguardExportSource(scope.authority,authorize,bounded)).proof!==scope.sourceProof) throw fail("Экспорт WireGuard изменился; подготовьте новый пакет","STATE_CONFLICT")
|
|
const payload=(await pool.query<{ciphertext:string}>("/* MCP WireGuard artifact payload */ 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 || hash(payload.ciphertext)!==scope.encryptedSha256) throw fail("Зашифрованный пакет изменился")
|
|
let content: Buffer
|
|
try{content=Buffer.from(await decryptSecret(payload.ciphertext),"base64")}catch{throw fail("Пакет не расшифрован")}
|
|
await authorize()
|
|
if(Buffer.byteLength(content)!==scope.bytes || hash(content)!==scope.sha256) throw fail("Размер или SHA-256 пакета не совпал")
|
|
if((await readWireguardExportSource(scope.authority,authorize,bounded)).proof!==scope.sourceProof) throw fail("Конфигурация изменилась во время выдачи пакета","STATE_CONFLICT")
|
|
await authorize()
|
|
return {filename:meta.filename,mediaType:meta.media_type,content}
|
|
}
|
|
|
|
export function wireguardExportAuthority(principal: McpPrincipal, ownerId: string, policy: unknown, generation: string, request: unknown) {
|
|
return wireguardExportAuthoritySchema.parse({principal,ownerId,policyProof:fingerprint(policy),generation,request})
|
|
}
|