157 lines
13 KiB
TypeScript
157 lines
13 KiB
TypeScript
/** Component cryptographic/history verification; these bundles model locked
|
|
* SQL row shapes, not execution authority or actual PostgreSQL acceptance. */
|
|
import assert from "node:assert/strict"
|
|
import { createHmac } from "node:crypto"
|
|
import { test } from "node:test"
|
|
import { verifyServerPollHistoryForTests, ServerPollHistoryInvalid, type ServerPollHistoryRows } from "./server-poll-history-verification.js"
|
|
import { encodeServerPollJournalAnchor } from "./server-poll-journal-anchor.js"
|
|
import { validateServerPollJournalReceipt } from "./server-poll-journal-validation.js"
|
|
import type { ServerPollJournalContext } from "./server-poll-journal.js"
|
|
import type { ServerPollReceipt } from "./server-poll-execution.js"
|
|
|
|
const canonical = (value: unknown): string => value && typeof value === "object" ? Array.isArray(value) ? "[" + value.map(canonical).join(",") + "]"
|
|
: "{" + Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => JSON.stringify(key) + ":" + canonical(item)).join(",") + "}" : JSON.stringify(value)
|
|
const mac = (domain: string, value: unknown) => createHmac("sha256", "component-secret:" + domain).update(canonical(value)).digest("hex")
|
|
const executionProof = async (value: unknown) => mac("execution", value)
|
|
const crypto = { decrypt: async (text: string) => Buffer.from(text, "base64").toString(), proof: async (domain: string, value: unknown) => mac("journal:" + domain, value) }
|
|
const encrypt = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64")
|
|
const id = "11111111-1111-4111-8111-111111111111", operation = "22222222-2222-4222-8222-222222222222"
|
|
const hash = "a".repeat(64)
|
|
|
|
async function fixture(kind: "mcp" | "rest" = "rest", version: 1 | 2 | 3 = 1) {
|
|
const context: ServerPollJournalContext = { identity: kind === "rest"
|
|
? { kind, ownerId: "owned-history", executionId: operation, issuedAt: 0, expiresAt: 6000, requestId: "accepted-request", authentication: "jwt" }
|
|
: { kind, ownerId: "owned-history", executionId: operation, issuedAt: 0, expiresAt: 6000, connectionId: "33333333-3333-4333-8333-333333333333", credentialId: "44444444-4444-4444-8444-444444444444", operationName: "servers.poll" },
|
|
plan: { version, ...(version === 3 ? { approvalProof: "b".repeat(64) } : {}), requiresHuman: true, scope: "global", request: { serverId: 1, receiptId: id }, around: new Date(1000).toISOString(), beforeProof: hash, authorityProof: hash, bindingProof: hash,
|
|
maintenance: [{ kind: "partition.drop", parent: "flow_buckets", name: "flow_buckets_d_20000101" }], affectedServerIds: [1, 2], mutationCost: 9 } }
|
|
const { bindingProof: _binding, ...core } = context.plan; context.plan.bindingProof = await executionProof(core)
|
|
const start = version === 3 ? "c".repeat(64) : hash
|
|
const anchorText = () => encodeServerPollJournalAnchor(context, version === 3 ? { fullProof: start, approvalProof: context.plan.approvalProof! } : undefined, crypto)
|
|
const rows: ServerPollHistoryRows = { execution: { receipt_id: id, identity_kind: kind, execution_id: operation, binding_proof: context.plan.bindingProof, context_ciphertext: Buffer.from(await anchorText()).toString("base64"), context_proof: await crypto.proof("context", context), created_at: new Date(1000) },
|
|
intents: [], acks: [], receipt: {}, quarantines: [] }
|
|
let chain = start
|
|
for (const stage of ["native.identity", "native.resource", "native.interfaces", "native.addresses", "publish.0", "publish.1", "publish.2"]) {
|
|
const before = stage.startsWith("native.") ? start : chain
|
|
const effect = stage === "publish.2" ? await executionProof(context.plan.maintenance[0]) : await executionProof({ stage, source: "private-native-payload-not-persisted" })
|
|
const result = await executionProof({ stage, complete: true })
|
|
const startAt = stage.startsWith("native.") ? 1100 : 1300 + Number(stage.slice(8)) * 200
|
|
rows.intents.push({ receipt_id: id, stage, before_proof: before, effect_proof: effect, intent_proof: await crypto.proof("intent", { receiptId: id, stage, beforeProof: before, effectProof: effect }), created_at: new Date(startAt) })
|
|
rows.acks.push({ receipt_id: id, stage, result_proof: result, outcome: "confirmed", ack_proof: await crypto.proof("ack", { receiptId: id, stage, resultProof: result, outcome: "confirmed" }), created_at: new Date(startAt + 100) })
|
|
if (stage.startsWith("publish.")) chain = result
|
|
}
|
|
const receipt: ServerPollReceipt = { receiptId: id, configurationVerified: true, complete: true, maintenanceComplete: true, nativeReads: 4, confirmedPublications: 3, completedPublications: 3, afterProof: chain,
|
|
observation: "online", snapshot: { id: 91, serverId: 1, status: "online", polledAt: new Date(1100).toISOString() } }
|
|
rows.receipt = { receipt_id: id, receipt_ciphertext: encrypt(receipt), receipt_proof: await crypto.proof("receipt", JSON.stringify(receipt)), created_at: new Date(1900) }
|
|
const resealContext = async () => { rows.execution.context_ciphertext = Buffer.from(await anchorText()).toString("base64"); rows.execution.context_proof = await crypto.proof("context", context) }
|
|
const resealReceipt = async () => { rows.receipt.receipt_ciphertext = encrypt(receipt); rows.receipt.receipt_proof = await crypto.proof("receipt", JSON.stringify(receipt)) }
|
|
const reack = async (index: number) => { const ack = rows.acks[index]; ack.ack_proof = await crypto.proof("ack", { receiptId: ack.receipt_id, stage: ack.stage, resultProof: ack.result_proof, outcome: ack.outcome }) }
|
|
const reintent = async (index: number) => { const intent = rows.intents[index]; intent.intent_proof = await crypto.proof("intent", { receiptId: intent.receipt_id, stage: intent.stage, beforeProof: intent.before_proof, effectProof: intent.effect_proof }) }
|
|
return { rows, context, receipt, start, resealContext, resealReceipt, reack, reintent, verify: () => verifyServerPollHistoryForTests(rows, { crypto, executionProof }) }
|
|
}
|
|
|
|
for (const kind of ["rest", "mcp"] as const) test(`${kind}: v3 expired history authenticates a distinct fresh start without changing the original context proof`, async () => {
|
|
const f = await fixture(kind, 3), result = await f.verify()
|
|
assert.equal(result.context.plan.version, 3)
|
|
assert.notEqual(f.start, f.context.plan.beforeProof)
|
|
assert.equal(f.rows.execution.context_proof, await crypto.proof("context", f.context))
|
|
})
|
|
test("v2 historical payload remains exactly the original context", async () => {
|
|
const f = await fixture("rest", 2); await f.verify()
|
|
assert.deepEqual(JSON.parse(await crypto.decrypt(String(f.rows.execution.context_ciphertext))), f.context)
|
|
})
|
|
test("v3 missing, replaced or cross-context start seal refuses even with otherwise authentic stages", async () => {
|
|
for (const change of ["missing", "proof", "full", "approval", "identity", "extra"]) {
|
|
const f = await fixture("rest", 3)
|
|
const payload = JSON.parse(await crypto.decrypt(String(f.rows.execution.context_ciphertext)))
|
|
if (change === "missing") delete payload.executionStart
|
|
if (change === "proof") payload.executionStart.proof = "d".repeat(64)
|
|
if (change === "full") payload.executionStart.fullProof = f.context.plan.beforeProof
|
|
if (change === "approval") payload.executionStart.approvalProof = "d".repeat(64)
|
|
if (change === "identity") payload.identity.ownerId = "another-owner"
|
|
if (change === "extra") payload.executionStart.unknown = true
|
|
f.rows.execution.context_ciphertext = encrypt(payload)
|
|
await assert.rejects(f.verify(), ServerPollHistoryInvalid)
|
|
}
|
|
})
|
|
test("v3 native chain cannot fall back to prepared proof even with valid stage MACs", async () => {
|
|
const f = await fixture("rest", 3)
|
|
for (let index = 0; index < 4; index++) { f.rows.intents[index].before_proof = f.context.plan.beforeProof; await f.reintent(index) }
|
|
await assert.rejects(f.verify(), ServerPollHistoryInvalid)
|
|
})
|
|
|
|
for (const kind of ["rest", "mcp"] as const) test(`${kind}: authentic expired history verifies without authorizing an old grant or creating capabilities`, async () => {
|
|
const f = await fixture(kind), result = await f.verify()
|
|
assert(f.context.identity.expiresAt < Date.now())
|
|
assert.deepEqual(result.context, f.context); assert.deepEqual(result.receipt, f.receipt)
|
|
assert.deepEqual(result.source, { createdAt: new Date(1000).toISOString(), completedAt: new Date(1900).toISOString(), stageCount: 7, publications: 3,
|
|
nativeOutcomes: f.rows.acks.slice(0, 4).map(row => ({ stage: row.stage, outcome: row.outcome, resultProof: row.result_proof })) })
|
|
assert.deepEqual(Object.keys(result).sort(), ["context", "receipt", "source"])
|
|
})
|
|
|
|
test("each stored context, intent, ACK and receipt authenticator is independently required", async () => {
|
|
for (const mutate of [
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.execution.context_proof = hash },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.intents[0].intent_proof = hash },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.acks[0].ack_proof = hash },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.receipt.receipt_proof = hash },
|
|
]) { const f = await fixture(); mutate(f); await assert.rejects(f.verify(), ServerPollHistoryInvalid) }
|
|
})
|
|
|
|
test("authenticated context does not replace original plan core binding", async () => {
|
|
const f = await fixture(); f.context.plan.maintenance[0] = { kind: "partition.drop", parent: "flow_buckets", name: "flow_buckets_d_20990101" }
|
|
await f.resealContext(); await assert.rejects(f.verify(), ServerPollHistoryInvalid)
|
|
})
|
|
|
|
test("cross-receipt/execution rows, duplicates, orphan ACK and strange stages cannot hide in a join", async () => {
|
|
for (const mutate of [
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.execution.execution_id = id },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.intents[0].receipt_id = operation },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.acks[0].receipt_id = operation },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.receipt.receipt_id = operation },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.intents[1] = structuredClone(f.rows.intents[0]) },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.acks[1] = structuredClone(f.rows.acks[0]) },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.acks[0].stage = "native.orphan" },
|
|
(f: Awaited<ReturnType<typeof fixture>>) => { f.rows.intents[0].stage = "publish.00" },
|
|
]) { const f = await fixture(); mutate(f); await assert.rejects(f.verify(), ServerPollHistoryInvalid) }
|
|
})
|
|
|
|
test("missing native ACK or quarantine refuses complete history", async () => {
|
|
const missing = await fixture(); missing.rows.acks.shift(); await assert.rejects(missing.verify(), ServerPollHistoryInvalid)
|
|
const quarantined = await fixture(); quarantined.rows.quarantines.push({ receipt_id: id }); await assert.rejects(quarantined.verify(), ServerPollHistoryInvalid)
|
|
})
|
|
|
|
test("valid stage MACs cannot replace publication chaining or the exact maintenance effect", async () => {
|
|
const chain = await fixture(); chain.rows.intents[5].before_proof = hash; await chain.reintent(5)
|
|
await assert.rejects(chain.verify(), ServerPollHistoryInvalid)
|
|
const maintenance = await fixture(); maintenance.rows.intents[6].effect_proof = hash; await maintenance.reintent(6)
|
|
await assert.rejects(maintenance.verify(), ServerPollHistoryInvalid)
|
|
})
|
|
|
|
test("online requires all confirmed native outcomes; offline read-failed requires the genuine unavailable proof", async () => {
|
|
const f = await fixture(); f.rows.acks[0].outcome = "read-failed"; f.rows.acks[0].result_proof = await executionProof({ unavailable: true }); await f.reack(0)
|
|
await assert.rejects(f.verify(), ServerPollHistoryInvalid)
|
|
f.receipt.observation = "offline"; f.receipt.snapshot.status = "offline"; await f.resealReceipt()
|
|
assert.equal((await f.verify()).receipt.observation, "offline", "Historical authentication is distinct from online-only compaction eligibility")
|
|
f.rows.acks[0].result_proof = hash; await f.reack(0); await assert.rejects(f.verify(), ServerPollHistoryInvalid)
|
|
})
|
|
|
|
test("source timestamps, row/ciphertext bounds, exact context and receipt shapes refuse", async () => {
|
|
for (const mutate of [
|
|
async (f: Awaited<ReturnType<typeof fixture>>) => { f.rows.acks[0].created_at = new Date(2000) },
|
|
async (f: Awaited<ReturnType<typeof fixture>>) => { f.rows.intents[4].created_at = new Date(1150) },
|
|
async (f: Awaited<ReturnType<typeof fixture>>) => { f.rows.intents[5].created_at = new Date(1350) },
|
|
async (f: Awaited<ReturnType<typeof fixture>>) => { f.rows.execution.context_ciphertext = "x".repeat(2097153) },
|
|
async (f: Awaited<ReturnType<typeof fixture>>) => { f.rows.intents = Array(2011).fill(f.rows.intents[0]) },
|
|
async (f: Awaited<ReturnType<typeof fixture>>) => { f.receipt.snapshot.rawInterfaces = []; await f.resealReceipt() },
|
|
async (f: Awaited<ReturnType<typeof fixture>>) => { (f.context as unknown as Record<string, unknown>).authority = true; await f.resealContext() },
|
|
]) { const f = await fixture(); await mutate(f); await assert.rejects(f.verify(), ServerPollHistoryInvalid) }
|
|
})
|
|
|
|
test("common receipt validator retains original completion flags and maintenance counts", async () => {
|
|
const f = await fixture()
|
|
const stages = f.rows.intents.map(intent => ({ ...intent, ...f.rows.acks.find(ack => ack.stage === intent.stage) })) as Parameters<typeof validateServerPollJournalReceipt>[2]
|
|
validateServerPollJournalReceipt(f.context.plan, f.receipt, stages)
|
|
for (const patch of [{ complete: false }, { nativeReads: 3 }, { completedPublications: 2 }, { afterProof: hash }])
|
|
assert.throws(() => validateServerPollJournalReceipt(f.context.plan, { ...f.receipt, ...patch }, stages))
|
|
})
|