172 lines
11 KiB
TypeScript
172 lines
11 KiB
TypeScript
/** Reader orchestration components: real original-binding AES/HMAC, SQL and
|
|
* already-verified archive dependency doubles. The archive's own tests cover
|
|
* its fixed decrypt/history/terminal pipeline; these are not public SQL proofs. */
|
|
import assert from "node:assert/strict"
|
|
import { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID } from "node:crypto"
|
|
import { test } from "node:test"
|
|
import { fingerprint } from "../modules/mcp/security.js"
|
|
import { readRetiredServerPollHistoryForTests, readServerPollArchivedHistoryForTests } from "./server-poll-history-reader.js"
|
|
import type { openServerPollRetiredArchive } from "./server-poll-retired-archive.js"
|
|
import type { openServerPollTerminalArchive, ServerPollArchiveSource } from "./server-poll-terminal-archive.js"
|
|
|
|
function fixture(){
|
|
const now=Date.now(),secret=randomBytes(32),connectionId=randomUUID(),receiptId=randomUUID(),executionId=randomUUID()
|
|
const events:string[]=[],calls:{sql:string;values:unknown[]}[]=[]
|
|
let revoked=false,mode="normal",opens=0,decrypts=0
|
|
const denied=Object.assign(Error("Current reader permission revoked"),{code:"PERMISSION_DENIED"})
|
|
const proof=async(value:unknown)=>createHmac("sha256",secret).update(fingerprint(value)).digest("hex")
|
|
const encrypt=(text:string)=>{
|
|
const nonce=randomBytes(12),cipher=createCipheriv("aes-256-gcm",secret,nonce),value=Buffer.concat([cipher.update(text),cipher.final()])
|
|
return Buffer.concat([nonce,cipher.getAuthTag(),value]).toString("base64")
|
|
}
|
|
const decrypt=async(text:string)=>{
|
|
events.push("decrypt");decrypts++
|
|
const value=Buffer.from(text,"base64"),cipher=createDecipheriv("aes-256-gcm",secret,value.subarray(0,12));cipher.setAuthTag(value.subarray(12,28))
|
|
const result=Buffer.concat([cipher.update(value.subarray(28)),cipher.final()]).toString("utf8")
|
|
if(mode==="revoke-decrypt")revoked=true
|
|
return result
|
|
}
|
|
const owner="original-owner",binding={version:1,operation:"servers.poll",ownerId:owner,issuedAt:now-600000,expiresAt:now-300000,
|
|
principal:{connectionId,credentialId:randomUUID(),credentialExpiresAt:new Date(now-200000).toISOString()},plan:{request:{serverId:1,receiptId},requiresHuman:true}}
|
|
let input:Record<string,unknown>
|
|
const originalAdmission={receipt_id:receiptId,execution_id:executionId,connection_id:connectionId,owner_id:owner,storage_state:"full",
|
|
compact_at:null,archive_bytes:null,original_activity_at:null,binding_proof:"a".repeat(64),context_proof:"b".repeat(64),future_opaque:{preserve:true}}
|
|
let original:ServerPollArchiveSource,row:Record<string,unknown>
|
|
const authorize=async()=>{events.push("authorize");if(revoked)throw denied}
|
|
const deps={now:()=>now,decrypt,bindingProof:proof,
|
|
query:async(sql:string,values:unknown[])=>{
|
|
events.push("query");calls.push({sql,values});if(mode==="revoke-sql")revoked=true
|
|
return mode==="missing"||mode==="late-gc"&&calls.length===2?[]:mode==="duplicate"?[structuredClone(row),structuredClone(row)]:[structuredClone(row)]
|
|
},
|
|
openArchive:async()=>{
|
|
events.push("archive");opens++;if(mode==="bad-archive")throw Error("Private archive proof failed")
|
|
if(mode==="revoke-archive")revoked=true
|
|
if(mode==="late-source") (row.current_terminal as ServerPollArchiveSource["terminal"]).operation.result={changed:true}
|
|
return {source:structuredClone(original),sourceText:"private full archive",metadata:{}} as Awaited<ReturnType<typeof openServerPollTerminalArchive>>
|
|
},
|
|
}
|
|
const setup=async()=>{
|
|
input={serverId:1,receiptId,inputDigest:await proof(binding),bindingCiphertext:encrypt(JSON.stringify(binding))}
|
|
const terminal={operation:{id:executionId,state:"applied",verification:"passed",result:{confirmedWrites:1}},
|
|
plan:{operation_id:"servers.poll",evidence:{sealed:encrypt(JSON.stringify({steps:[{kind:"service",service:"servers.poll",input}]}))}},
|
|
step:{operation_id:executionId,step_index:0,state:"verified",result:{receiptId,complete:true}}}
|
|
original={admission:originalAdmission,journal:{execution:{},intents:[],acks:[],receipt:{},quarantines:[]},terminal}
|
|
row={receipt_id:receiptId,execution_id:executionId,connection_id:connectionId,owner_id:owner,
|
|
current_admission:{...structuredClone(originalAdmission),storage_state:"compacted",compact_at:new Date(now-100000).toISOString(),archive_bytes:100,original_activity_at:new Date(now-200000).toISOString()},
|
|
current_terminal:structuredClone(terminal)}
|
|
}
|
|
const run=()=>readServerPollArchivedHistoryForTests(input,authorize,{deadlineAt:now+20000},deps)
|
|
return {setup,run,events,calls,binding,denied,encrypt,proof,raw:()=>input,row:()=>row,source:()=>original,mode:(value:string)=>{mode=value},revoke:()=>{revoked=true},counts:()=>({opens,decrypts}),now,deps,authorize}
|
|
}
|
|
|
|
test("expired original identity reads a verified archive under current authority without constructing a live session",async()=>{
|
|
const f=fixture();await f.setup();assert.equal(await f.run(),true)
|
|
assert.deepEqual(f.calls[0].values,[f.raw().receiptId,f.binding.principal.connectionId,f.binding.ownerId])
|
|
const sql=f.calls[0].sql
|
|
assert.match(sql,/FROM public\.server_poll_archives/);assert.match(sql,/a\.storage_state='compacted'/);assert.match(sql,/LIMIT 2$/)
|
|
assert.match(sql,/count\(\*\).*mcp_operation_steps/);assert.match(sql,/to_jsonb\(o\).*to_jsonb\(p\).*to_jsonb\(s\)/)
|
|
assert(!/\b(?:UPDATE|INSERT|DELETE|LOCK|FOR\s+UPDATE)\b/i.test(sql));assert(!sql.includes("mcp_credentials"));assert(!sql.includes("mcp_grants"))
|
|
for(const event of ["query","archive","decrypt"])for(const [index,value]of f.events.entries())if(value===event){assert.equal(f.events[index-1],"authorize");assert.equal(f.events[index+1],"authorize")}
|
|
assert.equal(f.events.at(-1),"authorize");assert.equal(f.counts().opens,1)
|
|
})
|
|
|
|
for(const mode of ["missing","duplicate","bad-archive","digest","owner","input","current-evidence","current-result","admission-opaque","malformed-binding","late-source","late-gc"])
|
|
test("historical reader fails safely on "+mode,async()=>{
|
|
const f=fixture();await f.setup();f.mode(mode)
|
|
if(mode==="digest")f.raw().inputDigest="0".repeat(64)
|
|
if(mode==="owner")f.row().owner_id="other"
|
|
if(mode==="input"){
|
|
f.source().terminal.plan.evidence={sealed:f.encrypt(JSON.stringify({steps:[{kind:"service",service:"servers.poll",input:{...f.raw(),inputDigest:"0".repeat(64)}}]}))}
|
|
f.row().current_terminal=structuredClone(f.source().terminal)
|
|
}
|
|
if(mode==="current-evidence")(f.row().current_terminal as ServerPollArchiveSource["terminal"]).plan.evidence={sealed:"tampered"}
|
|
if(mode==="current-result")(f.row().current_terminal as ServerPollArchiveSource["terminal"]).step.result={forged:true}
|
|
if(mode==="admission-opaque")(f.row().current_admission as Record<string,unknown>).future_opaque={preserve:false}
|
|
if(mode==="malformed-binding")f.raw().bindingCiphertext="invalid"
|
|
assert.equal(await f.run(),false)
|
|
if(mode==="digest"||mode==="malformed-binding")assert.equal(f.calls.length,0)
|
|
})
|
|
|
|
for(const mode of ["revoke-decrypt","revoke-sql","revoke-archive"])
|
|
test("current authority revocation after "+mode+" propagates and cannot publish success",async()=>{
|
|
const f=fixture();await f.setup();f.mode(mode)
|
|
await assert.rejects(f.run(),error=>error===f.denied)
|
|
if(mode==="revoke-decrypt")assert.equal(f.calls.length,0)
|
|
})
|
|
|
|
test("already revoked current authority refuses before crypto/SQL and deadline/cancel never becomes historical authority",async()=>{
|
|
const f=fixture();await f.setup();f.revoke();await assert.rejects(f.run(),error=>error===f.denied)
|
|
assert.deepEqual(f.counts(),{opens:0,decrypts:0});assert.equal(f.calls.length,0)
|
|
const g=fixture();await g.setup()
|
|
assert.equal(await readServerPollArchivedHistoryForTests(g.raw(),g.authorize,{deadlineAt:g.now},g.deps),false)
|
|
assert.equal(await readServerPollArchivedHistoryForTests(g.raw(),g.authorize,{deadlineAt:g.now+20000,signal:AbortSignal.abort()},g.deps),false)
|
|
assert.equal(g.calls.length,0)
|
|
})
|
|
|
|
test("caller mutation while decrypt awaits cannot replace authenticated lookup identity",async()=>{
|
|
const f=fixture();await f.setup();const raw=structuredClone(f.raw())
|
|
const decrypt=f.deps.decrypt
|
|
assert.equal(await readServerPollArchivedHistoryForTests(raw,f.authorize,{deadlineAt:f.now+20000},{...f.deps,decrypt:async value=>{
|
|
raw.receiptId=randomUUID();return decrypt(value)
|
|
}}),true)
|
|
assert.equal(f.calls[0].values[0],f.raw().receiptId)
|
|
})
|
|
|
|
function retiredFixture() {
|
|
const now = Date.now(), operationId = randomUUID(), connectionId = randomUUID(), planId = randomUUID(), ownerId = "retired-owner"
|
|
const identity = { operationId, connectionId, ownerId }
|
|
const row = { plan_id: planId, target_server_ids: ["2", "1"], gc_not_before: "2026-10-31T01:00:00.123456Z" }
|
|
const failure = Error("authority revoked")
|
|
let queries = 0, opens = 0, checks = 0
|
|
let mode = ""
|
|
const run = () => readRetiredServerPollHistoryForTests(identity, async () => {
|
|
checks++
|
|
if (mode === "revoked-after-open" && opens) throw failure
|
|
}, { deadlineAt: now + 1000 }, {
|
|
now: () => now,
|
|
query: async (sql, parameters) => {
|
|
queries++
|
|
assert.deepEqual(parameters, [operationId, connectionId, ownerId])
|
|
assert.match(sql, /mcp_operation_replay_tombstones/)
|
|
assert.match(sql, /r\.version=2/)
|
|
assert.match(sql, /NOT EXISTS\(SELECT 1 FROM public\.mcp_operations/)
|
|
if (mode === "gone" && queries === 2) return []
|
|
if (mode === "changed" && queries === 2) return [{ ...row, target_server_ids: ["1"] }]
|
|
return [row]
|
|
},
|
|
open: async () => {
|
|
opens++
|
|
if (mode === "bad-proof") throw Error("private proof failure")
|
|
return { metadata: { execution_id: operationId, connection_id: connectionId, owner_id: ownerId },
|
|
history: { planId, affectedServerIds: [1, 2], gcNotBefore: "2026-10-31T01:00:00.123456Z" } } as Awaited<ReturnType<typeof openServerPollRetiredArchive>>
|
|
},
|
|
})
|
|
return { row, failure, run, mode: (value: string) => { mode = value }, counts: () => ({ queries, opens, checks }) }
|
|
}
|
|
|
|
test("retired lookup verifies a current tombstone, archive proof and a second SQL snapshot before returning only scope", async () => {
|
|
const f = retiredFixture()
|
|
assert.deepEqual(await f.run(), { affectedServerIds: [1, 2] })
|
|
assert.deepEqual(f.counts(), { queries: 2, opens: 1, checks: 4 })
|
|
})
|
|
|
|
test("retired lookup refuses proof, plan, scope or retention drift and GC between reads", async () => {
|
|
for (const mode of ["bad-proof", "changed", "gone"]) {
|
|
const f = retiredFixture()
|
|
f.mode(mode)
|
|
assert.equal(await f.run(), undefined)
|
|
}
|
|
for (const row of [{ plan_id: randomUUID() }, { target_server_ids: ["1", "1"] }, { gc_not_before: "2026-10-31T01:00:00.123457Z" }]) {
|
|
const f = retiredFixture()
|
|
Object.assign(f.row, row)
|
|
assert.equal(await f.run(), undefined)
|
|
}
|
|
})
|
|
|
|
test("retired lookup propagates exact current authorization failure after archive open", async () => {
|
|
const f = retiredFixture()
|
|
f.mode("revoked-after-open")
|
|
await assert.rejects(f.run(), error => error === f.failure)
|
|
assert.equal(f.counts().queries, 1)
|
|
})
|