221 lines
17 KiB
TypeScript
221 lines
17 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID } from "node:crypto"
|
|
import { test } from "node:test"
|
|
import { encodeServerPollJournalAnchor } from "./server-poll-journal-anchor.js"
|
|
import { publicationLayout, serverPollMaintenancePublications } from "./server-poll-maintenance-groups.js"
|
|
import type { ServerPollEffect } from "./server-poll-execution-model.js"
|
|
import { fingerprint, redact } from "../modules/mcp/security.js"
|
|
import { verifyServerPollHistoryForTests } from "./server-poll-history-verification.js"
|
|
import { verifyServerPollTerminalSourceForTests, type ServerPollTerminalSourceRows, ServerPollTerminalSourceInvalid } from "./server-poll-terminal-source.js"
|
|
|
|
async function fixture(version:1|2|3|4=1) {
|
|
const key = randomBytes(32), base = Date.now() - 600000, stamp = (offset: number) => new Date(base + offset).toISOString()
|
|
const proof = async (domain: string, value: unknown) => createHmac("sha256", key).update(domain).update(fingerprint(value)).digest("hex")
|
|
const encrypt = (text: string) => {
|
|
const nonce = randomBytes(12), cipher = createCipheriv("aes-256-gcm", key, nonce)
|
|
const bytes = Buffer.concat([cipher.update(text, "utf8"), cipher.final()])
|
|
return Buffer.concat([nonce, cipher.getAuthTag(), bytes]).toString("base64")
|
|
}
|
|
const decrypt = async (text: string) => {
|
|
const bytes = Buffer.from(text, "base64"), cipher = createDecipheriv("aes-256-gcm", key, bytes.subarray(0, 12))
|
|
cipher.setAuthTag(bytes.subarray(12, 28)); return Buffer.concat([cipher.update(bytes.subarray(28)), cipher.final()]).toString("utf8")
|
|
}
|
|
const crypto = { decrypt, proof }, id = randomUUID(), receiptId = randomUUID(), connectionId = randomUUID(), planId = randomUUID(), credentialId = randomUUID()
|
|
const principal = { connectionId, credentialId, credentialExpiresAt: stamp(240000) }
|
|
const maintenance:ServerPollEffect[]=version===4?Array.from({length:17},(_,index)=>({kind:"partition.drop",parent:"server_snapshots",name:"server_snapshots_w_"+new Date(Date.UTC(2000,0,3+index*7)).toISOString().slice(0,10).replaceAll("-","")})):[]
|
|
const epochPlan=version===3||version===4
|
|
const core = { version, ...(epochPlan?{approvalProof:"9".repeat(64)}:{}),...(version===4?{maintenanceGroupSize:8}:{}), requiresHuman: true as const, scope: "global" as const, request: { serverId: 1, receiptId }, around: stamp(0),
|
|
beforeProof: "a".repeat(64), authorityProof: "b".repeat(64), maintenance, affectedServerIds: [1], mutationCost: maintenance.length+8 }
|
|
const plan = { ...core, bindingProof: await proof("server-poll-production-v1", core) }
|
|
const context = { identity: { kind: "mcp" as const, ownerId: "original-owner", executionId: id, connectionId, credentialId, operationName: "servers.poll", issuedAt: base, expiresAt: base + 180000 }, plan }
|
|
const contextProof = await proof("server-poll-journal-v1:context", context)
|
|
const firstProof=epochPlan?"d".repeat(64):plan.beforeProof
|
|
const anchorText=await encodeServerPollJournalAnchor(context,epochPlan?{fullProof:firstProof,approvalProof:plan.approvalProof!}:undefined,{proof:(domain,value)=>proof("server-poll-journal-v1:"+domain,value)})
|
|
const snapshot = { id: 42, serverId: 1, polledAt: stamp(1000), status: "online" as const, latencyMs: 0,
|
|
rosVersion: null, boardName: null, uptime: null, cpuLoad: null, freeMemory: null, totalMemory: null, identityName: null }
|
|
const effects=serverPollMaintenancePublications(plan),count=effects.length+2
|
|
const receipt = { receiptId, configurationVerified: true as const, complete: true as const, maintenanceComplete: true as const,
|
|
nativeReads: 4 as const, confirmedPublications: count, completedPublications: count, afterProof: "f".repeat(64), observation: "online" as const, snapshot }
|
|
const receiptText = JSON.stringify(receipt), stages = ["native.identity", "native.resource", "native.interfaces", "native.addresses", ...Array.from({length:count},(_,index)=>"publish."+index)]
|
|
const intents = [], acks = []
|
|
for (let index = 0; index < stages.length; index++) {
|
|
const stage = stages[index], beforeProof = index > 4 ? "e".repeat(64) : firstProof
|
|
const intent = { receiptId, stage, beforeProof, effectProof: index>=6?await proof("server-poll-production-v1",effects[index-6]):"c".repeat(64) }
|
|
const ack = { receiptId, stage, resultProof: index === stages.length-1 ? receipt.afterProof : "e".repeat(64), outcome: "confirmed" as const }
|
|
intents.push({ receipt_id: receiptId, stage, before_proof: beforeProof, effect_proof: intent.effectProof,
|
|
intent_proof: await proof("server-poll-journal-v1:intent", intent), created_at: stamp(500 + index * 100) })
|
|
acks.push({ receipt_id: receiptId, stage, result_proof: ack.resultProof, outcome: ack.outcome,
|
|
ack_proof: await proof("server-poll-journal-v1:ack", ack), created_at: stamp(550 + index * 100) })
|
|
}
|
|
const binding = { version: 1, operation: "servers.poll", principal, ownerId: context.identity.ownerId, issuedAt: base, expiresAt: base + 180000, plan }
|
|
const input = { serverId: 1, receiptId, inputDigest: await proof("server-poll-mcp-binding-v1", binding), bindingCiphertext: encrypt(JSON.stringify(binding)) }
|
|
const step = { kind: "service", service: "servers.poll", input }
|
|
const evidence = { target: { scope: "global" }, objects: [{ kind: "server", id: "1", serverId: 1 }], snapshots: [], steps: [step], before: { proof: plan.beforeProof },
|
|
mutationCost: plan.mutationCost, requiresHuman: true, verificationScope: "configuration", validUntil: stamp(180000),
|
|
warnings: ["Полный опрос читает устройство и изменяет общие снимки и разделы истории; требуется подтверждение человеком. Автоматический повтор запрещён."] }
|
|
const raw: ServerPollTerminalSourceRows = {
|
|
admission: { receipt_id: receiptId, identity_kind: "mcp", execution_id: id, connection_id: connectionId, owner_id: context.identity.ownerId,
|
|
storage_state: "full", compact_at: null, archive_bytes: null, original_activity_at: null,
|
|
binding_proof: plan.bindingProof, context_proof: contextProof, authority_issued_at: stamp(0), authority_expires_at: stamp(180000),
|
|
max_stages: publicationLayout(plan).journalMaxStages, claim_token: null, claim_attempted_at: stamp(300), created_at: stamp(200), retention_days: 14, safety_ms: 60000,
|
|
gc_not_before: stamp(180000 + 14 * 86400000 + 60000), used_rows: 2*stages.length+2, used_bytes: 4000 },
|
|
journal: { execution: { receipt_id: receiptId, identity_kind: "mcp", execution_id: id, binding_proof: plan.bindingProof,
|
|
context_ciphertext: encrypt(anchorText), context_proof: contextProof, created_at: stamp(400) }, intents, acks,
|
|
receipt: { receipt_id: receiptId, receipt_ciphertext: encrypt(receiptText), receipt_proof: await proof("server-poll-journal-v1:receipt", receiptText), created_at: stamp(1400) }, quarantines: [] },
|
|
terminal: {
|
|
operation: { id, plan_id: planId, connection_id: connectionId, state: "applied", verification: "passed", error_code: null,
|
|
result: { confirmedWrites: 1, verificationScope: "configuration" }, created_at: stamp(100), finished_at: stamp(1600) },
|
|
plan: { id: planId, connection_id: connectionId, operation_id: "servers.poll", operation_version: 1, state: "completed", created_at: stamp(25), approved_by: "human-owner", approved_at: stamp(50),
|
|
expires_at: stamp(190000), evidence: { sealed: encrypt(JSON.stringify(evidence)) }, payload: { sealed: encrypt(JSON.stringify({ serverId: 1 })) } },
|
|
step: { operation_id: id, step_index: 0, server_id: null, state: "verified", intended_state: redact(step), finished_at: stamp(1500),
|
|
result: { operationId: id, receiptId, nativeReads: 4, confirmedPublications: count, completedPublications: count, complete: true, maintenanceComplete: true,
|
|
configurationVerified: true, automaticReplay: false, snapshot } },
|
|
},
|
|
}
|
|
const history = await verifyServerPollHistoryForTests(raw.journal, { crypto: { decrypt, proof: (domain, value) => proof("server-poll-journal-v1:" + domain, value) },
|
|
executionProof: value => proof("server-poll-production-v1", value) })
|
|
const now = base + 600000
|
|
const run = () => verifyServerPollTerminalSourceForTests(raw, history, now, crypto)
|
|
return { raw, history, crypto, now, run, encrypt, decrypt, proof, binding, evidence, input, stamp }
|
|
}
|
|
|
|
for(const version of [2,3,4] as const)test(`v${version}: expired original source and exact original plan retain terminal eligibility`,async()=>{
|
|
const f=await fixture(version),result=await f.run()
|
|
assert.equal(result.receiptId,f.raw.admission.receipt_id)
|
|
assert.equal(f.history.context.plan.version,version)
|
|
if(version===3||version===4){
|
|
const payload=JSON.parse(await f.decrypt(String(f.raw.journal.execution.context_ciphertext)))
|
|
assert.notEqual(payload.executionStart.fullProof,f.history.context.plan.beforeProof)
|
|
assert.equal(f.raw.admission.context_proof,await f.proof("server-poll-journal-v1:context",f.history.context))
|
|
}
|
|
})
|
|
for(const version of [3,4] as const)test(`v${version} terminal source refuses missing/replaced start independently of the supplied authenticated history`,async()=>{
|
|
for(const change of ["missing","proof","full","extra"]){
|
|
const f=await fixture(version),payload=JSON.parse(await f.decrypt(String(f.raw.journal.execution.context_ciphertext)))
|
|
if(change==="missing")delete payload.executionStart
|
|
if(change==="proof")payload.executionStart.proof="0".repeat(64)
|
|
if(change==="full")payload.executionStart.fullProof=f.history.context.plan.beforeProof
|
|
if(change==="extra")payload.executionStart.extra=true
|
|
f.raw.journal.execution.context_ciphertext=f.encrypt(JSON.stringify(payload))
|
|
await assert.rejects(f.run(),ServerPollTerminalSourceInvalid)
|
|
}
|
|
})
|
|
|
|
test("v4 terminal retains full mutation cost separately from the grouped stage budget",async()=>{
|
|
const f=await fixture(4)
|
|
assert.equal(f.history.context.plan.mutationCost,25);assert.equal(f.raw.admission.max_stages,11)
|
|
await f.run()
|
|
f.raw.admission.max_stages=25
|
|
await assert.rejects(f.run(),ServerPollTerminalSourceInvalid)
|
|
})
|
|
|
|
test("expired original credentials need no live renewal: authenticated history and exact terminal return only fixed metadata", async () => {
|
|
const f = await fixture(), result = await f.run()
|
|
assert(f.now > Date.parse(f.binding.principal.credentialExpiresAt))
|
|
assert.equal(result.originalActivityAt, f.raw.terminal.plan.expires_at)
|
|
assert.equal(result.originalExpiresAt, f.raw.admission.authority_expires_at)
|
|
assert.equal(result.receiptId, f.raw.admission.receipt_id); assert.equal(result.ownerId, "original-owner")
|
|
assert.equal(result.retentionDays, 14); assert.equal(result.safetyMs, 60000)
|
|
assert.match(result.terminalDigest, /^[a-f0-9]{64}$/); assert(Object.isFrozen(result))
|
|
assert(!JSON.stringify(result).includes("bindingCiphertext")); assert(!("capability" in result))
|
|
assert.deepEqual(await f.run(), result)
|
|
})
|
|
|
|
for (const fault of ["rest", "unknown", "partial", "unverified", "unapproved", "version", "connection", "owner", "claim", "intent", "result", "operation-result", "quarantine", "native-failure", "rows", "context", "receipt", "binding-mac", "payload", "evidence", "time-order"] as const)
|
|
test("terminal source refuses " + fault + " without granting credit", async () => {
|
|
const f = await fixture(), { raw } = f
|
|
if (fault === "rest") raw.admission.identity_kind = "rest"
|
|
if (fault === "unknown" || fault === "partial") raw.terminal.operation.state = fault
|
|
if (fault === "unverified") raw.terminal.step.state = "applied"
|
|
if (fault === "unapproved") raw.terminal.plan.approved_by = null
|
|
if (fault === "version") raw.terminal.plan.operation_version = 2
|
|
if (fault === "connection") raw.terminal.operation.connection_id = randomUUID()
|
|
if (fault === "owner") raw.admission.owner_id = "other"
|
|
if (fault === "claim") raw.admission.claim_token = randomUUID()
|
|
if (fault === "intent") raw.terminal.step.intended_state = { service: "other" }
|
|
if (fault === "result") raw.terminal.step.result = { complete: true }
|
|
if (fault === "operation-result") raw.terminal.operation.result = { confirmedWrites: 1, verificationScope: "configuration", recovery: { state: "verified" } }
|
|
if (fault === "quarantine") raw.journal.quarantines.push({ receipt_id: raw.admission.receipt_id })
|
|
if (fault === "native-failure") f.history.source.nativeOutcomes[0].outcome = "read-failed"
|
|
if (fault === "rows") raw.admission.used_rows = 13
|
|
if (fault === "context") raw.journal.execution.context_proof = "0".repeat(64)
|
|
if (fault === "receipt") raw.journal.receipt.receipt_proof = "0".repeat(64)
|
|
if (fault === "binding-mac") {
|
|
f.input.inputDigest = "0".repeat(64)
|
|
raw.terminal.plan.evidence = { sealed: f.encrypt(JSON.stringify(f.evidence)) }
|
|
}
|
|
if (fault === "payload") raw.terminal.plan.payload = { sealed: f.encrypt(JSON.stringify({ serverId: 2 })) }
|
|
if (fault === "evidence") {
|
|
f.evidence.requiresHuman = false
|
|
raw.terminal.plan.evidence = { sealed: f.encrypt(JSON.stringify(f.evidence)) }
|
|
}
|
|
if (fault === "time-order") raw.terminal.operation.finished_at = f.stamp(1000)
|
|
await assert.rejects(f.run(), ServerPollTerminalSourceInvalid)
|
|
})
|
|
|
|
test("original deadline plus safety is strict; future activity cannot be compacted", async () => {
|
|
const f = await fixture(), deadline = Date.parse(String(f.raw.terminal.plan.expires_at)) + 60000
|
|
await assert.rejects(verifyServerPollTerminalSourceForTests(f.raw, f.history, deadline, f.crypto), ServerPollTerminalSourceInvalid)
|
|
await verifyServerPollTerminalSourceForTests(f.raw, f.history, deadline + 1, f.crypto)
|
|
f.raw.terminal.operation.finished_at = new Date(f.now + 1).toISOString()
|
|
await assert.rejects(f.run(), ServerPollTerminalSourceInvalid)
|
|
})
|
|
|
|
for (const fault of ["storage-unknown", "storage-compacted", "storage-missing", "compact-time", "compact-bytes", "compact-activity", "compact-undefined",
|
|
"missing-plan-created", "future-plan-created", "created-after-approval", "expired-before-approval", "expired-at-operation", "operation-at-original-expiry", "native-step-server", "missing-step-server", "late-ack", "late-receipt"] as const)
|
|
test("0041 terminal eligibility rejects " + fault, async () => {
|
|
const f = await fixture(), { raw } = f
|
|
if (fault === "storage-unknown") raw.admission.storage_state = "unknown"
|
|
if (fault === "storage-compacted") raw.admission.storage_state = "compacted"
|
|
if (fault === "storage-missing") delete raw.admission.storage_state
|
|
if (fault === "compact-time") raw.admission.compact_at = f.stamp(200000)
|
|
if (fault === "compact-bytes") raw.admission.archive_bytes = 100
|
|
if (fault === "compact-activity") raw.admission.original_activity_at = f.stamp(190000)
|
|
if (fault === "compact-undefined") raw.admission.compact_at = undefined
|
|
if (fault === "missing-plan-created") delete raw.terminal.plan.created_at
|
|
if (fault === "future-plan-created") raw.terminal.plan.created_at = new Date(f.now + 1).toISOString()
|
|
if (fault === "created-after-approval") raw.terminal.plan.created_at = f.stamp(51)
|
|
if (fault === "expired-before-approval") raw.terminal.plan.expires_at = f.stamp(49)
|
|
if (fault === "expired-at-operation") raw.terminal.plan.expires_at = raw.terminal.operation.created_at
|
|
if (fault === "operation-at-original-expiry") raw.terminal.operation.created_at = raw.admission.authority_expires_at
|
|
if (fault === "native-step-server") raw.terminal.step.server_id = 1
|
|
if (fault === "missing-step-server") delete raw.terminal.step.server_id
|
|
if (fault === "late-ack") raw.journal.acks.at(-1)!.created_at = raw.admission.authority_expires_at
|
|
if (fault === "late-receipt") raw.journal.receipt.created_at = raw.admission.authority_expires_at
|
|
await assert.rejects(f.run(), ServerPollTerminalSourceInvalid)
|
|
})
|
|
|
|
test("confirmed service work before original expiry permits delayed generic terminal SQL publication", async () => {
|
|
const f = await fixture()
|
|
f.raw.terminal.step.finished_at = f.stamp(181000)
|
|
f.raw.terminal.operation.finished_at = f.stamp(182000)
|
|
f.raw.terminal.plan.expires_at = f.stamp(179000)
|
|
const result = await f.run()
|
|
assert.equal(result.originalActivityAt, f.raw.terminal.operation.finished_at)
|
|
assert.equal(result.originalExpiresAt, f.raw.admission.authority_expires_at)
|
|
})
|
|
|
|
test("activity selection preserves original PostgreSQL microseconds", async () => {
|
|
const f = await fixture(), sourceTime = String(f.raw.terminal.plan.expires_at).replace(/\.(\d{3})Z$/, ".$1123+00:00")
|
|
f.raw.terminal.plan.expires_at = sourceTime
|
|
assert.equal((await f.run()).originalActivityAt, sourceTime)
|
|
})
|
|
|
|
test("unknown terminal columns remain in fixed terminal MAC rather than being dropped", async () => {
|
|
const f = await fixture(), first = await f.run()
|
|
f.raw.terminal.operation.future_opaque = { preserve: "unchanged original evidence" }
|
|
const second = await f.run()
|
|
assert.notEqual(second.terminalDigest, first.terminalDigest)
|
|
assert.deepEqual(f.raw.terminal.operation.future_opaque, { preserve: "unchanged original evidence" })
|
|
})
|
|
|
|
test("caller mutation after the first crypto await cannot replace the captured original source", async () => {
|
|
const f = await fixture(), expected = await f.run()
|
|
let first = true
|
|
const crypto = { ...f.crypto, decrypt: async (text: string) => {
|
|
if (first) { first = false; f.raw.terminal.operation.state = "unknown"; f.raw.admission.owner_id = "other" }
|
|
return f.decrypt(text)
|
|
} }
|
|
assert.deepEqual(await verifyServerPollTerminalSourceForTests(f.raw, f.history, f.now, crypto), expected)
|
|
})
|