100 lines
9.7 KiB
TypeScript
100 lines
9.7 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { basename, dirname, resolve } from "node:path"
|
|
|
|
/** Read/lock acceptance of existing source + current grant components only.
|
|
* Does not import, execute or simulate the pending production host patch. */
|
|
export async function acceptDiagnosticCancellationSourceSql(serverId: number) {
|
|
assert.equal(process.env.MMAPP_OWN_PROBE_STORAGE_JOURNAL, "true")
|
|
const url = new URL(process.env.DATABASE_URL ?? "")
|
|
assert.equal(url.hostname, "127.0.0.1"); assert.equal(url.pathname, "/postgres")
|
|
assert(process.env.MCP_STATE_DIR && basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
|
|
const { pool } = await import("../../db/index.js")
|
|
const security = await import("./security.js")
|
|
const { effectiveMcpConnection } = await import("./store.js")
|
|
const { loadDiagnosticCancellationSource, readServerProbeExecutionSource } = await import("./diagnostic-cancellation-source.js")
|
|
const operationId = randomUUID(), connectionId = randomUUID(), originalCredentialId = randomUUID(), credentialId = randomUUID(), receiptId = randomUUID(), planId = randomUUID()
|
|
const ownerId = "owned-source-" + randomUUID(), at = Date.now(), oldExpiry = new Date(at - 3600000).toISOString(), until = new Date(at + 3600000).toISOString()
|
|
const principal = { connectionId, credentialId, credentialExpiresAt: until }
|
|
const policy = { id: connectionId, version: 1, status: "active", mode: "approval", permissions: ["mm:servers:write"], expiresAt: until, scope: { serverIds: [serverId], operationIds: ["servers.probes.run"], allowGlobal: false } }
|
|
const binding = { version: 1, operation: "servers.probes.run", principal: { connectionId, credentialId: originalCredentialId, credentialExpiresAt: oldExpiry }, ownerId, issuedAt: at - 7200000, authorityExpiresAt: Date.parse(oldExpiry), prepared: { receiptId, serverId, tool: "ping", expiresAt: oldExpiry, bindingCiphertext: await security.encryptSecret("owned synthetic provider request") }, bindingProof: "a".repeat(64), stageBudget: 2 }
|
|
const proof = (value: unknown) => security.privateSecretFingerprint(security.fingerprint(value), "server-probe-mcp-binding-v1")
|
|
const input = { receiptId, serverId, inputDigest: await proof(binding), bindingCiphertext: await security.encryptSecret(JSON.stringify(binding)) }
|
|
const step = { kind: "service", service: "servers.probes.run", input }
|
|
const evidence = { steps: [step], target: { scope: "servers", serverIds: [serverId] }, requiresHuman: true, verificationScope: "acknowledgement", mutationCost: 2, validUntil: oldExpiry }
|
|
const sealedEvidence = { sealed: await security.encryptSecret(JSON.stringify(evidence)) }
|
|
const generation = await security.accessGeneration()
|
|
const previousEnabled = (await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled
|
|
const cases: string[] = []
|
|
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
|
|
try {
|
|
await pool.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,'owned source acceptance',$2,$3::jsonb,$4::jsonb,$5,$6,clock_timestamp())", [connectionId, ownerId, JSON.stringify(policy.permissions), JSON.stringify(policy), generation, until])
|
|
for (const [id, expiry] of [[originalCredentialId, oldExpiry], [credentialId, until]]) await pool.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [id, connectionId, randomUUID(), expiry])
|
|
await pool.query("INSERT INTO mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at,approved_by) VALUES($1,$2,'servers.probes.run',1,1,$3,'{}',$4::jsonb,'executing',$5,$6)", [planId, connectionId, generation, JSON.stringify(sealedEvidence), oldExpiry, ownerId])
|
|
await pool.query("INSERT INTO mcp_operations(id,plan_id,connection_id,idempotency_key,state) VALUES($1,$2,$3,$4,'pending')", [operationId, planId, connectionId, randomUUID()])
|
|
const read = async () => {
|
|
const client = await pool.connect()
|
|
try {
|
|
await client.query("BEGIN"); await client.query("SET LOCAL statement_timeout='2000ms'")
|
|
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('server-probe-storage-v2',0))")
|
|
return await loadDiagnosticCancellationSource(client, operationId, { connectionId, ownerId })
|
|
} finally { await client.query("ROLLBACK"); client.release(true) }
|
|
}
|
|
const snapshotRead = async () => {
|
|
const client = await pool.connect()
|
|
try {
|
|
await client.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
|
await client.query("SET LOCAL statement_timeout='2000ms'")
|
|
const result = await readServerProbeExecutionSource(client, operationId, { connectionId, ownerId })
|
|
const settings = (await client.query("SELECT current_setting('transaction_read_only') AS read_only, current_setting('transaction_isolation') AS isolation")).rows[0]
|
|
assert.equal(settings.read_only, "on"); assert.equal(settings.isolation, "repeatable read")
|
|
assert(Object.isFrozen(result) && Object.isFrozen(result.originalContext) && Object.isFrozen(result.originalContext.identity))
|
|
return result
|
|
} finally { await client.query("ROLLBACK"); client.release(true) }
|
|
}
|
|
const source = await read()
|
|
const snapshotSource = await snapshotRead()
|
|
const { originalContext, ...historicalSource } = snapshotSource
|
|
assert.deepEqual(historicalSource, source)
|
|
assert.equal(originalContext.identity.executionId, operationId)
|
|
assert.equal(originalContext.identity.expiresAt, Date.parse(oldExpiry))
|
|
assert.equal(originalContext.identity.kind, "mcp")
|
|
cases.push("actual REPEATABLE READ READ ONLY snapshot authenticates original expired context without row locks; locked source digest parity")
|
|
assert.equal(source.scope.receiptId, receiptId); assert.equal(source.scope.authorityExpiresAt, oldExpiry)
|
|
assert.equal(source.originalCredentialId, originalCredentialId); assert.equal(source.sourceState, "pending"); assert.equal(source.terminal, false)
|
|
assert.equal((await effectiveMcpConnection(principal)).owner_id, ownerId)
|
|
await assert.rejects(effectiveMcpConnection({ ...principal, credentialId: originalCredentialId, credentialExpiresAt: oldExpiry }))
|
|
cases.push("actual encrypted pending source with no step preserves expired original credential while independent current credential validates")
|
|
await pool.query("UPDATE mcp_operations SET state='running' WHERE id=$1", [operationId])
|
|
await pool.query("INSERT INTO mcp_operation_steps(operation_id,step_index,state,intended_state) VALUES($1,0,'intent',$2::jsonb)", [operationId, JSON.stringify(security.redact(step))])
|
|
assert.equal((await read()).sourceState, "running")
|
|
cases.push("actual running operation requires exact intent step and source is loaded under owned SQL row locks")
|
|
await pool.query("UPDATE mcp_operation_steps SET intended_state='{}'::jsonb WHERE operation_id=$1", [operationId])
|
|
await assert.rejects(read()); await assert.rejects(snapshotRead())
|
|
await pool.query("UPDATE mcp_operation_steps SET intended_state=$2::jsonb WHERE operation_id=$1", [operationId, JSON.stringify(security.redact(step))])
|
|
cases.push("actual intended step drift refuses authenticated source")
|
|
await pool.query("UPDATE mcp_plans SET operation_version=2 WHERE id=$1", [planId]); await assert.rejects(read())
|
|
await pool.query("UPDATE mcp_plans SET operation_version=1 WHERE id=$1", [planId])
|
|
cases.push("actual operation version drift refuses source")
|
|
const forged = { ...evidence, steps: [{ ...step, input: { ...input, inputDigest: "b".repeat(64) } }] }
|
|
await pool.query("UPDATE mcp_plans SET evidence=$2::jsonb WHERE id=$1", [planId, JSON.stringify({ sealed: await security.encryptSecret(JSON.stringify(forged)) })]); await assert.rejects(read())
|
|
await pool.query("UPDATE mcp_plans SET evidence=$2::jsonb WHERE id=$1", [planId, JSON.stringify(sealedEvidence)])
|
|
cases.push("actual encrypted evidence with forged keyed input digest refuses source")
|
|
for (const state of ["rejected", "partial", "applied", "unknown", "failed", "cancelled"]) {
|
|
await pool.query("UPDATE mcp_operations SET state=$2 WHERE id=$1", [operationId, state])
|
|
await pool.query("UPDATE mcp_plans SET state='completed' WHERE id=$1", [planId])
|
|
const terminal = await read(); assert.equal(terminal.terminal, true); assert.equal(terminal.sourceState, state)
|
|
}
|
|
cases.push("actual runner terminal states including rejected and partial are recognized as non-executable terminal sources")
|
|
const grantId = randomUUID()
|
|
await pool.query("INSERT INTO mcp_grants(id,connection_id,payload) VALUES($1,$2,$3::jsonb)", [grantId, connectionId, JSON.stringify({ id: grantId, credentialId, startsAt: new Date(at - 1000).toISOString(), expiresAt: until, scope: { serverIds: [], operationIds: ["servers.probes.run"], allowGlobal: false } })])
|
|
assert.deepEqual((await effectiveMcpConnection(principal)).policy.scope.serverIds, [])
|
|
assert.deepEqual((await read()).serverIds, [serverId])
|
|
cases.push("actual temporary grant narrows current authority independently of unchanged original source scope")
|
|
await pool.query("UPDATE mcp_credentials SET revoked_at=clock_timestamp() WHERE id=$1", [credentialId])
|
|
await assert.rejects(effectiveMcpConnection(principal))
|
|
cases.push("actual current credential revocation refuses grant validation without rewriting source")
|
|
return { cases, actualSql: true, productionCrypto: true, syntheticOriginalExecution: true, productionHostExecuted: false, cancellationsWritten: 0, nativeCalls: 0 }
|
|
} finally { await pool.query("UPDATE mcp_settings SET enabled=$1 WHERE id=1", [previousEnabled]) }
|
|
}
|