214 lines
16 KiB
TypeScript
214 lines
16 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createHash, randomUUID } from "node:crypto"
|
|
import { test } from "node:test"
|
|
import type { ActionContext, ChangeEvidence } from "./action-types.js"
|
|
import { createServerPollMcpAdapterForTests, type ServerPollMcpDependencies } from "./server-poll-actions.js"
|
|
import { fingerprint, redact } from "./security.js"
|
|
import type { DurableServerPollSessionInput } from "../../services/server-poll-durable-session.js"
|
|
import type { ServerPollReceipt } from "../../services/server-poll-execution.js"
|
|
|
|
function fixture(hooks: { verified?: () => Promise<void>; owned?: () => Promise<void>; authority?: () => Promise<void>; readArchived?:ServerPollMcpDependencies["readArchived"] } = {}) {
|
|
let now = Date.now(), revoked = false, verified = true, stateProof = "a".repeat(64), authorityProof = "b".repeat(64), executions = 0, reads = 0, authCalls = 0
|
|
const operationId = randomUUID(), sessions: DurableServerPollSessionInput[] = [], queries: unknown[][] = []
|
|
const context = { principal: { connectionId: randomUUID(), credentialId: randomUUID(), credentialExpiresAt: new Date(now + 600000).toISOString() },
|
|
connection: { owner_id: "owner", owner_claims_issued_at: new Date(now - 1000), owner_valid_until: new Date(now + 600000), policy: { expiresAt: new Date(now + 600000).toISOString() } } } as ActionContext
|
|
const encode = (value: string) => Buffer.from(value).toString("base64"), decode = (value: string) => Buffer.from(value, "base64").toString()
|
|
let evidence!: ChangeEvidence
|
|
const row: Record<string, unknown> = { operation_id: operationId, operation_state: "running", plan_state: "executing", approved_by: "human", step_state: "intent", step_index: 0, result: null }
|
|
let stored: ServerPollReceipt | undefined
|
|
let artifactOpens = 0, authorityPasses = 1, onPass: (index: number) => void = () => {}
|
|
const projections: boolean[] = []
|
|
const deps: ServerPollMcpDependencies = {
|
|
...(hooks.readArchived?{readArchived:hooks.readArchived}:{}),
|
|
now: () => now, seal: async value => encode(value), open: async value => { const text = decode(value); if (text.includes('"steps":')) artifactOpens++; return text }, proof: async value => fingerprint(value),
|
|
verified: async () => { await hooks.verified?.(); if (!verified) throw Error("PRIVATE_PROVIDER missing inherited guard") },
|
|
authority: () => async (_request, ids, signal) => { signal?.throwIfAborted(); await hooks.authority?.(); authCalls++; if (revoked || ids.some(id => ![1, 2].includes(id))) throw Error("PRIVATE_PROVIDER denied"); return { global: true, serverIds: [1, 2], authorityProof } },
|
|
query: async (sql, values) => {
|
|
await hooks.owned?.()
|
|
queries.push(values)
|
|
if (sql.startsWith("SELECT o.id FROM")) return [{ id: operationId }]
|
|
assert.equal(values[0], operationId); assert.equal(values[1], context.principal.connectionId); assert.equal(values[2], "owner")
|
|
const full = sql.includes("p.evidence AS evidence"), artifact = { sealed: encode(JSON.stringify(evidence)) }; projections.push(full)
|
|
return [{ ...row, intended_state: row.intended_state ?? redact(evidence.steps[0]), evidence: full ? artifact : null,
|
|
evidence_sha256: createHash("sha256").update(JSON.stringify(artifact)).digest("hex") }]
|
|
},
|
|
session: input => {
|
|
sessions.push(structuredClone({ ...input, authorize: undefined }) as unknown as DurableServerPollSessionInput)
|
|
return {
|
|
prepare: async signal => { await input.authorize(input.request, [1, 2], signal); return { version: 1, requiresHuman: true, scope: "global", request: { ...input.request }, around: new Date(now).toISOString(),
|
|
beforeProof: stateProof, authorityProof, bindingProof: "c".repeat(64), maintenance: [], affectedServerIds: [1, 2], mutationCost: 8 } },
|
|
execute: async (plan, signal) => { for (let index = 0; index < authorityPasses; index++) { onPass(index); await input.authorize(input.request, plan.affectedServerIds, signal) }; executions++
|
|
stored = { receiptId: input.request.receiptId, complete: true, maintenanceComplete: true, configurationVerified: true, nativeReads: 4, confirmedPublications: 2, completedPublications: 2,
|
|
afterProof: "d".repeat(64), observation: "online", snapshot: { id: 7, serverId: 1, polledAt: new Date(now).toISOString(), status: "online", identityName: "router" } }
|
|
return structuredClone(stored)
|
|
},
|
|
readExisting: async (plan, signal) => { await input.authorize(input.request, plan.affectedServerIds, signal); reads++; return stored ? structuredClone(stored) : undefined },
|
|
}
|
|
},
|
|
}
|
|
const adapter = createServerPollMcpAdapterForTests(deps)
|
|
const prepare = async () => { evidence = await adapter.prepare({ serverId: 1 }, context); return evidence.steps[0].kind === "service" ? evidence.steps[0].input : assert.fail("Expected service") }
|
|
const execute = (input: Record<string, unknown>) => adapter.service.execute(input, { operationId, phase: "forward", stepIndex: 0 })
|
|
return { adapter, context, deps, row, operationId, sessions, queries, prepare, execute, evidence: () => evidence, decode, encode,
|
|
revoke: () => { revoked = true }, unverify: () => { verified = false }, advance: (ms: number) => { now += ms }, drift: () => { stateProof = "e".repeat(64) }, grantDrift: () => { authorityProof = "f".repeat(64) },
|
|
executions: () => executions, reads: () => reads, authCalls: () => authCalls, artifactOpens: () => artifactOpens, projections,
|
|
passes: (count: number, callback: (index: number) => void = () => {}) => { authorityPasses = count; onPass = callback } }
|
|
}
|
|
|
|
test("each dispatch boundary waits for all independent live sources, including a late refusal", async () => {
|
|
for (const refused of [false, true]) {
|
|
let active = false, reached!: () => void
|
|
const started = new Set<string>(), releases = new Map<string, () => void>()
|
|
const allStarted = new Promise<void>(resolve => { reached = resolve })
|
|
const check = (name: string) => async () => {
|
|
if (!active) return
|
|
const waiting = new Promise<void>(resolve => { releases.set(name, resolve) })
|
|
started.add(name); if (started.size === 3) reached()
|
|
await waiting
|
|
if (refused && name === "authority") throw Error("late revocation")
|
|
}
|
|
const f = fixture({ verified: check("verified"), owned: check("owned"), authority: check("authority") })
|
|
const input = await f.prepare(); f.passes(1, () => { active = true })
|
|
const execution = f.execute(input)
|
|
// Observe rejection immediately, even while the other sources are pending.
|
|
const outcome = execution.then(() => true, () => false)
|
|
await allStarted
|
|
releases.get("verified")!(); releases.get("owned")!()
|
|
await Promise.resolve(); assert.equal(f.executions(), 0)
|
|
active = false; releases.get("authority")!()
|
|
assert.equal(await outcome, !refused); assert.equal(f.executions(), refused ? 0 : 1)
|
|
}
|
|
})
|
|
|
|
test("public input accepts only serverId; human global evidence seals original identity and no placeholder operation", async () => {
|
|
const f = fixture(), input = await f.prepare(), evidence = f.evidence()
|
|
assert(!f.adapter.schema.safeParse({ serverId: 1, operationId: randomUUID(), receiptId: randomUUID(), principal: {} }).success)
|
|
assert.deepEqual(evidence.target, { scope: "global" }); assert.equal(evidence.requiresHuman, true); assert.equal(evidence.mutationCost, 8)
|
|
assert.equal(evidence.verificationScope, "configuration"); assert.deepEqual(evidence.objects.map(object => object.serverId), [1, 2])
|
|
const binding = JSON.parse(f.decode(String(input.bindingCiphertext)))
|
|
assert.deepEqual(binding.principal, f.context.principal); assert.equal(binding.ownerId, "owner"); assert.equal(binding.expiresAt, Date.parse(evidence.validUntil!))
|
|
assert(!("executionId" in binding)); assert(!("identity" in binding)); assert.equal(f.executions(), 0)
|
|
assert(f.sessions.every(session => session.identity.executionId !== f.operationId))
|
|
})
|
|
|
|
test("apply uses actual runner op ID, inherited guard and original sealed expiry/principal", async () => {
|
|
const f = fixture(), input = await f.prepare(), expiry = Date.parse(f.evidence().validUntil!)
|
|
const result = await f.execute(input) as Record<string, unknown>, execution = f.sessions.at(-1)!
|
|
assert.equal(execution.identity.executionId, f.operationId); assert.equal(execution.identity.expiresAt, expiry)
|
|
assert.equal(execution.identity.kind, "mcp"); assert.equal(f.executions(), 1); assert(f.authCalls() > 3)
|
|
assert.equal(result.operationId, f.operationId); assert.equal(result.nativeReads, 4); assert(!JSON.stringify(result).includes("bindingProof")); assert(!JSON.stringify(result).includes("rawInterfaces"))
|
|
})
|
|
|
|
test("service refuses missing real context, recovery, wrong step, absent guard and human approval", async () => {
|
|
for (const mode of ["context", "recovery", "step", "guard", "human"]) {
|
|
const f = fixture(), input = await f.prepare()
|
|
if (mode === "guard") f.unverify(); if (mode === "human") f.row.approved_by = null
|
|
await assert.rejects(mode === "context" ? f.adapter.service.execute(input) : mode === "recovery" ? f.adapter.service.execute(input, { operationId: f.operationId, phase: "recovery" })
|
|
: mode === "step" ? f.adapter.service.execute(input, { operationId: f.operationId, phase: "forward", stepIndex: 1 }) : f.execute(input))
|
|
assert.equal(f.executions(), 0)
|
|
}
|
|
})
|
|
|
|
test("sealed input/evidence tamper and an expired original plan refuse despite another live credential", async () => {
|
|
for (const mode of ["digest", "receipt", "evidence", "expired"]) {
|
|
const f = fixture(), input = await f.prepare()
|
|
if (mode === "digest") input.inputDigest = "0".repeat(64)
|
|
if (mode === "receipt") input.receiptId = randomUUID()
|
|
if (mode === "evidence") f.evidence().requiresHuman = false
|
|
if (mode === "expired") { f.advance(300001); f.context.principal.credentialId = randomUUID(); f.context.principal.credentialExpiresAt = new Date(Date.now() + 3600000).toISOString() }
|
|
await assert.rejects(f.execute(input)); assert.equal(f.executions(), 0)
|
|
}
|
|
})
|
|
|
|
test("current is journal-free and refuses original source/policy drift; revoked scope cannot prepare", async () => {
|
|
const f = fixture(), input = await f.prepare()
|
|
assert.deepEqual(await f.adapter.service.current(input), f.evidence().before); assert.equal(f.executions(), 0); assert.equal(f.reads(), 0)
|
|
f.drift(); await assert.rejects(f.adapter.service.current(input))
|
|
const g = fixture(), other = await g.prepare(); g.grantDrift(); await assert.rejects(g.adapter.service.current(other))
|
|
const h = fixture(); h.revoke(); await assert.rejects(h.prepare()); assert.equal(h.executions(), 0)
|
|
})
|
|
|
|
test("verify/reconcile use only authenticated persisted read, never execute/claim replay", async () => {
|
|
const f = fixture(), input = await f.prepare()
|
|
assert.equal(await f.adapter.service.verify!(input, {}), false)
|
|
const result = await f.execute(input); f.row.result = result; f.row.step_state = "applied"
|
|
assert.equal(await f.adapter.service.verify!(input, result), true); assert.equal(f.executions(), 1); assert.equal(f.reads(), 1)
|
|
assert.deepEqual(await f.adapter.service.reconcile!(input, async () => {}), { matchesDesiredState: true, matchesOriginalState: false })
|
|
assert.equal(f.executions(), 1); assert.equal(f.reads(), 2)
|
|
f.row.result = { forged: true }; assert.equal(await f.adapter.service.verify!(input, result), false)
|
|
f.revoke(); assert.equal(await f.adapter.service.verify!(input, result), false)
|
|
})
|
|
|
|
test("expired binding reconciles through optional historical reader with current authority and no old session/grant",async()=>{
|
|
let archiveCalls=0,currentChecks=0
|
|
const f=fixture({readArchived:async(_raw,authorize)=>{archiveCalls++;await authorize();return true}}),input=await f.prepare()
|
|
f.advance(300001);f.revoke()
|
|
const before={sessions:f.sessions.length,auth:f.authCalls(),queries:f.queries.length}
|
|
assert.deepEqual(await f.adapter.service.reconcile!(input,async()=>{currentChecks++}),{matchesDesiredState:true,matchesOriginalState:false})
|
|
assert.equal(archiveCalls,1);assert(currentChecks>=4)
|
|
assert.deepEqual({sessions:f.sessions.length,auth:f.authCalls(),queries:f.queries.length},before)
|
|
const g=fixture(),other=await g.prepare();g.advance(300001)
|
|
assert.deepEqual(await g.adapter.service.reconcile!(other,async()=>{}),{matchesDesiredState:false,matchesOriginalState:false})
|
|
})
|
|
|
|
test("expired historical reconcile propagates current permission denial instead of publishing a safe-looking false",async()=>{
|
|
const denied=Error("current permission denied")
|
|
const f=fixture({readArchived:async(_raw,authorize)=>{await authorize();throw denied}}),input=await f.prepare()
|
|
f.advance(300001);let checks=0
|
|
await assert.rejects(f.adapter.service.reconcile!(input,async()=>{if(++checks===4)throw denied}),error=>error===denied)
|
|
})
|
|
|
|
test("missing persisted receipt cannot verify a plausible result", async () => {
|
|
const f = fixture(), input = await f.prepare()
|
|
const plausible = { operationId: f.operationId, receiptId: input.receiptId, nativeReads: 4, confirmedPublications: 2, completedPublications: 2, complete: true, maintenanceComplete: true, configurationVerified: true, automaticReplay: false,
|
|
snapshot: { id: 7, serverId: 1, polledAt: new Date().toISOString(), status: "online" } }
|
|
f.row.result = plausible
|
|
assert.equal(await f.adapter.service.verify!(input, plausible), false); assert.equal(f.executions(), 0); assert.equal(f.reads(), 1)
|
|
})
|
|
|
|
test("same-window artifact decrypt occurs once while ownership and authority SQL remain fresh at every boundary", async () => {
|
|
const f = fixture(), input = await f.prepare(); f.passes(5)
|
|
await f.execute(input)
|
|
assert.equal(f.artifactOpens(), 1); assert.equal(f.queries.length, 7); assert.deepEqual(f.projections, [true, false, false, false, false, false, false])
|
|
assert(f.authCalls() >= 8)
|
|
await f.execute(input)
|
|
assert.equal(f.artifactOpens(), 2); assert.equal(f.projections.filter(Boolean).length, 2, "A new window cannot reuse artifact validation")
|
|
})
|
|
|
|
test("fresh SHA drift refetches full artifact and rejects tamper instead of using cached approval", async () => {
|
|
const f = fixture(), input = await f.prepare()
|
|
f.passes(2, index => { if (index === 1) f.evidence().requiresHuman = false })
|
|
await assert.rejects(f.execute(input)); assert.equal(f.executions(), 0)
|
|
assert.deepEqual(f.projections, [true, false, false, true]); assert.equal(f.artifactOpens(), 2)
|
|
})
|
|
|
|
test("cached artifact never caches revocation, human approval, operation ID or original expiry", async () => {
|
|
for (const mode of ["revocation", "approval", "expiry"]) {
|
|
const f = fixture(), input = await f.prepare()
|
|
f.passes(2, index => { if (index !== 1) return; if (mode === "revocation") f.revoke(); if (mode === "approval") f.row.approved_by = null; if (mode === "expiry") f.advance(300001) })
|
|
await assert.rejects(f.execute(input)); assert.equal(f.executions(), 0)
|
|
assert.equal(f.artifactOpens(), 1)
|
|
}
|
|
const f = fixture(), input = await f.prepare(); await f.execute(input)
|
|
await assert.rejects(f.adapter.service.execute(input, { operationId: randomUUID(), phase: "forward", stepIndex: 0 }))
|
|
assert.equal(f.executions(), 1); assert.equal(f.artifactOpens(), 1)
|
|
})
|
|
|
|
test("derived expected input never substitutes for a changed current intended-state row", async () => {
|
|
const f=fixture(),input=await f.prepare()
|
|
f.passes(2,index=>{if(index===1)f.row.intended_state={kind:"service",service:"servers.poll",input:{serverId:2}}})
|
|
await assert.rejects(f.execute(input));assert.equal(f.executions(),0)
|
|
assert.equal(f.artifactOpens(),1);assert(f.queries.length>=3)
|
|
assert(f.queries.every(values=>JSON.parse(String(values[4])).input.serverId===1))
|
|
})
|
|
|
|
|
|
test("unbranded combined-authority injection cannot replace the original verified runtime branch", async () => {
|
|
const f=fixture(),input=await f.prepare();let forgedCalls=0
|
|
const forged=async()=>{forgedCalls++;return {global:true as const,serverIds:[1,2],authorityProof:"b".repeat(64)}}
|
|
const adapter=createServerPollMcpAdapterForTests({...f.deps,combinedAuthority:()=>forged})
|
|
f.passes(1,()=>f.unverify())
|
|
await assert.rejects(adapter.service.execute(input,{operationId:f.operationId,phase:"forward",stepIndex:0}))
|
|
assert.equal(forgedCalls,0);assert.equal(f.executions(),0)
|
|
})
|