90 lines
6.7 KiB
TypeScript
90 lines
6.7 KiB
TypeScript
/** Component test: actual store validation/parser with fake SQL rows and an
|
|
* isolated real generation/revocation filesystem. No PostgreSQL or network. */
|
|
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { mkdtemp, rm } from "node:fs/promises"
|
|
import { join } from "node:path"
|
|
import { fileURLToPath } from "node:url"
|
|
import { test } from "node:test"
|
|
import type { PoolClient } from "pg"
|
|
import { mcpConnectionPolicySchema } from "@mmapp/contracts/mcp"
|
|
import { pool, closePool } from "../../db/index.js"
|
|
import { accessGeneration, fingerprint } from "./security.js"
|
|
import { effectiveMcpConnection, effectiveMcpConnectionSource, type ConnectionRow, type McpPrincipal } from "./store.js"
|
|
|
|
test("effective connection source reuses precisely the grant rows it validates; fake SQL component only", async t => {
|
|
const state = await mkdtemp(join(fileURLToPath(new URL("../../../../tmp/", import.meta.url)), "mm-mcp-grant-source-"))
|
|
const previousState = process.env.MCP_STATE_DIR, originalQuery = pool.query, originalConnect = pool.connect
|
|
process.env.MCP_STATE_DIR = state
|
|
pool.query = (() => { throw Error("Component must not use default SQL") }) as never
|
|
pool.connect = (() => { throw Error("Component must not acquire a backend") }) as never
|
|
try {
|
|
const generation = await accessGeneration(), now = Date.now()
|
|
const principal: McpPrincipal = { connectionId: randomUUID(), credentialId: randomUUID(), credentialExpiresAt: new Date(now + 60000).toISOString() }
|
|
const connection: ConnectionRow = { id: principal.connectionId, name: "component", owner_id: "owner", owner_permissions: ["mm:servers:write"], generation,
|
|
created_at: new Date(now), updated_at: new Date(now), last_used_at: null, owner_valid_until: new Date(now + 60000), owner_claims_issued_at: new Date(now - 1000),
|
|
policy: mcpConnectionPolicySchema.parse({ id: principal.connectionId, version: 1, status: "active", mode: "approval", dangerousPolicy: "approval", expiresAt: principal.credentialExpiresAt,
|
|
permissions: ["mm:servers:write"], scope: { serverIds: [1, 2], operationIds: ["servers.poll", "operations.global.reconcile"], allowGlobal: true },
|
|
limits: { callsPerMinute: 100, mutationsPerHour: 100, serversPerPlan: 100, objectsPerPlan: 100 } }) }
|
|
const grant = () => ({ payload: { credentialId: principal.credentialId, id: "source-grant", startsAt: new Date(now - 1000).toISOString(), expiresAt: new Date(now + 30000).toISOString(),
|
|
scope: { serverIds: [1], operationIds: ["servers.poll"], allowGlobal: false } } })
|
|
let rows: { payload: Record<string, unknown> }[] = [], active = true
|
|
const commands: string[] = []
|
|
const client = { async query(text: string, values: unknown[]) {
|
|
commands.push(text)
|
|
if (text.startsWith("/* mcp-principal:coherent-source-v1 */")) {
|
|
assert.deepEqual(values.slice(0, 2), [principal.credentialId, principal.connectionId])
|
|
const utc = (value: Date) => value.toISOString().replace(/(\.\d{3})Z$/, "$1000Z")
|
|
const core = { ...structuredClone(connection), __ps_exists: true, __ps_oversize: false, __ps_bytes: 4096, __ps_guard: true, __ps_isolation: "read committed",
|
|
__ps_credential: active ? principal.credentialId : null, __ps_credential_current: active, __ps_credential_expires: active ? utc(new Date(principal.credentialExpiresAt)) : null,
|
|
__ps_credential_revoked: null, __ps_owner_until: utc(connection.owner_valid_until), __ps_owner_issued: utc(connection.owner_claims_issued_at),
|
|
__ps_cutoff_owner: null, __ps_cutoff: null, __ps_cutoff_text: null, __ps_settings: 1, __ps_enabled: true, __ps_policy_sha256: fingerprint(connection.policy) }
|
|
return { rows: values[2] && rows.length ? rows.map((row, index) => ({ ...core, __ps_grant_id: "grant-row-" + index, __ps_grant_oversize: false, __ps_grant_payload: structuredClone(row.payload), __ps_grant_sha256: fingerprint(row.payload) }))
|
|
: [{ ...core, __ps_grant_id: null, __ps_grant_oversize: null, __ps_grant_payload: null, __ps_grant_sha256: null }] }
|
|
}
|
|
throw Error("Unexpected component SQL")
|
|
} } as unknown as Pick<PoolClient, "query">
|
|
const assertOneRead = (start: number) => {
|
|
const calls = commands.slice(start)
|
|
assert.equal(calls.length, 2)
|
|
assert(calls.every(text => text.startsWith("/* mcp-principal:coherent-source-v1 */")))
|
|
assert.match(calls.at(-1)!, /ORDER BY id LIMIT 2/)
|
|
}
|
|
await t.test("no grant retains ordinary connection; public delegate returns identical DTO", async () => {
|
|
let start = commands.length
|
|
const source = await effectiveMcpConnectionSource(principal, client)
|
|
assert.deepEqual(source.grantRows, []); assert.deepEqual(source.connection, connection); assertOneRead(start)
|
|
start = commands.length
|
|
assert.deepEqual(await effectiveMcpConnection(principal, client), source.connection); assertOneRead(start)
|
|
})
|
|
await t.test("single source preserves full raw descriptor while intersecting all scope dimensions", async () => {
|
|
rows = [grant()]; const start = commands.length
|
|
const source = await effectiveMcpConnectionSource(principal, client)
|
|
assert.deepEqual(source.grantRows, rows)
|
|
assert.deepEqual(source.connection.policy.scope, { serverIds: [1], operationIds: ["servers.poll"], allowGlobal: false })
|
|
assert.deepEqual(connection.policy.scope.serverIds, [1, 2]); assertOneRead(start)
|
|
})
|
|
await t.test("expired/future and duplicate source refuse, with exactly two coherent source queries", async () => {
|
|
for (const candidate of [
|
|
[{ payload: { ...grant().payload, startsAt: new Date(now - 2000).toISOString(), expiresAt: new Date(now - 1000).toISOString() } }],
|
|
[{ payload: { ...grant().payload, startsAt: new Date(now + 10000).toISOString() } }], [grant(), grant()],
|
|
]) {
|
|
rows = candidate; const start = commands.length
|
|
await assert.rejects(effectiveMcpConnectionSource(principal, client), { code: "GRANT_INACTIVE" }); assertOneRead(start)
|
|
}
|
|
})
|
|
await t.test("no source read survives revoked principal and no source result is cached", async () => {
|
|
rows = [grant()]; active = false; const start = commands.length
|
|
await assert.rejects(effectiveMcpConnectionSource(principal, client), { code: "UNAUTHORIZED" })
|
|
assert.equal(commands.slice(start).some(text => text.startsWith("SELECT payload")), false)
|
|
active = true; rows = []
|
|
assert.deepEqual((await effectiveMcpConnectionSource(principal, client)).grantRows, [])
|
|
})
|
|
} finally {
|
|
pool.query = originalQuery; pool.connect = originalConnect
|
|
if (previousState === undefined) delete process.env.MCP_STATE_DIR
|
|
else process.env.MCP_STATE_DIR = previousState
|
|
await closePool(); await rm(state, { recursive: true, force: true })
|
|
}
|
|
})
|