Files
MikrotikManager/backend/src/services/server-probe-storage-history.sql.test.ts
T

106 lines
13 KiB
TypeScript

import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { readFile } from "node:fs/promises"
import { basename, dirname, resolve } from "node:path"
import type { ServerProbeHistoryBinding } from "./server-probe-journal-history.js"
import type { ServerProbeReceipt } from "./server-probe-execution.js"
assert.equal(process.env.MMAPP_OWN_PROBE_STORAGE_HISTORY, "true")
const url = new URL(process.env.DATABASE_URL ?? "")
assert.equal(url.hostname, "127.0.0.1"); assert.equal(url.pathname, "/postgres")
assert(process.env.MCP_STATE_DIR && basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
const { pool, closePool } = await import("../db/index.js")
const { applyLegacyProbeFixtureMigrations: applySqlMigrations } = await import("../db/legacy-probe-fixture.js")
const security = await import("../modules/mcp/security.js")
const { createMcpServerProbeReadAuthority } = await import("./server-probe-authority.js")
const { createServerProbeStorageHistoryReader } = await import("./server-probe-storage-history.js")
const { ProbePayloadExpired, ProbePayloadUnavailable } = await import("./server-probe-storage-journal-adapter.js")
const { createProbeJournalStorage } = await import("./server-probe-journal-maintenance.js")
const cases: string[] = []
let source: number, destination: number
const crypto = { decrypt: security.decryptSecret, proof: async (domain: string, value: unknown) => security.privateSecretFingerprint(security.fingerprint(value), "server-probe-journal-v1:" + domain) }
async function seed(tamper = "", separated = false) {
const at = separated ? Date.now() : Date.now() - 32 * 86400000, ownerId = "history-" + randomUUID(), connectionId = randomUUID(), oldCredential = randomUUID(), credentialId = randomUUID()
const binding: ServerProbeHistoryBinding = { receiptId: randomUUID(), bindingProof: "a".repeat(64), context: {
identity: { kind: "mcp", ownerId, connectionId, credentialId: oldCredential, executionId: randomUUID(), issuedAt: at, expiresAt: at + 3600000, operationName: "servers.probes.run" },
sourceServerId: source, destinationServerId: destination, tool: "bandwidth" } }
const identity = binding.context.identity
const until = new Date(Date.now() + 3600000), principal = { connectionId, credentialId, credentialExpiresAt: until.toISOString() }
const policy = { id: connectionId, version: 1, status: "active", mode: "observer", permissions: ["mm:servers:read"], expiresAt: until.toISOString(), scope: { serverIds: [source, destination], operationIds: ["servers.probes.receipt.read"], allowGlobal: false } }
await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'owned historical reader',$2,$3::jsonb,$4::jsonb,$5,$6,clock_timestamp())", [connectionId, ownerId, JSON.stringify(policy.permissions), JSON.stringify(policy), await security.accessGeneration(), until])
for (const [id, expires] of [[oldCredential, new Date(identity.expiresAt)], [credentialId, until]]) await pool.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [id, connectionId, randomUUID(), expires])
const receipt: ServerProbeReceipt = { receiptId: binding.receiptId, serverId: source, destinationServerId: destination, tool: "bandwidth", state: "completed", httpStatus: 200, output: "owned historical measurement", data: { kind: "bandwidth" }, attemptedStages: 1, completedStages: 1, automaticReplay: false, forwardingVerified: false }
const plaintext = JSON.stringify({ version: 1, context: binding.context, bindingProof: binding.bindingProof, receipt })
const cipher = tamper === "cipher" ? "untrusted-cipher" : await security.encryptSecret(plaintext)
const proof = tamper === "proof" ? "b".repeat(64) : await crypto.proof("receipt", plaintext)
if (separated) {
// Model an incomplete writer using only valid v2 guard transitions. No
// payload DELETE or trigger bypass is used to manufacture this gap.
await pool.query("INSERT INTO server_probe_storage_admissions(receipt_id,owner_id,identity_kind,execution_id,binding_proof,authority_expires_at,claim_token,retention_days) VALUES($1,$2,'mcp',$3,$4,$5,$6,30)", [binding.receiptId, ownerId, identity.executionId, binding.bindingProof, new Date(identity.expiresAt), randomUUID()])
await pool.query("UPDATE server_probe_storage_admissions SET claim_token=NULL,claim_attempted_at=clock_timestamp() WHERE receipt_id=$1", [binding.receiptId])
}
await pool.query(`INSERT INTO server_probe_executions(receipt_id,binding_proof,identity_kind,execution_id,actor_id,authentication,mcp_connection_id,mcp_credential_id,authority_issued_at,authority_expires_at,source_server_id,destination_server_id,tool,created_at)
VALUES($1,$2,'mcp',$3,$4,'mcp',$5,$6,$7,$8,$9,$10,'bandwidth',$11)`, [binding.receiptId, binding.bindingProof, identity.executionId, ownerId, connectionId, oldCredential, at, new Date(identity.expiresAt), source, destination, new Date(at)])
await pool.query("INSERT INTO server_probe_execution_stages(receipt_id,stage_index,kind,timeout_ms,state,outcome,created_at,received_at) VALUES($1,1,'native-bandwidth',1000,'received','received',$2,$2)", [binding.receiptId, new Date(at)])
if (separated) await pool.query("UPDATE server_probe_executions SET state='completed',attempted_stages=1,completed_stages=1,receipt_proof=$2,finished_at=$3 WHERE receipt_id=$1", [binding.receiptId, proof, new Date(at)])
else await pool.query("UPDATE server_probe_executions SET state='completed',attempted_stages=1,completed_stages=1,receipt_ciphertext=$2,receipt_proof=$3,finished_at=$4 WHERE receipt_id=$1", [binding.receiptId, cipher, proof, new Date(at)])
let decrypts = 0, hook: (() => Promise<void>) | undefined
const access = createMcpServerProbeReadAuthority(principal)
const reader = () => createServerProbeStorageHistoryReader({ options: { deadlineAt: Date.now() + 120000 }, crypto: { ...crypto, async decrypt(value) { decrypts++; await hook?.(); return crypto.decrypt(value) } },
async assertReadAuthority(actual) {
assert.deepEqual(actual, binding)
const current = await access.readAuthority()
assert.equal(current.ownerId, ownerId); assert.equal(current.connectionId, connectionId)
assert.equal(current.credentialId, credentialId); assert.notEqual(credentialId, oldCredential)
assert([source, destination].every(id => current.scopeServerIds.includes(id)))
await access.assertProtections([source, destination], current)
} })
return { binding, receipt, reader, ownerId, connectionId, credentialId, oldCredential, decrypts: () => decrypts, onDecrypt(value: () => Promise<void>) { hook = value } }
}
type Fixture = Awaited<ReturnType<typeof seed>>
const quarantine = async (f: Fixture) => { await pool.query("INSERT INTO server_probe_execution_quarantines(receipt_id,identity_kind,execution_id,binding_proof,identity_proof,error_code,attempted_stages,completed_stages) VALUES($1,'mcp',$2,$3,$4,'JOURNAL_UNKNOWN',1,1)", [f.binding.receiptId, f.binding.context.identity.executionId, f.binding.bindingProof, "c".repeat(64)]) }
const connect = async () => { const client = await pool.connect(); return { query: (text: string, values?: unknown[]) => client.query(text, values), release: (destroy?: boolean) => client.release(destroy) } }
const storage = createProbeJournalStorage({ connect, safetyWindowMs: 60000, policy: { retentionDays: 30, globalBytes: 64000000, ownerBytes: 1000000, globalFiles: 100, ownerFiles: 3, globalAdmissions: 100, ownerAdmissions: 3 }, authorize: async () => "c".repeat(64) })
const purge = (f: Fixture) => storage.purge(f.ownerId, 10, { deadlineAt: Date.now() + 120000 })
try {
await applySqlMigrations(pool)
await pool.query("UPDATE traffic_settings SET enabled=false; UPDATE uptime_settings SET enabled=false,resources_enabled=false,ping_enabled=false,speed_enabled=false; UPDATE mcp_settings SET enabled=true")
const ids = (await pool.query("INSERT INTO servers(name,host,port,enabled) VALUES('history-source','127.0.0.1',9,true),('history-destination','127.0.0.1',9,true) RETURNING id")).rows.map(row => Number(row.id))
;[source, destination] = ids
const normal = await seed(), expired = await seed(), duringPurge = await seed(), duringQuarantine = await seed(), duringRevoke = await seed(), badProof = await seed("proof"), badCipher = await seed("cipher"), scope = await seed(), protection = await seed(), foreign = await seed()
const client = await pool.connect()
try { await client.query(await readFile(new URL("../db/proposals/server-probe-storage-v2.sql", import.meta.url), "utf8")) } finally { client.release(true) }
const orphan = randomUUID()
await assert.rejects(pool.query(`INSERT INTO server_probe_executions(receipt_id,binding_proof,identity_kind,execution_id,actor_id,authentication,mcp_connection_id,mcp_credential_id,authority_issued_at,authority_expires_at,source_server_id,destination_server_id,tool)
VALUES($1,$2,'mcp',$3,$4,'mcp',$5,$6,$7,$8,$9,$10,'bandwidth')`, [orphan, normal.binding.bindingProof, randomUUID(), normal.ownerId, normal.connectionId, normal.credentialId, Date.now(), new Date(Date.now() + 3600000), source, destination]), /no live consumed admission/)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_probe_executions WHERE receipt_id=$1", [orphan])).rows[0].n, 0)
cases.push("actual v2 guard rejects orphan anchor without consumed matching admission")
const incomplete = await seed("", true)
await assert.rejects(incomplete.reader().read(incomplete.binding), ProbePayloadUnavailable); assert.equal(incomplete.decrypts(), 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_probe_executions j JOIN server_probe_storage_admissions a USING(receipt_id) WHERE j.receipt_id=$1 AND a.purged_at IS NULL", [incomplete.binding.receiptId])).rows[0].n, 1)
cases.push("valid spent terminal anchor without payload yields explicit unavailable and preserves attempt metadata")
assert.deepEqual(await normal.reader().read(normal.binding), normal.receipt)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_credentials WHERE id=$1 AND expires_at<clock_timestamp()", [normal.oldCredential])).rows[0].n, 1)
cases.push("converted original expired MCP envelope is authenticated using separate current read credential and both actual participant protections")
assert.equal((await purge(expired)).purged, 1)
await assert.rejects(expired.reader().read(expired.binding), ProbePayloadExpired); assert.equal(expired.decrypts(), 0)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_probe_executions j JOIN server_probe_storage_admissions a USING(receipt_id) WHERE j.receipt_id=$1 AND a.purged_at IS NOT NULL", [expired.binding.receiptId])).rows[0].n, 1)
cases.push("validated purged payload yields explicit expired without decrypt or replay; original metadata survives")
duringPurge.onDecrypt(async () => { assert.equal((await purge(duringPurge)).purged, 1) })
await assert.rejects(duringPurge.reader().read(duringPurge.binding)); cases.push("separate final SQL snapshot observes payload purge committed during decrypt and refuses stale result")
duringQuarantine.onDecrypt(() => quarantine(duringQuarantine))
await assert.rejects(duringQuarantine.reader().read(duringQuarantine.binding)); cases.push("quarantine committed on another backend during decrypt blocks adoption")
duringRevoke.onDecrypt(async () => { await pool.query("UPDATE mcp_credentials SET revoked_at=clock_timestamp() WHERE id=$1", [duringRevoke.credentialId]) })
await assert.rejects(duringRevoke.reader().read(duringRevoke.binding)); cases.push("actual current credential revocation during decrypt blocks adoption despite unchanged original anchor")
for (const f of [badProof, badCipher]) { await assert.rejects(f.reader().read(f.binding)); cases.push("converted " + (f === badProof ? "forged proof" : "malformed ciphertext") + " refuses without rewriting original envelope") }
await pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{scope,serverIds}',$2::jsonb) WHERE id=$1", [scope.connectionId, JSON.stringify([source])])
await assert.rejects(scope.reader().read(scope.binding)); assert.equal(scope.decrypts(), 0); cases.push("missing current destination scope refuses before decrypt")
await pool.query("UPDATE mcp_connections SET owner_id='foreign-owner' WHERE id=$1", [foreign.connectionId])
await assert.rejects(foreign.reader().read(foreign.binding)); assert.equal(foreign.decrypts(), 0); cases.push("current foreign owner refuses before decrypt")
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'owned-history-test')", [randomUUID(), JSON.stringify({ kind: "server", id: String(destination), serverId: destination, protection: "deny" })])
await assert.rejects(protection.reader().read(protection.binding)); assert.equal(protection.decrypts(), 0); cases.push("current participant protection denies before decrypt")
console.log("Owned separated probe history SQL:", JSON.stringify({ cases: cases.length, names: cases, actualSql: true, productionCrypto: true, productionCurrentReadAuthority: true, syntheticOriginalExecution: true, nativeCalls: 0, metadataGcRun: false, productionDdlApplied: false, routesRegistered: false }))
} finally { await closePool() }