193 lines
15 KiB
TypeScript
193 lines
15 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { mkdtemp, readdir, unlink, rmdir } from "node:fs/promises"
|
|
import os from "node:os"
|
|
import path from "node:path"
|
|
import type { PoolClient } from "pg"
|
|
import type { AuthUser } from "../lib/permissions.js"
|
|
import type { IpsecExistingCertificateExportAuthority as Authority } from "./ipsec-existing-certificate-export-model.js"
|
|
import { IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED } from "./ipsec-existing-certificate-export-model.js"
|
|
import { createIpsecExistingCertificateExportArtifactStore, createIpsecExistingCertificateExportArtifact,
|
|
verifyIpsecExistingCertificateExportArtifact, humanIpsecExistingCertificateExportMetadata, readHumanIpsecExistingCertificateExportArtifact,
|
|
type IpsecExistingCertificateExportArtifactStoreDependencies as Dependencies } from "./ipsec-existing-certificate-export-artifact.js"
|
|
import { fingerprint, privateSecretFingerprint, McpError } from "../modules/mcp/security.js"
|
|
import { pool, closePool } from "../db/index.js"
|
|
|
|
// Synthetic bytes and real crypto in an isolated temporary key directory. All
|
|
// SQL/access/source/admission are injected; no RouterOS/PKI/export is executed.
|
|
const directory = await mkdtemp(path.join(os.tmpdir(), "mm-ipsec-artifact-test-"))
|
|
const originalState = process.env.MCP_STATE_DIR
|
|
process.env.MCP_STATE_DIR = directory
|
|
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150", connectionId = "fa58fa40-4bcb-4616-9316-cb69463b3151"
|
|
const actor: AuthUser = { id: "artifact-owner", email: "[email protected]", name: "Synthetic owner", apps: ["mm"], permissions: ["mm:network:write"], expiresAt: Date.now() + 3600000, issuedAt: Date.now() - 1000 }
|
|
const input = { serverId: 207, receiptId: id, bindingCiphertext: "[redacted]" }
|
|
const authority: Authority = { principal: { connectionId, credentialId: id, credentialExpiresAt: new Date(Date.now() + 3600000).toISOString() }, ownerId: actor.id,
|
|
ownerProof: "a".repeat(64), policyProof: "b".repeat(64), generation: "synthetic-generation", request: { serverId: 207,
|
|
selector: { kind: "certificate", name: "synthetic-certificate" }, privateKeyExport: true, caPrivateKeyExport: false, passphrase: { kind: "generate" } },
|
|
receiptId: id, certificateId: "*c1", certificateName: "synthetic-certificate", role: "client", sourceProof: "c".repeat(64), expectedProof: "d".repeat(64),
|
|
referenceProof: "e".repeat(64), requestProof: "f".repeat(64), inputProof: fingerprint(input), proofRevision: 1 }
|
|
const bundle = { user: "synthetic-user", filename: "synthetic.p12", mime: "application/x-pkcs12", contentB64: "SYNTHETIC_PRIVATE_BYTES", passphrase: "SYNTHETIC_PASSPHRASE" }
|
|
const serialized = JSON.stringify(bundle), encoded = Buffer.from(serialized).toString("base64")
|
|
type Row = Record<string, unknown>
|
|
function fixture() {
|
|
let stored: Row | undefined, pending: Row | undefined
|
|
let result: Row | undefined
|
|
let checkpointRows = 1, permit = true, denied = false, claimsDenied = false, sourceProof = authority.expectedProof
|
|
let sourceCalls = 0, payloadReads = 0, queries = 0, admissions = 0, failAfterInsert = false
|
|
let usage = { files: "0", own_bytes: "0", total_bytes: "0" }
|
|
let claimHook: (() => void) | undefined, sourceHook: (() => void) | undefined
|
|
const query: Dependencies["query"] = async (sql, values = []) => {
|
|
queries++
|
|
if (sql.includes("SELECT id,connection_id,filename")) {
|
|
assert(!sql.includes("SELECT ciphertext")); assert.match(sql, /octet_length\(access_scope::text\)<=32768/)
|
|
if (!stored || values[0] !== stored.id || (stored.expires_at as Date).getTime() <= Date.now()) return { rows: [] }
|
|
const { ciphertext, ...meta } = stored
|
|
return { rows: [{ ...structuredClone(meta), encrypted_bytes: Buffer.byteLength(String(ciphertext)) }] }
|
|
}
|
|
if (sql.includes("SELECT s.intended_state,s.result")) {
|
|
assert.match(sql, /p.operation_id='network.ipsec.existing-certificates.export'/); assert.match(sql, /p.approved_by IS NOT NULL/)
|
|
assert.match(sql, /s.state='verified'/); assert.match(sql, /LIMIT 2/)
|
|
assert.deepEqual(values, [connectionId, stored?.id])
|
|
return { rows: Array.from({ length: checkpointRows }, () => ({ intended_state: { input }, result: structuredClone(result) })) }
|
|
}
|
|
if (sql.startsWith("SELECT ciphertext")) {
|
|
payloadReads++; assert.match(sql, /octet_length\(ciphertext\)<=2097152/)
|
|
return { rows: stored && values[0] === stored.id && values[1] === (stored.access_scope as Row).proof ? [{ ciphertext: stored.ciphertext }] : [] }
|
|
}
|
|
throw Error("Unexpected synthetic query")
|
|
}
|
|
const deps: Dependencies = { query, transaction: async work => {
|
|
const client = { query: async (sql: string, values: unknown[] = []) => {
|
|
if (sql.includes("FROM mcp_connections")) { assert.match(sql, /FOR UPDATE/); return { rows: [{ id: connectionId }] } }
|
|
if (sql.includes("pg_advisory_xact_lock") || sql.startsWith("DELETE FROM mcp_artifacts")) return { rows: [] }
|
|
if (sql.startsWith("SELECT count(*)")) return { rows: [usage] }
|
|
assert.match(sql, /^INSERT INTO mcp_artifacts/)
|
|
pending = { id: values[0], connection_id: values[1], filename: values[2], media_type: values[3], ciphertext: values[4], access_scope: JSON.parse(String(values[5])), expires_at: values[6] }
|
|
if (failAfterInsert) throw Error("synthetic transaction failure")
|
|
return { rows: [] }
|
|
} } as Pick<PoolClient, "query">
|
|
try { const value = await work(client); stored = pending; pending = undefined; return value }
|
|
catch (error) { pending = undefined; throw error }
|
|
}, authorizeExport: () => { admissions++; if (!permit) throw new McpError("APPROVAL_REQUIRED", "Synthetic admission closed", 409) },
|
|
access: async a => { assert.equal(fingerprint(a), fingerprint(authority)); if (denied) throw new McpError("PERMISSION_DENIED", "Synthetic access revoked") },
|
|
source: async (_a, authorize) => { sourceCalls++; await authorize(); sourceHook?.(); return { proof: sourceProof } },
|
|
checkClaims: async () => { claimHook?.(); if (claimsDenied) throw new McpError("PERMISSION_DENIED", "Synthetic portal claims revoked") } }
|
|
const store = createIpsecExistingCertificateExportArtifactStore(deps)
|
|
return { store, deps, row: () => { assert(stored); return stored }, result: () => { assert(result); return result },
|
|
stats: () => ({ queries, admissions, sourceCalls, payloadReads }), setCheckpointRows(n: number) { checkpointRows = n },
|
|
revoke() { denied = true }, revokeClaims() { claimsDenied = true }, closeAdmission() { permit = false },
|
|
changeSource() { sourceProof = "0".repeat(64) }, setSourceHook(hook: () => void) { sourceHook = hook }, setClaimsHook(hook: () => void) { claimHook = hook },
|
|
fullQuota() { usage = { files: "8", own_bytes: "0", total_bytes: "0" } }, failTransaction() { failAfterInsert = true },
|
|
async create() { const receipt = await store.create(authority, bundle, authority.expectedProof, async () => {}); result = { ...receipt, ok: true, verified: true,
|
|
receiptId: authority.receiptId, certificateId: authority.certificateId, serverId: 207, commandCount: 2, completedCommands: 2, confirmedWrites: 2,
|
|
afterProof: authority.expectedProof, automaticReplay: false, forwardingVerified: false }; return receipt },
|
|
async resign() { const row = this.row(), scope = row.access_scope as Row, { proof: _proof, ...unsigned } = scope
|
|
scope.proof = await privateSecretFingerprint(fingerprint({ id: row.id, connection_id: row.connection_id, filename: row.filename, media_type: row.media_type,
|
|
expires_at: (row.expires_at as Date).toISOString(), scope: unsigned }), "ipsec-existing-certificate-bundle-artifact-v1") }
|
|
}
|
|
}
|
|
async function trackBuffers(work: (tracked: { created?: Buffer; decoded?: Buffer }) => Promise<void>) {
|
|
const tracked: { created?: Buffer; decoded?: Buffer } = {}, originalFrom = Buffer.from
|
|
Buffer.from = ((...args: unknown[]) => {
|
|
const output = (originalFrom as (...values: unknown[]) => Buffer)(...args)
|
|
if (args[0] === serialized && args[1] === undefined) tracked.created = output
|
|
if (args[0] === encoded && args[1] === "base64") tracked.decoded = output
|
|
return output
|
|
}) as typeof Buffer.from
|
|
try { await work(tracked) } finally { Buffer.from = originalFrom }
|
|
}
|
|
|
|
try {
|
|
const originalQuery = pool.query, originalConnect = pool.connect
|
|
let productionSql = 0
|
|
pool.query = (async () => { productionSql++; return { rows: [] } }) as unknown as typeof pool.query
|
|
pool.connect = (() => { productionSql++; throw Error("Production connection forbidden") }) as typeof pool.connect
|
|
try {
|
|
for (const operation of [() => createIpsecExistingCertificateExportArtifact(authority, bundle, authority.expectedProof, async () => {}),
|
|
() => verifyIpsecExistingCertificateExportArtifact(id, authority, authority.expectedProof),
|
|
() => humanIpsecExistingCertificateExportMetadata(id, actor), () => readHumanIpsecExistingCertificateExportArtifact(id, actor)]) {
|
|
await assert.rejects(operation, error => error instanceof McpError && error.code !== "APPROVAL_REQUIRED")
|
|
}
|
|
assert.equal(IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED, true); assert.ok(productionSql >= 4)
|
|
assert.deepEqual(await readdir(directory), [])
|
|
} finally { pool.query = originalQuery; pool.connect = originalConnect }
|
|
{
|
|
const f = fixture(); assert.equal(f.stats().queries, 0); assert.equal(f.stats().admissions, 0)
|
|
await trackBuffers(async tracked => {
|
|
const receipt = await f.create(); assert(tracked.created); assert(tracked.created.every(value => value === 0))
|
|
assert.equal(receipt.humanDownloadOnly, true); assert.equal(receipt.ipsecContentReturned, false)
|
|
assert.doesNotMatch(JSON.stringify(receipt), /SYNTHETIC_|contentB64|passphrase/)
|
|
})
|
|
assert(!String(f.row().ciphertext).includes("SYNTHETIC_"))
|
|
assert.equal(await f.store.verify(String(f.row().id), authority, authority.expectedProof), true)
|
|
const reads = f.stats().payloadReads
|
|
const scope = await f.store.metadata(String(f.row().id), actor)
|
|
assert.equal(scope.kind, "ipsec-existing-certificate-bundle"); assert.equal(f.stats().payloadReads, reads)
|
|
await trackBuffers(async tracked => {
|
|
const delivered = await f.store.read(String(f.row().id), actor)
|
|
assert.equal(delivered.content, tracked.decoded); assert.equal(delivered.content.toString(), serialized)
|
|
assert.equal(delivered.mediaType, "application/json"); delivered.content.fill(0)
|
|
})
|
|
for (const badActor of [{ ...actor, id: "foreign" }, { ...actor, permissions: ["mm:network:read"] }, { ...actor, apps: [] },
|
|
{ ...actor, expiresAt: Date.now() - 1 }, { connectionId, credentialId: id } as unknown as AuthUser]) {
|
|
const before = f.stats().payloadReads
|
|
await assert.rejects(f.store.metadata(String(f.row().id), badActor)); await assert.rejects(f.store.read(String(f.row().id), badActor))
|
|
assert.equal(f.stats().payloadReads, before)
|
|
}
|
|
}
|
|
for (const mutate of [(f: ReturnType<typeof fixture>) => { f.row().filename = "changed.json" },
|
|
(f: ReturnType<typeof fixture>) => { f.row().connection_id = id },
|
|
(f: ReturnType<typeof fixture>) => { (f.row().access_scope as Row).proof = "0".repeat(64) },
|
|
(f: ReturnType<typeof fixture>) => { (f.row().access_scope as Row).kind = "ipsec-user-bundle" },
|
|
(f: ReturnType<typeof fixture>) => { f.row().expires_at = new Date(Date.now() - 1) },
|
|
(f: ReturnType<typeof fixture>) => { f.revoke() }, (f: ReturnType<typeof fixture>) => { f.revokeClaims() },
|
|
(f: ReturnType<typeof fixture>) => { f.setCheckpointRows(0) }, (f: ReturnType<typeof fixture>) => { f.setCheckpointRows(2) },
|
|
(f: ReturnType<typeof fixture>) => { f.result().humanDownloadOnly = false },
|
|
(f: ReturnType<typeof fixture>) => { f.result().serverId = 208 },
|
|
(f: ReturnType<typeof fixture>) => { f.result().downloadPath = "https://unsafe.invalid" }]) {
|
|
const f = fixture(); await f.create(); mutate(f)
|
|
await assert.rejects(f.store.metadata(String(f.row().id), actor)); assert.equal(f.stats().payloadReads, 0)
|
|
}
|
|
for (const failure of ["checksum", "source", "claims", "aborted"] as const) {
|
|
const f = fixture(); await f.create()
|
|
if (failure === "checksum") { (f.row().access_scope as Row).sha256 = "0".repeat(64); f.result().sha256 = "0".repeat(64); await f.resign() }
|
|
const abort = new AbortController()
|
|
await trackBuffers(async tracked => {
|
|
if (failure === "source") f.setSourceHook(() => { if (tracked.decoded) f.changeSource() })
|
|
if (failure === "claims") f.setClaimsHook(() => { if (tracked.decoded) f.revokeClaims() })
|
|
if (failure === "aborted") f.setSourceHook(() => { if (tracked.decoded) abort.abort() })
|
|
await assert.rejects(f.store.read(String(f.row().id), actor, undefined, abort.signal))
|
|
assert(tracked.decoded, `${failure}: read must reach decoding`); assert(tracked.decoded.every(value => value === 0), `${failure}: decoded buffer must be erased`)
|
|
})
|
|
}
|
|
for (const failure of ["quota", "transaction", "source"] as const) {
|
|
const f = fixture()
|
|
if (failure === "quota") f.fullQuota()
|
|
if (failure === "transaction") f.failTransaction()
|
|
if (failure === "source") f.changeSource()
|
|
await trackBuffers(async tracked => { await assert.rejects(f.create()); assert(tracked.created); assert(tracked.created.every(value => value === 0)) })
|
|
assert.throws(() => f.row())
|
|
}
|
|
{
|
|
const f = fixture(); await f.create(); f.row().ciphertext = String(f.row().ciphertext) + "changed"
|
|
assert.equal(await f.store.verify(String(f.row().id), authority, authority.expectedProof), false)
|
|
await trackBuffers(async tracked => { await assert.rejects(f.store.read(String(f.row().id), actor)); assert.equal(tracked.decoded, undefined) })
|
|
}
|
|
{
|
|
const f = fixture()
|
|
await assert.rejects(f.store.create(authority, { ...bundle, contentB64: "x".repeat(1048576) }, authority.expectedProof, async () => {}), error => error instanceof McpError && error.code === "EXPORT_LIMIT")
|
|
assert.throws(() => f.row())
|
|
}
|
|
{
|
|
const f = fixture(); await f.create(); f.closeAdmission(); const before = f.stats().queries
|
|
for (const operation of [() => f.create(), () => f.store.verify(String(f.row().id), authority, authority.expectedProof),
|
|
() => f.store.metadata(String(f.row().id), actor), () => f.store.read(String(f.row().id), actor)]) await assert.rejects(operation)
|
|
assert.equal(f.stats().queries, before)
|
|
}
|
|
console.log("Existing IPsec artifact store: active default rejects missing SQL authority before crypto; injected admission, real crypto/HMAC, metadata-only human policy, exact checkpoint/source/TTL/budget, rollback and plaintext buffer lifetime passed")
|
|
} finally {
|
|
if (originalState === undefined) delete process.env.MCP_STATE_DIR; else process.env.MCP_STATE_DIR = originalState
|
|
await unlink(path.join(directory, "encryption-key")).catch(() => {})
|
|
await rmdir(directory)
|
|
await closePool()
|
|
}
|