import assert from "node:assert/strict" import { test } from "node:test" import { generateKeyPairSync, randomUUID, sign } from "node:crypto" import { mkdtemp, readFile, writeFile, rm, readdir } from "node:fs/promises" import { tmpdir } from "node:os" import path from "node:path" import { captureDatabaseSourceObservation } from "./database-source-observation.js" import type { ProbeStorageSql } from "../services/server-probe-journal-maintenance.js" import { createDatabaseSourceBindingVerifier, readDatabaseSourceBindingRegistry, sourceBindingBytes, sourceBindingCanonical, sourceBindingSha256, DATABASE_SOURCE_SIGNATURE_DOMAINS, DatabaseSourceBindingError } from "./database-source-binding.js" import { provisionDatabaseSourceBindingOffline, databaseSourceBindingOperatorCli } from "../../scripts/database-source-binding-operator.js" assert.equal(process.env.MMAPP_OWN_SOURCE_BINDING_SYNTHETIC, "true") assert.equal(process.env.DATABASE_URL, undefined) const options = () => ({ deadlineAt: Date.now() + 10000 }) const row = () => ({ system_identifier: "18446744073709551615", database_oid: "16384", database_name: "synthetic", session_user: "source_operator", current_user: "source_operator", in_recovery: false, server_version_num: "180006", backend_pid: 123, transaction_timestamp: "2026-10-31 12:34:56.123456+00", snapshot: "100:110:101,105,109", isolation: "repeatable read", read_only: "on", explicit_transaction: true }) function facade(change?: (count: number, value: ReturnType) => Promise) { let count = 0 const sql: ProbeStorageSql = { async query() { const value = row(); await change?.(++count, value); return { rows: [value] } } } return sql } const refused = (error: unknown) => error instanceof DatabaseSourceBindingError async function own(work: (root: string) => Promise) { const root = await mkdtemp(path.join(tmpdir(), "mm-source-binding-synthetic-")) try { return await work(root) } finally { const relative = path.relative(path.resolve(tmpdir()), path.resolve(root)) assert(relative && !relative.startsWith("..") && !path.isAbsolute(relative) && path.basename(root).startsWith("mm-source-binding-synthetic-")) await rm(root, { recursive: true, force: true }) } } async function fixture(root: string) { const key = generateKeyPairSync("ed25519"), privateKeyFile = path.join(root, "synthetic-private.pem") await writeFile(privateKeyFile, key.privateKey.export({ type: "pkcs8", format: "pem" }), { flag: "wx" }) const sql = facade(), observation = await captureDatabaseSourceObservation(sql, options()) const request = { installationId: randomUUID(), sourceIdentityId: randomUUID(), generation: randomUUID(), source: { ...observation.source, inRecovery: false as const } } const issued = await provisionDatabaseSourceBindingOffline({ request, privateKeyFile, outputDirectory: path.join(root, "registry-one") }) const pin = issued.deploymentPin, verifier = createDatabaseSourceBindingVerifier(pin) const headPath = path.join(pin.registryDirectory, "head-" + pin.currentHeadSha256 + ".json") const head = JSON.parse(await readFile(headPath, "utf8")) const bindingPath = path.join(pin.registryDirectory, "binding-" + head.body.bindingSha256 + ".json") return { key, privateKeyFile, sql, observation, request, pin, verifier, headPath, bindingPath } } test("real offline Ed25519 issuance + bounded registry files + genuine same-facade observation verify without READY/generation claims", () => own(async root => { const f = await fixture(root), result = await f.verifier.verify(f.sql, f.observation, options()) assert.equal(result.operatorSignatureVerified, true); assert.equal(result.currentHeadPinVerified, true); assert.equal(result.genuineSourceFactsMatched, true) assert.equal(result.platformProtectionVerified, false); assert.equal(result.generationAuthenticated, false); assert.equal(result.allWriterDrainAuthenticated, false); assert.equal(result.readyAuthorized, false) assert.equal(result.ordinal, 1) for (const name of await readdir(f.pin.registryDirectory)) assert(!(await readFile(path.join(f.pin.registryDirectory, name), "utf8")).includes("PRIVATE KEY")) })) test("runtime registry read never enrolls absent trusted state or creates any files", () => own(async root => { const f = await fixture(root), missing = path.join(root, "not-provisioned") await assert.rejects(readDatabaseSourceBindingRegistry({ ...f.pin, registryDirectory: missing }), refused) await assert.rejects(readdir(missing)); assert.deepEqual((await readdir(root)).sort(), ["registry-one", "synthetic-private.pem"]) })) test("runtime-supplied envelope/unknown trust configuration fields refuse", () => own(async root => { const f = await fixture(root) assert.throws(() => createDatabaseSourceBindingVerifier({ ...f.pin, body: f.request } as typeof f.pin)) await assert.rejects(readDatabaseSourceBindingRegistry(f.request as unknown as typeof f.pin), refused) })) test("JSON/copies and other SQL facade cannot forge the existing private source observation capability", () => own(async root => { const f = await fixture(root) for (const observation of [structuredClone(f.observation), JSON.parse(JSON.stringify(f.observation)), { ...f.observation }]) await assert.rejects(f.verifier.verify(f.sql, observation, options()), refused) await assert.rejects(f.verifier.verify(facade(), f.observation, options()), refused) })) test("logical clone/dump source with different database OID or cluster identifier refuses even with valid signed old binding", () => own(async root => { const f = await fixture(root) for (const changes of [{ database_oid: "16385" }, { system_identifier: "18446744073709551614" }, { database_name: "dump_clone" }]) { const sql = facade(async (_count, value) => { Object.assign(value, changes) }), observation = await captureDatabaseSourceObservation(sql, options()) await assert.rejects(f.verifier.verify(sql, observation, options()), refused) } })) test("genuine same-database observation with role/version drift refuses signed source comparison", () => own(async root => { const f = await fixture(root) for (const changes of [{ current_user: "other_operator" }, { server_version_num: "180007" }]) { const sql = facade(async (_count, value) => { Object.assign(value, changes) }), observation = await captureDatabaseSourceObservation(sql, options()) await assert.rejects(f.verifier.verify(sql, observation, options()), refused) } })) test("attacker-generated self-signed registry cannot replace independently pinned public key", () => own(async root => { const f = await fixture(root), attacker = generateKeyPairSync("ed25519") await writeFile(path.join(f.pin.registryDirectory, "operator-public.pem"), attacker.publicKey.export({ type: "spki", format: "pem" })) await assert.rejects(f.verifier.verify(f.sql, f.observation, options()), refused) })) test("missing current head cannot fall back to older filenames or unsigned caller JSON", () => own(async root => { const f = await fixture(root) await rm(f.headPath) await writeFile(path.join(f.pin.registryDirectory, "current.json"), JSON.stringify(f.request)) await assert.rejects(f.verifier.verify(f.sql, f.observation, options()), refused) })) test("current head hash and strict canonical bytes reject tamper, duplicate keys and oversized files", () => own(async root => { const f = await fixture(root), original = await readFile(f.headPath) for (const bytes of [Buffer.from("{}\n"), Buffer.from('{"body":{},"body":{},"signature":"x"}\n'), Buffer.alloc(8193, 32), Buffer.concat([original, Buffer.from(" ")])]) { await writeFile(f.headPath, bytes); await assert.rejects(f.verifier.verify(f.sql, f.observation, options()), refused) } })) test("binding tamper refused before any generation/evidence result", () => own(async root => { const f = await fixture(root), value = JSON.parse(await readFile(f.bindingPath, "utf8")) value.body.generation = randomUUID(); await writeFile(f.bindingPath, sourceBindingBytes(value)) await assert.rejects(f.verifier.verify(f.sql, f.observation, options()), refused) })) test("valid signature under the wrong domain refuses despite a matching externally pinned head digest", () => own(async root => { const f = await fixture(root), value = JSON.parse(await readFile(f.headPath, "utf8")) value.signature = sign(null, Buffer.from(DATABASE_SOURCE_SIGNATURE_DOMAINS.binding + sourceBindingCanonical(value.body)), f.key.privateKey).toString("base64url") const bytes = sourceBindingBytes(value), digest = sourceBindingSha256(bytes) await writeFile(path.join(f.pin.registryDirectory, "head-" + digest + ".json"), bytes) await assert.rejects(readDatabaseSourceBindingRegistry({ ...f.pin, currentHeadSha256: digest }), refused) })) test("binding signature itself is verified even when a genuine signed head authorizes its exact digest", () => own(async root => { const f = await fixture(root), signedBinding = JSON.parse(await readFile(f.bindingPath, "utf8")), head = JSON.parse(await readFile(f.headPath, "utf8")) const attacker = generateKeyPairSync("ed25519") signedBinding.signature = sign(null, Buffer.from(DATABASE_SOURCE_SIGNATURE_DOMAINS.binding + sourceBindingCanonical(signedBinding.body)), attacker.privateKey).toString("base64url") const bindingBytes = sourceBindingBytes(signedBinding), bindingHash = sourceBindingSha256(bindingBytes) head.body.bindingSha256 = bindingHash head.signature = sign(null, Buffer.from(DATABASE_SOURCE_SIGNATURE_DOMAINS.head + sourceBindingCanonical(head.body)), f.key.privateKey).toString("base64url") const headBytes = sourceBindingBytes(head), headHash = sourceBindingSha256(headBytes) await writeFile(path.join(f.pin.registryDirectory, "binding-" + bindingHash + ".json"), bindingBytes) await writeFile(path.join(f.pin.registryDirectory, "head-" + headHash + ".json"), headBytes) await assert.rejects(readDatabaseSourceBindingRegistry({ ...f.pin, currentHeadSha256: headHash }), refused) })) test("even valid operator signatures cannot authorize unknown binding fields or caller READY claims", () => own(async root => { const f = await fixture(root), signedBinding = JSON.parse(await readFile(f.bindingPath, "utf8")), head = JSON.parse(await readFile(f.headPath, "utf8")) signedBinding.body.readyAuthorized = true signedBinding.signature = sign(null, Buffer.from(DATABASE_SOURCE_SIGNATURE_DOMAINS.binding + sourceBindingCanonical(signedBinding.body)), f.key.privateKey).toString("base64url") const bindingBytes = sourceBindingBytes(signedBinding), bindingHash = sourceBindingSha256(bindingBytes) head.body.bindingSha256 = bindingHash head.signature = sign(null, Buffer.from(DATABASE_SOURCE_SIGNATURE_DOMAINS.head + sourceBindingCanonical(head.body)), f.key.privateKey).toString("base64url") const headBytes = sourceBindingBytes(head), headHash = sourceBindingSha256(headBytes) await writeFile(path.join(f.pin.registryDirectory, "binding-" + bindingHash + ".json"), bindingBytes) await writeFile(path.join(f.pin.registryDirectory, "head-" + headHash + ".json"), headBytes) await assert.rejects(readDatabaseSourceBindingRegistry({ ...f.pin, currentHeadSha256: headHash }), refused) })) test("operator explicit next generation increments ordinal, binds previous pinned head and refuses same generation/reuse", () => own(async root => { const f = await fixture(root) const next = await provisionDatabaseSourceBindingOffline({ request: { ...f.request, generation: randomUUID() }, privateKeyFile: f.privateKeyFile, outputDirectory: path.join(root, "registry-two"), previousPin: f.pin }) const verified = await readDatabaseSourceBindingRegistry(next.deploymentPin) assert.equal(verified.body.ordinal, 2); assert.equal(verified.head.previousHeadSha256, f.pin.currentHeadSha256) await assert.rejects(provisionDatabaseSourceBindingOffline({ request: f.request, privateKeyFile: f.privateKeyFile, outputDirectory: path.join(root, "bad"), previousPin: f.pin })) await assert.rejects(provisionDatabaseSourceBindingOffline({ request: f.request, privateKeyFile: f.privateKeyFile, outputDirectory: f.pin.registryDirectory })) })) test("old genuine operator-signed head or binding substituted into current registry refuses rollback under the current independent pin", () => own(async root => { const f = await fixture(root), next = await provisionDatabaseSourceBindingOffline({ request: { ...f.request, generation: randomUUID() }, privateKeyFile: f.privateKeyFile, outputDirectory: path.join(root, "registry-two"), previousPin: f.pin }) const oldHead = await readFile(f.headPath), newHead = path.join(next.deploymentPin.registryDirectory, "head-" + next.deploymentPin.currentHeadSha256 + ".json") await writeFile(newHead, oldHead) await assert.rejects(readDatabaseSourceBindingRegistry(next.deploymentPin), refused) })) test("registry replacement during genuine source recheck is refused by second fixed artifact read", () => own(async root => { const f = await fixture(root), sql = facade(async count => { if (count === 4) await writeFile(f.headPath, "{}\n") }) const observation = await captureDatabaseSourceObservation(sql, options()) await assert.rejects(f.verifier.verify(sql, observation, options()), refused) })) test("abort/expired request refuses without reading any SQL facade", () => own(async root => { const f = await fixture(root), controller = new AbortController(); controller.abort() await assert.rejects(f.verifier.verify(f.sql, f.observation, { deadlineAt: Date.now() - 1 }), refused) await assert.rejects(f.verifier.verify(f.sql, f.observation, { ...options(), signal: controller.signal }), refused) })) test("offline CLI uses explicit bounded files, rejects unknown/duplicate args and never auto-installs deployment config", () => own(async root => { const f = await fixture(root), requestPath = path.join(root, "request.json") await writeFile(requestPath, JSON.stringify({ ...f.request, generation: randomUUID() })) const previous = path.join(root, "previous.json"); await writeFile(previous, JSON.stringify(f.pin)) const issued = await databaseSourceBindingOperatorCli(["--request=" + requestPath, "--private-key=" + f.privateKeyFile, "--output=" + path.join(root, "cli-output"), "--previous-pin=" + previous]) assert.equal((await readDatabaseSourceBindingRegistry(issued.deploymentPin)).body.ordinal, 2) await assert.rejects(databaseSourceBindingOperatorCli(["--runtime-self-enroll=true"])) await assert.rejects(databaseSourceBindingOperatorCli(["--output=x", "--output=y"])) assert.equal(issued.keyIsolationVerified, false); assert.equal(issued.readyAuthorized, false) })) test("private key material is never accepted as the runtime public artifact", () => own(async root => { const f = await fixture(root); await writeFile(path.join(f.pin.registryDirectory, "operator-public.pem"), await readFile(f.privateKeyFile)) await assert.rejects(f.verifier.verify(f.sql, f.observation, options()), refused) })) test("honest indistinguishability boundary: same metadata after same-database restore is signature evidence only, never generation authentication", () => own(async root => { const f = await fixture(root), result = await f.verifier.verify(f.sql, f.observation, options()) assert.equal(result.generationAuthenticated, false); assert.equal(result.platformProtectionVerified, false); assert.equal(result.readyAuthorized, false) }))