144 lines
12 KiB
TypeScript
144 lines
12 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { test } from "node:test"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import { pool, closePool } from "../db/index.js"
|
|
import { withVerifiedConfigurationChange, assertVerifiedConfigurationAccess, captureVerifiedMcpServiceExecution as capture, inspectVerifiedMcpServiceExecution as inspect, type VerifiedMcpServiceMetadata, type VerifiedMcpServiceExecution } from "./config-mutation-policy.js"
|
|
|
|
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done }); return { promise, resolve } }
|
|
function fixture(milliseconds = 5000) {
|
|
const connectionId = randomUUID(), expiry = Date.now() + milliseconds
|
|
const metadata: VerifiedMcpServiceMetadata = { operationId: randomUUID(), planId: randomUUID(), operationName: "diagnostics.bandwidth", serviceName: "routing.measure", phase: "forward", stepIndex: 2,
|
|
operationVersion: 3, policyVersion: 4, generation: "original-generation", sealedEvidenceProof:"e".repeat(64),sealedPayloadProof:"f".repeat(64),originalTemporaryGrantProof:"a".repeat(64),originalTemporaryGrantExpiresAt:null,principal: { connectionId, credentialId: randomUUID(), credentialExpiresAt: new Date(expiry + 1000).toISOString() },
|
|
originalExpiresAt: expiry, serviceInput: { srcServerId: 101, dstServerId: 102, command: { durationSec: 2147483647, body: { address: "192.0.2.2", password: "SYNTHETIC-PRIVATE-STEP" } }, list: [1, { flag: true }] } }
|
|
let calls = 0, allowed = true, hook: (() => Promise<void>) | undefined
|
|
const input = { actorId: "owned-test-actor", connectionId, approved: false, serverIds: [101, 102], objects: [{ kind: "server", id: "101", serverId: 101 }], serverWide: true,
|
|
serviceExecution: metadata, authorize: async () => { calls++; if (hook) await hook(); if (!allowed) throw Error("Original authority revoked") } }
|
|
return { metadata, input, calls: () => calls, revoke: () => { allowed = false }, onAuthorize: (value: () => Promise<void>) => { hook = value } }
|
|
}
|
|
|
|
test("genuine MCP service execution capability lifecycle; no DB or network", async t => {
|
|
const originalQuery = pool.query, originalConnect = pool.connect
|
|
let sqlCalls = 0
|
|
pool.query = (() => { sqlCalls++; throw Error("Service token unit must not issue SQL") }) as never
|
|
pool.connect = (() => { sqlCalls++; throw Error("Service token unit must not acquire DB") }) as never
|
|
try {
|
|
await t.test("capture and inspect expose exact deeply frozen private metadata, not token JSON or extra authority", async () => {
|
|
const f = fixture(), expected = structuredClone(f.metadata)
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
const token = await capture(); assert.equal(f.calls(), 1); assert(Object.isFrozen(token)); assert.equal(Object.getPrototypeOf(token), null)
|
|
assert.equal(JSON.stringify(token), "{}"); assert.equal(Reflect.ownKeys(token).length, 0); assert(!JSON.stringify(token).includes("SYNTHETIC-PRIVATE-STEP"))
|
|
const value = await inspect(token); assert.equal(f.calls(), 2)
|
|
assert.deepEqual(value, { ...expected, ownerId: f.input.actorId, connectionId: f.input.connectionId, approved: false, serverWide: true, serverIds: [101, 102], objects: f.input.objects })
|
|
assert(Object.isFrozen(value)); assert(Object.isFrozen(value.principal)); assert(Object.isFrozen(value.serviceInput)); assert(Object.isFrozen(value.serviceInput.command)); assert(Object.isFrozen(value.serverIds)); assert(Object.isFrozen(value.objects[0]))
|
|
assert.throws(() => { value.serviceInput.srcServerId = 999 })
|
|
assert.equal(Object.hasOwn(value, "ready"), false); assert.equal(Object.hasOwn(value, "enrollmentAllowed"), false)
|
|
})
|
|
})
|
|
await t.test("legacy contexts retain callbacks and returned effects but cannot capture an origin token", async () => {
|
|
const f = fixture(), { serviceExecution: _metadata, ...legacy } = f.input
|
|
let effects = 0
|
|
assert.equal(await withVerifiedConfigurationChange(legacy, async () => { effects++; await assertVerifiedConfigurationAccess(); await assert.rejects(capture()); return "old-result" }), "old-result")
|
|
assert.equal(effects, 1); assert.equal(f.calls(), 1); await assert.rejects(capture())
|
|
await assert.rejects(withVerifiedConfigurationChange(legacy, async () => { throw Error("original-effect-error") }), /original-effect-error/)
|
|
})
|
|
await t.test("copied, serialized and forged capabilities refuse without running original authorization", async () => {
|
|
const f = fixture()
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
const token = await capture(), before = f.calls()
|
|
for (const fake of [undefined, null, {}, { ...token }, JSON.parse(JSON.stringify(token)), { operationId: f.metadata.operationId }, Object.create(token)]) await assert.rejects(inspect(fake))
|
|
assert.equal(f.calls(), before); await inspect(token)
|
|
})
|
|
})
|
|
await t.test("concurrent equal-field contexts cannot transfer genuine tokens", async () => {
|
|
const f = fixture(), aReady = deferred(), bReady = deferred()
|
|
let a!: VerifiedMcpServiceExecution, b!: VerifiedMcpServiceExecution
|
|
await Promise.all([
|
|
withVerifiedConfigurationChange(f.input, async () => { a = await capture(); aReady.resolve(); await bReady.promise; await assert.rejects(inspect(b)); await inspect(a) }),
|
|
withVerifiedConfigurationChange(f.input, async () => { b = await capture(); bReady.resolve(); await aReady.promise; await assert.rejects(inspect(a)); await inspect(b) }),
|
|
])
|
|
await assert.rejects(inspect(a)); await assert.rejects(inspect(b))
|
|
})
|
|
await t.test("scope exit invalidates detached continuations and later equal/approved contexts", async () => {
|
|
const f = fixture(), later = deferred(); let token!: VerifiedMcpServiceExecution, detached!: Promise<void>
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
token = await capture()
|
|
detached = (async () => { await later.promise; await assert.rejects(inspect(token)); await assert.rejects(capture()) })()
|
|
})
|
|
await assert.rejects(inspect(token)); later.resolve(); await detached
|
|
for (const approved of [false, true]) await withVerifiedConfigurationChange({ ...f.input, approved }, async () => { await assert.rejects(inspect(token)); await inspect(await capture()) })
|
|
})
|
|
await t.test("fresh authorization rejection or revoke during async authorization cannot mint/inspect", async () => {
|
|
for (const phase of ["capture", "inspect"] as const) {
|
|
const f = fixture(), entered = deferred(), gate = deferred()
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
const token = phase === "inspect" ? await capture() : undefined
|
|
f.onAuthorize(async () => { entered.resolve(); await gate.promise })
|
|
const pending = phase === "capture" ? capture() : inspect(token), rejected = assert.rejects(pending)
|
|
await entered.promise; f.revoke(); gate.resolve(); await rejected
|
|
})
|
|
}
|
|
const f = fixture(); f.revoke(); await withVerifiedConfigurationChange(f.input, async () => { await assert.rejects(capture(), /revoked/) })
|
|
})
|
|
await t.test("stalled authorization completing after owning scope ends cannot mint or inspect a token", async () => {
|
|
for (const phase of ["capture", "inspect"] as const) {
|
|
const f = fixture(), entered = deferred(), gate = deferred(); let rejected!: Promise<void>
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
const token = phase === "inspect" ? await capture() : undefined
|
|
f.onAuthorize(async () => { entered.resolve(); await gate.promise })
|
|
rejected = assert.rejects(phase === "capture" ? capture() : inspect(token)); await entered.promise
|
|
})
|
|
gate.resolve(); await rejected
|
|
}
|
|
})
|
|
await t.test("caller mutation of principal/service input/metadata cannot rewrite the captured original", async () => {
|
|
const f = fixture(), expected = structuredClone(f.metadata)
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
f.metadata.principal.credentialId = randomUUID(); f.metadata.principal.credentialExpiresAt = new Date(Date.now() + 600000).toISOString()
|
|
f.metadata.operationId = randomUUID(); f.metadata.originalExpiresAt += 600000
|
|
const command = f.metadata.serviceInput.command as { body: { password: string } }; command.body.password = "MUTATED"
|
|
f.metadata.serviceInput.list = []; f.input.serviceExecution = fixture().metadata; f.input.approved = true
|
|
const value = await inspect(await capture())
|
|
assert.equal(value.operationId, expected.operationId); assert.deepEqual(value.principal, expected.principal); assert.deepEqual(value.serviceInput, expected.serviceInput)
|
|
assert.equal(value.originalExpiresAt, expected.originalExpiresAt); assert.equal(value.approved, false)
|
|
})
|
|
})
|
|
await t.test("mutating referenced server/protection closure denies rather than broadening scope", async () => {
|
|
for (const mutate of [(f: ReturnType<typeof fixture>) => f.input.serverIds.push(999), (f: ReturnType<typeof fixture>) => { f.input.objects[0].id = "999" }, (f: ReturnType<typeof fixture>) => { f.input.objects[0].serverId = 999 }]) {
|
|
const f = fixture()
|
|
await withVerifiedConfigurationChange(f.input, async () => { const token = await capture(); mutate(f); await assert.rejects(inspect(token)); await assert.rejects(capture()) })
|
|
}
|
|
const f = fixture()
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
const original = await capture()
|
|
await withVerifiedConfigurationChange({ ...f.input, approved: true }, async () => { await assert.rejects(inspect(original)); assert.equal((await inspect(await capture())).approved, true) })
|
|
assert.equal((await inspect(original)).approved, false)
|
|
})
|
|
})
|
|
await t.test("original wall expiry cannot be renewed by later input changes", async () => {
|
|
const f = fixture(35)
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
const token = await capture(); f.metadata.originalExpiresAt = Date.now() + 600000
|
|
await delay(55); await assert.rejects(inspect(token)); await assert.rejects(capture())
|
|
})
|
|
})
|
|
await t.test("monotonic original expiry survives a backwards wall clock jump", async () => {
|
|
const f = fixture(35), originalNow = Date.now, baseline = Date.now()
|
|
await withVerifiedConfigurationChange(f.input, async () => {
|
|
const token = await capture()
|
|
try { Date.now = () => baseline - 60000; await delay(55); await assert.rejects(inspect(token)); await assert.rejects(capture()) }
|
|
finally { Date.now = originalNow }
|
|
})
|
|
})
|
|
await t.test("malformed runtime metadata and missing authorizer cannot issue capabilities", async () => {
|
|
const mutations: Array<(m: VerifiedMcpServiceMetadata) => void> = [m => { m.operationId = "model-id" }, m => { m.principal.connectionId = randomUUID() }, m => { m.originalExpiresAt = Date.parse(m.principal.credentialExpiresAt) + 1 },
|
|
m => { m.originalTemporaryGrantProof = "" }, m => { m.originalTemporaryGrantExpiresAt = m.originalExpiresAt - 1 },
|
|
m => { m.stepIndex = -1 }, m => { m.operationVersion = 0 }, m => { m.policyVersion = 0 }, m => { m.generation = "bad\nvalue" }, m => { m.phase = "recovery" as "forward" }, m => { m.principal.credentialExpiresAt = "invalid" }]
|
|
for (const mutate of mutations) { const f = fixture(); mutate(f.metadata); await withVerifiedConfigurationChange(f.input, async () => { await assert.rejects(capture()) }) }
|
|
const f = fixture(); await withVerifiedConfigurationChange({ ...f.input, authorize: undefined }, async () => { await assert.rejects(capture()) })
|
|
})
|
|
assert.equal(sqlCalls, 0)
|
|
console.log("MCP service origin token: 12 groups; same-active-ALS, exact immutable original, fresh authorization and original monotonic expiry; 0 SQL/0 native calls; no bandwidth/enrollment authority")
|
|
} finally { pool.query = originalQuery; pool.connect = originalConnect; await closePool() }
|
|
})
|