Files
MikrotikManager/backend/src/services/server-probe-journal.test.ts
T

172 lines
16 KiB
TypeScript

import assert from "node:assert/strict"
import { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID } from "node:crypto"
import { createSqlServerProbeJournal, ServerProbeJournalConflict, ServerProbeJournalOutcomeUnknown, type ProbeJournalConnections, type ProbeJournalCrypto, type ServerProbeJournalContext } from "./server-probe-journal.js"
import { SERVER_PROBE_JOURNAL_DDL } from "./server-probe-journal-schema.js"
import type { ServerProbeJournalBinding, ServerProbeReceipt } from "./server-probe-execution.js"
type Row = Record<string, unknown>
interface State { anchors: Row[]; stages: Row[]; quarantines: Row[] }
function fixture(kind: "mcp" | "jwt" | "local" = "jwt", bandwidth = false) {
let state: State = { anchors: [], stages: [], quarantines: [] }, live = true, sqlOwner = true, enabled = true, pending: string | undefined, queued = Promise.resolve(), guardCalls = 0, connections = 0
const released: boolean[] = [], queries: string[] = [], key = randomBytes(32)
const context: ServerProbeJournalContext = { identity: kind === "mcp" ? { kind: "mcp", executionId: randomUUID(), ownerId: "real-owner", connectionId: randomUUID(), credentialId: randomUUID(), operationName: "servers.probes.run", issuedAt: 1000, expiresAt: 2000000 } : { kind: "rest", executionId: randomUUID(), ownerId: kind === "local" ? "local-request-actor" : "real-jwt-sub", authentication: kind, requestId: "actual-http-request-17", issuedAt: 1000, expiresAt: 2000000 }, sourceServerId: 1, ...(bandwidth ? { destinationServerId: 2 } : {}), tool: bandwidth ? "bandwidth" : "ping" }
const metadata: ServerProbeJournalBinding = { receiptId: randomUUID(), bindingProof: "a".repeat(64), ownerId: context.identity.ownerId, transport: context.identity.kind, ...(context.identity.kind === "mcp" ? { connectionId: context.identity.connectionId } : { requestId: context.identity.requestId, issuedAt: context.identity.issuedAt }), serverIds: bandwidth ? [1, 2] : [1], tool: context.tool }
const crypto: ProbeJournalCrypto = {
async encrypt(value) { const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", key, iv), body = Buffer.concat([cipher.update(value), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), body]).toString("base64") },
async decrypt(value) { const data = Buffer.from(value, "base64"), decipher = createDecipheriv("aes-256-gcm", key, data.subarray(0, 12)); decipher.setAuthTag(data.subarray(12, 28)); return Buffer.concat([decipher.update(data.subarray(28)), decipher.final()]).toString() },
async proof(domain, value) { return createHmac("sha256", key).update(domain).update(JSON.stringify(value)).digest("hex") },
}
const pool: ProbeJournalConnections = { async connect() {
connections++; let current: State | undefined, unlock: (() => void) | undefined, lastMutation: string | undefined
return { async query(text, values = []) {
queries.push(text)
if (text === "BEGIN") { if (pending === "BEGIN") { pending = undefined; throw Error("NEVER_SQL_SECRET") } return { rows: [] } }
if (text.includes("probe-journal:lock")) {
if (!unlock) { const previous = queued; queued = new Promise<void>(resolve => { unlock = resolve }); await previous; current = structuredClone(state) }
return { rows: [] }
}
if (text === "COMMIT") { if (current) state = structuredClone(current); if (pending !== undefined && pending === lastMutation) { pending = undefined; throw Error("NEVER_LOST_COMMIT_ACK") } return { rows: [] } }
if (text === "ROLLBACK") { current = undefined; return { rows: [] } }
assert.ok(current, "every query uses owned transaction + advisory locks")
const result = (rows: Row[]) => ({ rows: structuredClone(rows) })
if (text.includes("probe-journal:server_probe_executions")) return result(current.anchors.filter(row => row.receipt_id === values[0] || row.identity_kind === values[1] && row.execution_id === values[2]))
if (text.includes("probe-journal:server_probe_execution_quarantines")) return result(current.quarantines.filter(row => row.receipt_id === values[0] || row.identity_kind === values[1] && row.execution_id === values[2]))
if (text.includes("probe-journal:servers")) return result(enabled ? (values[0] as number[]).map(id => ({ id })) : [])
if (text.includes("probe-journal:owner")) {
assert.equal(context.identity.kind, "mcp"); const identity = context.identity as Extract<typeof context.identity, { kind: "mcp" }>
assert.deepEqual(values, [identity.executionId, identity.connectionId, identity.ownerId, identity.credentialId, JSON.stringify(metadata.serverIds), identity.operationName])
assert.match(text, /scope,operationIds/); return result(sqlOwner ? [{ id: identity.executionId }] : [])
}
if (text.includes("probe-journal:claim")) {
if (current.anchors.some(row => row.receipt_id === values[0] || row.identity_kind === values[2] && row.execution_id === values[3])) return result([])
const fields = ["receipt_id", "binding_proof", "identity_kind", "execution_id", "actor_id", "authentication", "mcp_connection_id", "mcp_credential_id", "request_id", "authority_issued_at", "authority_expires_at", "source_server_id", "destination_server_id", "tool"]
const row: Row = Object.fromEntries(fields.map((field, index) => [field, values[index]])); row.state = "claimed"; current.anchors.push(row); lastMutation = "claim"; return result([{ receipt_id: row.receipt_id }])
}
if (text.includes("probe-journal:stages")) return result(current.stages.filter(row => row.receipt_id === values[0]).sort((a, b) => Number(a.stage_index) - Number(b.stage_index)))
if (text.includes("probe-journal:intent")) {
if (current.stages.some(row => row.receipt_id === values[0] && row.stage_index === values[1])) throw Error("duplicate native intent")
current.stages.push({ receipt_id: values[0], stage_index: values[1], kind: values[2], timeout_ms: values[3], state: "intent" }); lastMutation = "intent"; return result([{ stage_index: values[1] }])
}
if (text.includes("probe-journal:received")) {
const row = current.stages.find(row => row.receipt_id === values[0] && row.stage_index === values[1] && row.state === "intent"); if (!row) return result([])
row.state = "received"; row.outcome = values[2]; lastMutation = "received"; return result([{ stage_index: row.stage_index }])
}
if (text.includes("probe-journal:finish")) {
const row = current.anchors.find(row => row.receipt_id === values[0] && row.state === "claimed"); if (!row) return result([])
Object.assign(row, { state: values[1], attempted_stages: values[2], completed_stages: values[3], receipt_ciphertext: values[4], receipt_proof: values[5] }); lastMutation = "finish"; return result([{ receipt_id: values[0] }])
}
if (text.includes("probe-journal:quarantine")) {
if (current.quarantines.some(row => row.receipt_id === values[0] || row.identity_kind === values[2] && row.execution_id === values[3])) return result([])
const fields = ["receipt_id", "binding_proof", "identity_kind", "execution_id", "identity_proof", "error_code", "attempted_stages", "completed_stages"]
current.quarantines.push(Object.fromEntries(fields.map((field, index) => [field, values[index]]))); lastMutation = "quarantine"; return result([{ receipt_id: values[0] }])
}
throw Error("unexpected fake SQL")
}, release(destroy) { released.push(!!destroy); unlock?.() } }
} }
const deps = { connections: pool, crypto, now: () => 1000000, async assertAuthority() { guardCalls++; if (!live) throw Error("NEVER_REVOKED_SECRET") } }
const journal = createSqlServerProbeJournal(context, deps)
const receipt = (): ServerProbeReceipt => ({ receiptId: metadata.receiptId, tool: context.tool, serverId: 1, ...(bandwidth ? { destinationServerId: 2 } : {}), state: "completed", httpStatus: 200, output: "NEVER_PRIVATE_MEASUREMENT", data: { kind: context.tool, known: "NEVER_PRIVATE_MEASUREMENT" }, attemptedStages: 1, completedStages: 1, automaticReplay: false, forwardingVerified: false })
const stage = async () => { await journal.intent({ receiptId: metadata.receiptId, stageIndex: 1, kind: bandwidth ? "native-bandwidth" : "native-ping", timeoutMs: 1000 }); await journal.received({ receiptId: metadata.receiptId, stageIndex: 1, outcome: "received" }) }
const quarantine = () => journal.quarantine({ ...metadata, errorCode: "JOURNAL_UNKNOWN", attemptedStages: 1, completedStages: 0 })
return { journal, context, metadata, receipt, stage, quarantine, queries, crypto, deps, released,
state: () => state, connections: () => connections, guardCalls: () => guardCalls, revoke() { live = false }, restore() { live = true }, denySqlOwner() { sqlOwner = false }, disableServer() { enabled = false }, lose(which: string) { pending = which },
}
}
let cases = 0
async function refused(work: Promise<unknown>) { await assert.rejects(work); cases++ }
for (const authentication of ["mcp", "jwt", "local"] as const) {
const f = fixture(authentication, true)
assert.equal(await f.journal.claim(f.metadata), "claimed"); await f.stage(); await f.journal.finish(f.receipt())
assert.deepEqual(await f.journal.read(f.metadata.receiptId, f.metadata.bindingProof), f.receipt())
assert.equal(await f.journal.claim(f.metadata), "exists")
assert.equal(f.state().anchors.length, 1); const anchor = f.state().anchors[0]
assert.equal(anchor.authentication, authentication); assert.equal(anchor.actor_id, f.context.identity.ownerId)
assert.equal(anchor.mcp_connection_id === null, authentication !== "mcp")
assert.equal(f.queries.some(query => query.includes("probe-journal:owner")), authentication === "mcp")
assert(!JSON.stringify(f.state()).includes("NEVER_PRIVATE_MEASUREMENT"))
const snapshot = structuredClone(f.state()); await refused(f.journal.finish(f.receipt())); assert.deepEqual(f.state(), snapshot)
await refused(f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 2, kind: "native-bandwidth", timeoutMs: 1000 })); assert.deepEqual(f.state(), snapshot)
assert(f.connections() >= 7); cases++
}
{
const f = fixture(), second = createSqlServerProbeJournal(f.context, f.deps)
const results = await Promise.all([f.journal.claim(f.metadata), second.claim(f.metadata)])
assert.deepEqual(results.sort(), ["claimed", "exists"]); assert.equal(f.state().anchors.length, 1); cases++
await refused(createSqlServerProbeJournal(f.context, f.deps).claim({ ...f.metadata, receiptId: randomUUID(), bindingProof: "b".repeat(64) }))
}
for (const mutate of [
(value: ServerProbeJournalBinding) => { value.ownerId = "foreign" },
(value: ServerProbeJournalBinding) => { value.transport = "mcp"; value.connectionId = randomUUID() },
(value: ServerProbeJournalBinding) => { value.requestId = "foreign-http-request" },
(value: ServerProbeJournalBinding) => { value.issuedAt = 1 },
(value: ServerProbeJournalBinding) => { value.serverIds = [1] },
(value: ServerProbeJournalBinding) => { value.serverIds = [2, 1] },
(value: ServerProbeJournalBinding) => { value.tool = "dns" },
]) { const f = fixture("jwt", true), value = structuredClone(f.metadata); mutate(value); await refused(f.journal.claim(value)); assert.equal(f.state().anchors.length, 0) }
{
const f = fixture("mcp"); f.denySqlOwner(); await refused(f.journal.claim(f.metadata)); assert.equal(f.state().anchors.length, 0)
}
{
const f = fixture(); f.disableServer(); await refused(f.journal.claim(f.metadata)); assert.equal(f.state().anchors.length, 0)
}
{
const f = fixture(); f.revoke(); await refused(f.journal.claim(f.metadata)); assert.equal(f.connections(), 0)
}
for (const lost of ["BEGIN", "claim", "intent", "received", "finish"]) {
const f = fixture()
if (["BEGIN", "claim"].includes(lost)) { f.lose(lost); await assert.rejects(f.journal.claim(f.metadata), ServerProbeJournalOutcomeUnknown) }
else {
await f.journal.claim(f.metadata)
if (lost === "intent") { f.lose(lost); await assert.rejects(f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 1, kind: "native-ping", timeoutMs: 1000 }), ServerProbeJournalOutcomeUnknown) }
else if (lost === "received") { await f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 1, kind: "native-ping", timeoutMs: 1000 }); f.lose(lost); await assert.rejects(f.journal.received({ receiptId: f.metadata.receiptId, stageIndex: 1, outcome: "received" }), ServerProbeJournalOutcomeUnknown) }
else { await f.stage(); f.lose(lost); await assert.rejects(f.journal.finish(f.receipt()), ServerProbeJournalOutcomeUnknown) }
}
assert(f.released.includes(true)); const oldAnchor = structuredClone(f.state().anchors)
f.revoke(); await f.quarantine(); f.restore()
assert.deepEqual(f.state().anchors, oldAnchor, "quarantine never rewrites immutable terminal receipts")
assert.equal((await f.journal.read(f.metadata.receiptId, f.metadata.bindingProof))?.state, "unknown")
assert.equal(await createSqlServerProbeJournal(f.context, f.deps).claim(f.metadata), "exists")
await refused(f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 2, kind: "native-ping", timeoutMs: 1000 }))
assert.equal(f.state().quarantines.length, 1); await f.quarantine(); assert.equal(f.state().quarantines.length, 1); cases++
}
{
const f = fixture(); await f.journal.claim(f.metadata)
await refused(f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 2, kind: "native-ping", timeoutMs: 1000 }))
await refused(f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 1, kind: "native-bandwidth", timeoutMs: 1000 }))
await refused(f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 1, kind: "native-ping", timeoutMs: 120001 }))
await f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 1, kind: "source-dns-A", timeoutMs: 1000 })
await refused(f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 2, kind: "native-ping", timeoutMs: 1000 }))
await f.journal.received({ receiptId: f.metadata.receiptId, stageIndex: 1, outcome: "source-unavailable" })
await refused(f.journal.received({ receiptId: f.metadata.receiptId, stageIndex: 1, outcome: "received" }))
await f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 2, kind: "native-ping", timeoutMs: 1000 })
await refused(f.journal.received({ receiptId: f.metadata.receiptId, stageIndex: 2, outcome: "source-unavailable" }))
}
for (const mutate of [
(receipt: ServerProbeReceipt) => { receipt.receiptId = randomUUID() },
(receipt: ServerProbeReceipt) => { receipt.serverId = 99 },
(receipt: ServerProbeReceipt) => { receipt.destinationServerId = 99 },
(receipt: ServerProbeReceipt) => { receipt.completedStages = 2 },
(receipt: ServerProbeReceipt) => { receipt.attemptedStages = 0.5 },
(receipt: ServerProbeReceipt) => { receipt.output = "x".repeat(131073) },
(receipt: ServerProbeReceipt) => { receipt.data = { kind: "ping", value: Number.NaN } },
]) { const f = fixture(); await f.journal.claim(f.metadata); await f.stage(); const receipt = f.receipt(); mutate(receipt); await refused(f.journal.finish(receipt)); assert.equal(f.state().anchors[0].state, "claimed") }
{
const f = fixture(); await f.journal.claim(f.metadata); await f.stage(); await f.journal.finish(f.receipt())
f.state().anchors[0].receipt_proof = "f".repeat(64); await refused(f.journal.read(f.metadata.receiptId, f.metadata.bindingProof))
}
{
const f = fixture(); await f.journal.claim(f.metadata); await f.stage(); await f.journal.finish(f.receipt())
f.state().anchors[0].actor_id = "foreign"; await refused(f.journal.read(f.metadata.receiptId, f.metadata.bindingProof))
}
{
const f = fixture(); await f.journal.claim(f.metadata); await f.journal.intent({ receiptId: f.metadata.receiptId, stageIndex: 1, kind: "native-ping", timeoutMs: 1000 })
const receipt = { ...f.receipt(), state: "cancelled" as const, httpStatus: 502, output: undefined, data: undefined, errorCode: "CANCELLED", attemptedStages: 0, completedStages: 0 }
await f.journal.finish(receipt); assert.equal((await f.journal.read(f.metadata.receiptId, f.metadata.bindingProof))?.state, "cancelled"); cases++
}
assert.match(SERVER_PROBE_JOURNAL_DDL, /UNIQUE\(identity_kind,execution_id\)/)
assert.match(SERVER_PROBE_JOURNAL_DDL, /terminal receipt is immutable/)
assert.match(SERVER_PROBE_JOURNAL_DDL, /quarantine is immutable/)
assert.doesNotMatch(SERVER_PROBE_JOURNAL_DDL, /ON DELETE CASCADE/)
assert.ok(ServerProbeJournalConflict)
console.log(`Server probe SQL journal: ${cases} injected transactional cases passed; MCP/JWT/local identities, single CAS, ordered stages, encrypted immutable receipts, append-only lost-ACK quarantine; no SQL/network executed`)