137 lines
9.7 KiB
TypeScript
137 lines
9.7 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import type { PoolClient } from "pg"
|
|
import type { IpsecExistingCertificateExportRestAuthority as Authority } from "./ipsec-existing-certificate-export-rest.js"
|
|
|
|
// Guard before importing any configured pool or migration/audit runtime.
|
|
const url = new URL(process.env.DATABASE_URL ?? "postgresql://invalid")
|
|
assert.equal(process.env.MMAPP_OWN_IPSEC_EXPORT_JOURNAL, "true")
|
|
assert.equal(url.hostname, "127.0.0.1")
|
|
assert.equal(url.username, "mcp_test")
|
|
assert.equal(url.pathname, "/postgres")
|
|
assert.equal(process.env.MMAPP_OWN_SQL_DB, "postgres")
|
|
assert.match(process.env.MCP_STATE_DIR ?? "", /mm-mcp-test-/)
|
|
const { pool, closePool } = await import("../db/index.js")
|
|
const { applySqlMigrations } = await import("../db/migrate.js")
|
|
const { audit } = await import("../modules/mcp/store.js")
|
|
const { fingerprint } = await import("../modules/mcp/security.js")
|
|
const { createIpsecExistingCertificateExportRestJournal } = await import("./ipsec-existing-certificate-export-rest-journal.js")
|
|
type Dependencies = Parameters<typeof createIpsecExistingCertificateExportRestJournal>[0]
|
|
async function transaction<T>(work: (client: Pick<PoolClient, "query">) => Promise<T>): Promise<T> {
|
|
const client = await pool.connect()
|
|
let committed = false
|
|
try {
|
|
await client.query("BEGIN")
|
|
const result = await work(client)
|
|
await client.query("COMMIT"); committed = true
|
|
return result
|
|
} catch (error) { if (!committed) await client.query("ROLLBACK"); throw error }
|
|
finally { client.release() }
|
|
}
|
|
function authority(): Authority {
|
|
const actor = { id: "rest-export-owned-" + randomUUID(), email: "NEVER_EMAIL", name: "NEVER_NAME", apps: ["mm"], permissions: ["mm:network:write"], issuedAt: Date.now() - 1000, expiresAt: Date.now() + 600000 }
|
|
const request = { serverId: 1, selector: { kind: "certificate" as const, name: "NEVER_CERTIFICATE_NAME" }, privateKeyExport: true as const, caPrivateKeyExport: false }
|
|
return { transport: "rest", actor, ownerProof: fingerprint(actor), requestKey: randomUUID(), receiptId: randomUUID(), deadlineAt: Date.now() + 180000,
|
|
request, requestProof: fingerprint(request), certificateId: "*owned", certificateName: "NEVER_CERTIFICATE_NAME", role: "client", sourceProof: "a".repeat(64), expectedProof: "b".repeat(64), referenceProof: "c".repeat(64) }
|
|
}
|
|
const journal = (overrides: Partial<Dependencies> = {}) => createIpsecExistingCertificateExportRestJournal({ transaction, audit, authorize: async () => {}, ...overrides })
|
|
const claimRows = async (a: Authority) => (await pool.query("SELECT payload FROM mcp_audit WHERE actor_id=$1 AND connection_id IS NULL AND action='ipsec.existing.export.rest.claim' AND payload->>'requestKey'=$2", [a.actor.id, a.requestKey])).rows
|
|
const stageRows = async (a: Authority) => (await pool.query("SELECT payload FROM mcp_audit WHERE actor_id=$1 AND connection_id IS NULL AND action='ipsec.existing.export.rest.checkpoint' AND payload->>'requestKey'=$2 ORDER BY id", [a.actor.id, a.requestKey])).rows
|
|
const stageOne = (a: Authority) => ({ completedCommands: 1, afterProof: "d".repeat(64), file: { id: "*file", name: `mm-ipsec-existing-${a.receiptId}.p12`, size: 128 } })
|
|
const stageTwo = (a: Authority) => ({ completedCommands: 2, afterProof: a.expectedProof })
|
|
const cases: string[] = []
|
|
async function check(name: string, work: () => Promise<void>) { await work(); cases.push(name) }
|
|
try {
|
|
await applySqlMigrations(pool)
|
|
await check("claim persists only exact safe metadata and refuses same actor/key replay", async () => {
|
|
const a = authority(), store = journal(); await store.claim(a)
|
|
assert.equal((await claimRows(a)).length, 1)
|
|
assert.ok(!JSON.stringify(await claimRows(a)).includes("NEVER_"))
|
|
await assert.rejects(store.claim(a)); assert.equal((await claimRows(a)).length, 1)
|
|
})
|
|
await check("changing receipt or target under a spent key cannot dispatch again", async () => {
|
|
const a = authority(), store = journal(); await store.claim(a)
|
|
const request = { ...a.request, selector: { kind: "certificate" as const, name: "another" } }
|
|
await assert.rejects(store.claim({ ...a, receiptId: randomUUID(), request, requestProof: fingerprint(request) }))
|
|
assert.equal((await claimRows(a)).length, 1)
|
|
})
|
|
await check("stable keys are actor scoped", async () => {
|
|
const a = authority(), other = authority(); other.requestKey = a.requestKey
|
|
await journal().claim(a); await journal().claim(other)
|
|
assert.equal((await claimRows(a)).length, 1); assert.equal((await claimRows(other)).length, 1)
|
|
})
|
|
await check("concurrent claims serialize on the real transaction advisory lock", async () => {
|
|
const a = authority(), store = journal()
|
|
const results = await Promise.allSettled([store.claim(a), store.claim(a)])
|
|
assert.equal(results.filter(r => r.status === "fulfilled").length, 1)
|
|
assert.equal((await claimRows(a)).length, 1)
|
|
})
|
|
await check("audit failure rolls back claim before any native work", async () => {
|
|
const a = authority(), store = journal({ audit: async (...args) => { await audit(...args); throw Error("synthetic audit failure") } })
|
|
await assert.rejects(store.claim(a)); assert.equal((await claimRows(a)).length, 0)
|
|
})
|
|
await check("lost COMMIT acknowledgement leaves a spent key and forbids replay", async () => {
|
|
const a = authority(), store = journal({ transaction: async work => { await transaction(work); throw Error("synthetic lost COMMIT acknowledgement") } })
|
|
await assert.rejects(store.claim(a)); assert.equal((await claimRows(a)).length, 1)
|
|
await assert.rejects(journal().claim(a)); assert.equal((await claimRows(a)).length, 1)
|
|
})
|
|
await check("revocation after audit insert rolls back atomically", async () => {
|
|
const a = authority(); let revoked = false
|
|
const store = journal({ audit: async (...args) => { await audit(...args); revoked = true }, authorize: async () => { if (revoked) throw Error("revoked") } })
|
|
await assert.rejects(store.claim(a)); assert.equal((await claimRows(a)).length, 0)
|
|
})
|
|
await check("revocation after an observed real advisory-lock wait blocks the claim", async () => {
|
|
const a = authority(), blocker = await pool.connect(); let revoked = false
|
|
let result: Promise<boolean> | undefined
|
|
try {
|
|
await blocker.query("BEGIN")
|
|
await blocker.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`ipsec-existing-export-rest:${a.actor.id}:${a.requestKey}`])
|
|
result = journal({ authorize: async () => { if (revoked) throw Error("revoked after lock wait") } }).claim(a).then(() => true, () => false)
|
|
let observed = false
|
|
for (let i = 0; i < 50; i++) {
|
|
const waiting = (await pool.query("SELECT 1 FROM pg_catalog.pg_locks WHERE locktype='advisory' AND NOT granted AND database=(SELECT oid FROM pg_catalog.pg_database WHERE datname=current_database()) LIMIT 1")).rows.length
|
|
if (waiting) { observed = true; break }
|
|
await new Promise<void>(resolve => setTimeout(resolve, 10))
|
|
}
|
|
assert.equal(observed, true, "actual waiting backend must be observed before revocation")
|
|
revoked = true
|
|
} finally { await blocker.query("ROLLBACK"); blocker.release() }
|
|
assert.equal(await result, false); assert.equal((await claimRows(a)).length, 0)
|
|
})
|
|
await check("two exact checkpoint stages bind the committed claim without private values", async () => {
|
|
const a = authority(), store = journal(); await store.claim(a)
|
|
await store.checkpoint(a, stageOne(a)); await store.checkpoint(a, stageTwo(a))
|
|
assert.equal((await stageRows(a)).length, 2)
|
|
assert.ok(!JSON.stringify(await stageRows(a)).includes("NEVER_"))
|
|
})
|
|
await check("missing claim or skipped stage cannot manufacture completion", async () => {
|
|
const a = authority(), store = journal()
|
|
await assert.rejects(store.checkpoint(a, stageOne(a)))
|
|
await store.claim(a); await assert.rejects(store.checkpoint(a, stageTwo(a)))
|
|
assert.equal((await stageRows(a)).length, 0)
|
|
})
|
|
await check("checkpoint identity must match all original claim proofs", async () => {
|
|
const a = authority(), store = journal(); await store.claim(a)
|
|
await assert.rejects(store.checkpoint({ ...a, referenceProof: "f".repeat(64) }, stageOne(a)))
|
|
assert.equal((await stageRows(a)).length, 0)
|
|
})
|
|
await check("duplicate or regressing checkpoint stages remain single use", async () => {
|
|
const a = authority(), store = journal(); await store.claim(a); await store.checkpoint(a, stageOne(a))
|
|
await assert.rejects(store.checkpoint(a, stageOne(a)))
|
|
await store.checkpoint(a, stageTwo(a)); await assert.rejects(store.checkpoint(a, stageTwo(a)))
|
|
await assert.rejects(store.checkpoint(a, stageOne(a))); assert.equal((await stageRows(a)).length, 2)
|
|
})
|
|
await check("invalid owned file and false completion evidence fail before append", async () => {
|
|
const a = authority(), store = journal(); await store.claim(a)
|
|
for (const file of [{ ...stageOne(a).file, size: 61439 }, { ...stageOne(a).file, name: "foreign.p12" }, { ...stageOne(a).file, id: "unsafe" }]) await assert.rejects(store.checkpoint(a, { ...stageOne(a), file }))
|
|
await assert.rejects(store.checkpoint(a, { ...stageTwo(a), afterProof: "f".repeat(64) }))
|
|
assert.equal((await stageRows(a)).length, 0)
|
|
})
|
|
await check("concurrent checkpoints cannot duplicate the same stage", async () => {
|
|
const a = authority(), store = journal(); await store.claim(a)
|
|
const result = await Promise.allSettled([store.checkpoint(a, stageOne(a)), store.checkpoint(a, stageOne(a))])
|
|
assert.equal(result.filter(r => r.status === "fulfilled").length, 1); assert.equal((await stageRows(a)).length, 1)
|
|
})
|
|
console.log("Owned REST export journal SQL:", JSON.stringify({ cases: cases.length, names: cases, actualSql: true, nativeCalls: 0, productionDatabaseTouched: false, nativeExportInvoked: false }))
|
|
} finally { await closePool() }
|