126 lines
9.8 KiB
TypeScript
126 lines
9.8 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createHash, randomUUID } from "node:crypto"
|
|
import { mkdtemp, readdir, rm, rmdir } from "node:fs/promises"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { createDiagnosticCancellationSourceForTests, createReadServerProbeExecutionSourceForTests, readServerProbeExecutionSource } from "./diagnostic-cancellation-source.js"
|
|
import { fingerprint, redact } from "./security.js"
|
|
|
|
const proof = async (value: unknown) => createHash("sha256").update(fingerprint(value)).digest("hex")
|
|
function fixture() {
|
|
const operationId = randomUUID(), connectionId = randomUUID(), credentialId = randomUUID(), receiptId = randomUUID()
|
|
const owner = { connectionId, ownerId: "owner" }, sealed = new Map<string,string>()
|
|
const binding = { version: 1, operation: "servers.probes.run", principal: { connectionId, credentialId, credentialExpiresAt: "2020-01-01T00:00:00.000Z" }, ownerId: owner.ownerId, issuedAt: 1, authorityExpiresAt: 1577836800000, prepared: { receiptId, serverId: 9, tool: "ping", expiresAt: "2020-01-01T00:00:00.000Z", bindingCiphertext: "original-inner" }, bindingProof: "a".repeat(64), stageBudget: 2 }
|
|
const input = { receiptId, serverId: 9, inputDigest: "", bindingCiphertext: "original-binding" }
|
|
const step = { kind: "service", service: "servers.probes.run", input }
|
|
const evidence = { steps: [step], target: { scope: "servers", serverIds: [9] }, requiresHuman: true, verificationScope: "acknowledgement", validUntil: binding.prepared.expiresAt, mutationCost: 2 }
|
|
const row: Record<string,unknown> = { operation_id: operationId, connection_id: connectionId, owner_id: owner.ownerId, operation_state: "running", operation_name: "servers.probes.run", operation_version: 1, plan_state: "executing", approved_by: "human", evidence: { sealed: "original-evidence" }, step_index: 0, step_state: "intent", intended_state: null }
|
|
let rows = [row], calls = 0
|
|
const refresh = async () => { input.inputDigest = await proof(binding); sealed.set(input.bindingCiphertext, JSON.stringify(binding)); sealed.set("original-evidence", JSON.stringify(evidence)); row.intended_state = redact(step) }
|
|
const crypto = { proof, open: async (value: string) => { const raw = sealed.get(value); if (!raw) throw new Error("PRIVATE_SECRET"); return raw } }
|
|
const load = createDiagnosticCancellationSourceForTests(crypto), read = createReadServerProbeExecutionSourceForTests(crypto)
|
|
const readSql: string[] = []
|
|
const client = { query: async (sql: string, values?: unknown[]) => { calls++; assert.ok(sql.includes("LEFT JOIN mcp_operation_steps")); assert.deepEqual(values, [operationId, connectionId, owner.ownerId]); assert.match(sql,/FOR UPDATE OF o,p,c/); assert.ok(!/INSERT|UPDATE|DELETE/.test(sql.replace("FOR UPDATE OF o,p,c",""))); return { rows } } }
|
|
const snapshot = { query: async (sql: string, values?: unknown[]) => {
|
|
readSql.push(sql); assert.deepEqual(values, [operationId, connectionId, owner.ownerId])
|
|
assert.ok(sql.includes("LEFT JOIN mcp_operation_steps")); assert.match(sql, /LIMIT 2$/)
|
|
assert.ok(!/FOR UPDATE|FOR SHARE|INSERT|UPDATE|DELETE|BEGIN|COMMIT/.test(sql))
|
|
return { rows }
|
|
} }
|
|
return { load: () => load(client, operationId, owner), read: () => read(snapshot, operationId, owner), readSql,
|
|
readWithExistingKey: () => readServerProbeExecutionSource(snapshot, operationId, owner),
|
|
refresh, binding, input, evidence, row, sealed, setRows: (value: typeof rows) => { rows=value }, calls: () => calls, operationId, credentialId }
|
|
}
|
|
{
|
|
const f=fixture(); await f.refresh(); const source=await f.load()
|
|
assert.equal(source.scope.executionId,f.operationId); assert.equal(source.scope.bindingProof,f.binding.bindingProof); assert.equal(source.originalCredentialId,f.credentialId)
|
|
assert.equal(source.scope.authorityExpiresAt,"2020-01-01T00:00:00.000Z"); assert.equal(source.terminal,false); assert.equal(f.calls(),1)
|
|
assert.ok(Object.isFrozen(source) && Object.isFrozen(source.scope) && Object.isFrozen(source.serverIds))
|
|
assert.equal("originalContext" in source, false)
|
|
const original=source.sourceDigest
|
|
f.row.operation_state="pending"; f.row.step_index=null; f.row.step_state=null; f.row.intended_state=null
|
|
assert.equal((await f.load()).sourceState,"pending")
|
|
f.row.step_index=0; f.row.step_state="pending"; f.row.intended_state=redact(f.evidence.steps[0]); assert.equal((await f.load()).terminal,false)
|
|
f.row.operation_state="applied"; f.row.plan_state="completed"; f.row.step_state="acknowledged"
|
|
const terminal=await f.load(); assert.equal(terminal.terminal,true); assert.equal(terminal.sourceDigest,original)
|
|
f.row.approved_by="different-human"; assert.notEqual((await f.load()).sourceDigest,original)
|
|
}
|
|
const mutations: Array<(f:ReturnType<typeof fixture>)=>void|Promise<void>> = [
|
|
f=>{f.setRows([])}, f=>{f.setRows([f.row,f.row])},
|
|
f=>{f.row.operation_id=randomUUID()}, f=>{f.row.connection_id=randomUUID()}, f=>{f.row.owner_id="foreign"},
|
|
f=>{f.row.operation_name="servers.poll"}, f=>{f.row.operation_version=2}, f=>{f.row.approved_by=null},
|
|
f=>{f.row.step_index=1}, f=>{f.row.step_state="applied"}, f=>{f.row.plan_state="approved"}, f=>{f.row.intended_state={ mismatch:true }},
|
|
f=>{f.row.evidence={sealed:"missing"}}, f=>{f.sealed.set("original-evidence","x".repeat(2097153))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,steps:[...f.evidence.steps,...f.evidence.steps]}))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,requiresHuman:false}))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,verificationScope:"configuration"}))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,validUntil:"2030-01-01T00:00:00.000Z"}))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,target:{scope:"servers",serverIds:[8]}}))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,mutationCost:1}))},
|
|
async f=>{f.binding.ownerId="foreign";await f.refresh()},
|
|
async f=>{f.binding.principal.connectionId=randomUUID();await f.refresh()},
|
|
async f=>{f.binding.stageBudget=1;f.evidence.mutationCost=1;await f.refresh()},
|
|
f=>{f.sealed.set("original-binding",JSON.stringify({...f.binding,bindingProof:"b".repeat(64)}))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,steps:[{...f.evidence.steps[0],input:{...f.input,receiptId:randomUUID()}}]}))},
|
|
f=>{f.sealed.set("original-evidence",JSON.stringify({...f.evidence,steps:[{...f.evidence.steps[0],input:{...f.input,serverId:8}}]}))},
|
|
async f=>{Object.assign(f.binding,{unexpected:true});await f.refresh()},
|
|
]
|
|
for (const mutate of mutations) {
|
|
const f=fixture();await f.refresh();await mutate(f)
|
|
await assert.rejects(f.load(),error=>error instanceof Error && !error.message.includes("PRIVATE_SECRET"))
|
|
await assert.rejects(f.read(),error=>error instanceof Error && !error.message.includes("PRIVATE_SECRET"))
|
|
}
|
|
{
|
|
const f = fixture(); await f.refresh()
|
|
const locked = await f.load(), snapshot = await f.read()
|
|
assert.equal(snapshot.sourceDigest, locked.sourceDigest)
|
|
assert.deepEqual(Object.keys(snapshot).filter(key => key !== "originalContext"), Object.keys(locked))
|
|
assert.equal(f.readSql.length, 1)
|
|
const context = snapshot.originalContext
|
|
assert.deepEqual(context, { identity: { kind: "mcp", ownerId: f.binding.ownerId, executionId: f.operationId,
|
|
connectionId: f.binding.principal.connectionId, credentialId: f.credentialId, issuedAt: 1,
|
|
expiresAt: 1577836800000, operationName: "servers.probes.run" }, sourceServerId: 9, tool: "ping" })
|
|
assert.equal("destinationServerId" in context, false)
|
|
assert.ok(Object.isFrozen(snapshot) && Object.isFrozen(context) && Object.isFrozen(context.identity))
|
|
assert.throws(() => { Object.assign(context.identity, { expiresAt: Date.now() + 300000 }) }, TypeError)
|
|
assert.throws(() => { Object.assign(context, { sourceServerId: 8 }) }, TypeError)
|
|
assert.equal(context.identity.expiresAt, f.binding.authorityExpiresAt)
|
|
assert(context.identity.expiresAt < Date.now())
|
|
assert.equal(JSON.stringify(snapshot).includes("original-binding"), false)
|
|
assert.equal(JSON.stringify(snapshot).includes("original-inner"), false)
|
|
// The historical loader needs neither today's credential nor live authority.
|
|
f.row.operation_state = "unknown"; f.row.plan_state = "expired"
|
|
const terminal = await f.read(); assert.equal(terminal.terminal, true)
|
|
assert.equal(terminal.originalContext.identity.expiresAt, context.identity.expiresAt)
|
|
assert.equal(terminal.sourceDigest, snapshot.sourceDigest)
|
|
}
|
|
{
|
|
const f = fixture()
|
|
Object.assign(f.binding.prepared, { tool: "bandwidth", destinationServerId: 12 })
|
|
f.binding.stageBudget = 1; f.evidence.mutationCost = 1; f.evidence.target.serverIds = [9, 12]
|
|
await f.refresh()
|
|
const source = await f.read()
|
|
assert.deepEqual(source.serverIds, [9, 12]); assert.equal(source.originalContext.destinationServerId, 12)
|
|
assert.equal(source.originalContext.tool, "bandwidth"); assert.equal(source.stageBudget, 1)
|
|
assert.equal(source.originalContext.identity.credentialId, f.credentialId)
|
|
}
|
|
{
|
|
const state = await mkdtemp(join(tmpdir(), "mm-legacy-source-test-"))
|
|
const previousState = process.env.MCP_STATE_DIR
|
|
process.env.MCP_STATE_DIR = state
|
|
try {
|
|
const f = fixture()
|
|
await f.refresh()
|
|
f.row.evidence = { sealed: Buffer.alloc(32).toString("base64") }
|
|
await assert.rejects(f.readWithExistingKey, { code: "STATE_CONFLICT" })
|
|
assert.equal(f.readSql.length, 1)
|
|
assert.deepEqual(await readdir(state), [], "Historical source reads must leave missing encryption state untouched")
|
|
} finally {
|
|
if (previousState === undefined) delete process.env.MCP_STATE_DIR
|
|
else process.env.MCP_STATE_DIR = previousState
|
|
await rm(join(state, "encryption-key"), { force: true })
|
|
await rmdir(state)
|
|
}
|
|
}
|
|
console.log(`diagnostic-cancellation-source: locked/read-only source, missing key, expired original contexts and ${mutations.length} shared tamper checks passed`)
|