119 lines
12 KiB
TypeScript
119 lines
12 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 { buildTrafficFlowHostFilesBundle } from "../../services/traffic-flow-host-files.js"
|
|
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
|
import { assertLogArtifactBudget } from "./log-artifacts.js"
|
|
import { connectionWrite, effectiveMcpConnection, type McpPrincipal } from "./store.js"
|
|
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError, privateSecretFingerprint } 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 hostExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest }).strict()
|
|
export type HostExportAuthority = z.infer<typeof hostExportAuthoritySchema>
|
|
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("netflow-host-files"), authority: hostExportAuthoritySchema, sourceProof: digest,
|
|
bytes: z.number().int().min(1).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), "netflow-host-files-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 assertHostExportAccess(raw: unknown, client: Pick<PoolClient, "query"> = pool) {
|
|
const authority = hostExportAuthoritySchema.parse(raw), connection = await effectiveMcpConnection(authority.principal, client)
|
|
if (connection.owner_id !== authority.ownerId || !connection.policy.scope.allowGlobal || !hasPermission(connection.owner_permissions,"mm:traffic:write") || !hasPermission(connection.policy.permissions,"mm:traffic:write") || !connection.policy.scope.operationIds.includes("traffic.flow.hostFiles.export")) throw new McpError("PERMISSION_DENIED","Нет полного допуска к экспорту ключей коллектора",403)
|
|
if (fingerprint(connection.policy) !== authority.policyProof || await accessGeneration() !== authority.generation) throw fail("Допуск изменился; подготовьте экспорт заново","RESET_REQUIRED")
|
|
const ids = (await client.query<{ id: number }>("SELECT id FROM servers ORDER BY id LIMIT 1001")).rows.map(row=>row.id)
|
|
if (ids.length>1000 || ids.some(id=>!connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED","Экспорт коллектора требует все серверы приложения",403)
|
|
return { connection, serverIds: ids }
|
|
}
|
|
|
|
export async function readHostExportSource(authority: HostExportAuthority, authorize: () => Promise<unknown> = async()=>{}) {
|
|
await authorize()
|
|
const access = await assertHostExportAccess(authority)
|
|
const row = (await pool.query<{ collectorIp: string; prefix: string; flowListenPort: number; wgListenPort: number; hostPrivateKey: string; peers: unknown }>(`SELECT collector_ip AS "collectorIp",prefix,flow_listen_port AS "flowListenPort",wg_listen_port AS "wgListenPort",
|
|
host_private_key AS "hostPrivateKey",CASE WHEN octet_length(peers_json::text)<=1048576 THEN peers_json ELSE NULL END AS peers FROM traffic_flow_settings WHERE id=1`)).rows[0]
|
|
if (!row || !Array.isArray(row.peers) || row.peers.length>1000 || row.peers.some(peer=>!peer || !Number.isSafeInteger(peer.serverId) || !access.serverIds.includes(peer.serverId))) throw fail("Не подтверждён полный набор peers коллектора","STATE_UNAVAILABLE")
|
|
await authorize();await assertHostExportAccess(authority)
|
|
let files
|
|
try { files = await buildTrafficFlowHostFilesBundle(row) } catch { throw fail("Файлы коллектора не сформированы; проверьте конфигурацию","STATE_UNAVAILABLE") }
|
|
const content = JSON.stringify({ version: 1, kind: "netflow-host-files", files },null,2)+"\n"
|
|
if (Buffer.byteLength(content)>MAX_BYTES) throw fail("Пакет файлов превышает 1 МиБ","EXPORT_LIMIT")
|
|
await authorize()
|
|
const final = await assertHostExportAccess(authority)
|
|
if (fingerprint(final.serverIds)!==fingerprint(access.serverIds)) throw fail("Каталог серверов изменился во время экспорта","STATE_CONFLICT")
|
|
return { content, serverIds: access.serverIds, proof: await sign({ serverIds: access.serverIds, content }) }
|
|
}
|
|
|
|
export async function createHostFilesArtifact(authority: HostExportAuthority, expectedProof: string) {
|
|
const authorize = assertVerifiedConfigurationAccess
|
|
return executeGuardedApplicationWrite({kind:"netflow-host-files",id:"1"},(await assertHostExportAccess(authority)).serverIds,async()=>{
|
|
const source = await readHostExportSource(authority,authorize)
|
|
if (source.proof!==expectedProof) throw fail("Файлы или ключи коллектора изменились после подтверждения","STATE_CONFLICT")
|
|
const ciphertext = await encryptSecret(source.content)
|
|
if(Buffer.byteLength(ciphertext)>MAX_CIPHER) throw fail("Зашифрованный пакет превышает предел","EXPORT_LIMIT")
|
|
const header: Header = { id: randomUUID(), connection_id: authority.principal.connectionId, filename: "netflow-host-files.json", media_type: "application/json", expires_at: new Date(Date.now()+900000) }
|
|
const access = { version: 1 as const, kind: "netflow-host-files" as const, authority, sourceProof: source.proof, bytes: Buffer.byteLength(source.content), sha256: hash(source.content), encryptedSha256: hash(ciphertext) }
|
|
const scope = scopeSchema.parse({...access,proof:await sign(signed(header,access))})
|
|
await authorize()
|
|
if ((await readHostExportSource(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 assertHostExportAccess(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 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 assertHostExportAccess(authority)
|
|
return {artifactId:header.id,downloadPath:`/api/mcp/artifacts/${header.id}`,expiresInSeconds:900,bytes:access.bytes,sha256:access.sha256,humanDownloadOnly:true,keyMaterialReturned:false,configurationApplied:false}
|
|
})
|
|
}
|
|
|
|
async function loadMeta(id: string): Promise<Meta> {
|
|
const row = (await pool.query<Meta>("/* MCP host artifact metadata */ SELECT id,connection_id,filename,media_type,expires_at,access_scope,octet_length(ciphertext)::int AS encrypted_bytes FROM mcp_artifacts WHERE id=$1 AND expires_at>now()",[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.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}
|
|
}
|
|
export async function verifyHostFilesArtifact(id: string, authority: HostExportAuthority, sourceProof: string) {
|
|
const meta=await loadMeta(id)
|
|
await assertHostExportAccess(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 assertHostExportAccess(authority)
|
|
return !!payload && hash(payload.ciphertext)===meta.access_scope.encryptedSha256 && (await readHostExportSource(authority)).proof===sourceProof
|
|
}
|
|
export async function readHumanHostFilesArtifact(id: string, actor: AuthUser) {
|
|
const meta=await loadMeta(id), scope=meta.access_scope
|
|
const authorize=async()=>{
|
|
if(actor.id!==scope.authority.ownerId || !hasPermission(actor.permissions,"mm:traffic:write")) throw new McpError("PERMISSION_DENIED","Пакет с ключами доступен только владельцу с правом настройки NetFlow",403)
|
|
await assertHostExportAccess(scope.authority)
|
|
if(meta.expires_at.getTime()<=Date.now()) throw fail("Срок пакета истёк")
|
|
}
|
|
await authorize()
|
|
if((await readHostExportSource(scope.authority,authorize)).proof!==scope.sourceProof) throw fail("Файлы или ключи коллектора изменились; подготовьте новый пакет","STATE_CONFLICT")
|
|
const payload=(await pool.query<{ciphertext:string}>("/* MCP host 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: string
|
|
try{content=await decryptSecret(payload.ciphertext)}catch{throw fail("Пакет не расшифрован")}
|
|
await authorize()
|
|
if(Buffer.byteLength(content)!==scope.bytes || hash(content)!==scope.sha256) throw fail("Размер или SHA-256 пакета не совпал")
|
|
if((await readHostExportSource(scope.authority,authorize)).proof!==scope.sourceProof) throw fail("Конфигурация изменилась во время выдачи пакета","STATE_CONFLICT")
|
|
await authorize()
|
|
return {filename:meta.filename,mediaType:meta.media_type,content}
|
|
}
|
|
|
|
export function hostExportAuthority(principal: McpPrincipal, ownerId: string, policy: unknown, generation: string) {
|
|
return hostExportAuthoritySchema.parse({principal,ownerId,policyProof:fingerprint(policy),generation})
|
|
}
|