139 lines
12 KiB
TypeScript
139 lines
12 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { performance } from "node:perf_hooks"
|
|
import { test } from "node:test"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import type { PoolClient } from "pg"
|
|
import { pool, closePool } from "../../db/index.js"
|
|
import { readMcpTemporaryGrantOrigin as read, assertOriginalMcpTemporaryGrant as check, type OriginalServiceGrant } from "./temporary-grant-origin.js"
|
|
|
|
type Sql = Pick<PoolClient, "query">
|
|
const connectionId = randomUUID(), credentialId = randomUUID()
|
|
const denied = (error: unknown) => !!error && typeof error === "object" && "code" in error && error.code === "GRANT_INACTIVE"
|
|
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done }); return { promise, resolve } }
|
|
function row() {
|
|
return { id: randomUUID(), payload: { credentialId, id: "original-grant", startsAt: new Date(Date.now() - 1000).toISOString(), expiresAt: new Date(Date.now() + 10000).toISOString(), scope: { serverIds: [101, 102], operationIds: ["diagnostics.bandwidth"], allowGlobal: false } } }
|
|
}
|
|
function fixture(initial: unknown[] = [row()]) {
|
|
let rows = initial, hook: (() => Promise<void>) | undefined
|
|
const calls: Array<{ text: string; values: unknown[] }> = []
|
|
const sql = { async query(text: string, values: unknown[]) { calls.push({ text, values }); if (hook) await hook(); return { rows } } } as unknown as Sql
|
|
return { sql, calls, replace: (next: unknown[]) => { rows = next }, stall: (work: () => Promise<void>) => { hook = work } }
|
|
}
|
|
const pin = (value: Awaited<ReturnType<typeof read>>, admissionBudgetMs = 5000): OriginalServiceGrant => {
|
|
const wall = Date.now(), monotonic = performance.now(), admissionExpiresAt = Math.min(wall + admissionBudgetMs, value.expiresAt ?? Infinity)
|
|
return Object.freeze({ ...value, monotonicEnd: value.expiresAt === null ? Infinity : monotonic + Math.max(0, value.expiresAt - wall),
|
|
admissionExpiresAt, admissionMonotonicEnd: monotonic + Math.max(0, admissionExpiresAt - wall) })
|
|
}
|
|
|
|
test("temporary grant origin read/check contract, fake read-only SQL only", async t => {
|
|
const originalQuery = pool.query, originalConnect = pool.connect
|
|
let realSqlCalls = 0
|
|
pool.query = (() => { realSqlCalls++; throw Error("Grant-origin unit cannot use default SQL") }) as never
|
|
pool.connect = (() => { realSqlCalls++; throw Error("Grant-origin unit cannot acquire a backend") }) as never
|
|
try {
|
|
await t.test("bounded parameterized read authenticates physical row plus validated descriptor", async () => {
|
|
const original = row(), f = fixture([original]), first = await read(f.sql, connectionId, credentialId)
|
|
assert(Object.isFrozen(first)); assert.match(first.proof, /^[a-f0-9]{64}$/); assert.equal(first.expiresAt, Date.parse(original.payload.expiresAt))
|
|
assert.deepEqual(await read(f.sql, connectionId, credentialId), first)
|
|
const call = f.calls[0]; assert.deepEqual(call.values, [connectionId, credentialId]); assert(!call.text.includes(connectionId)); assert(!call.text.includes(credentialId))
|
|
assert.match(call.text, /^SELECT\b/); assert.match(call.text, /FROM public\.mcp_grants\b/); assert.match(call.text, /revoked_at IS NULL/); assert.match(call.text, /LIMIT 2$/)
|
|
assert.match(call.text, /octet_length\(payload::text\)<=1048576/); assert(!/\b(?:UPDATE|INSERT|DELETE|LOCK|FOR|CALL)\b|;/i.test(call.text))
|
|
f.replace([{ ...original, id: randomUUID() }]); assert.notEqual((await read(f.sql, connectionId, credentialId)).proof, first.proof, "new physical row cannot reuse descriptor proof")
|
|
for (const payload of [{ ...original.payload, id: "replacement-descriptor" }, { ...original.payload, expiresAt: new Date(Date.parse(original.payload.expiresAt) + 1000).toISOString() }, { ...original.payload, scope: { ...original.payload.scope, serverIds: [101] } }]) {
|
|
f.replace([{ ...original, payload }]); assert.notEqual((await read(f.sql, connectionId, credentialId)).proof, first.proof)
|
|
}
|
|
})
|
|
await t.test("absence is an immutable credential-bound original state, never an active grant", async () => {
|
|
const f = fixture([]), absent = await read(f.sql, connectionId, credentialId), original = pin(absent)
|
|
assert(Object.isFrozen(absent)); assert.equal(absent.expiresAt, null); assert.match(absent.proof, /^[a-f0-9]{64}$/)
|
|
await check(f.sql, connectionId, credentialId, original)
|
|
assert.notEqual((await read(f.sql, connectionId, randomUUID())).proof, absent.proof)
|
|
f.replace([row()]); await assert.rejects(check(f.sql, connectionId, credentialId, original), denied)
|
|
const active = pin(await read(f.sql, connectionId, credentialId)); f.replace([]); await assert.rejects(check(f.sql, connectionId, credentialId, active), denied)
|
|
})
|
|
await t.test("expired, future, ambiguous, oversized-null and malformed records refuse", async () => {
|
|
const original = row()
|
|
const invalid: unknown[][] = [
|
|
[original, original], [{ ...original, payload: null }], [{ ...original, payload: undefined }], [{ ...original, id: "chosen-row" }],
|
|
[{ ...original, payload: { ...original.payload, credentialId: randomUUID() } }],
|
|
[{ ...original, payload: { ...original.payload, startsAt: new Date(Date.now() - 2000).toISOString(), expiresAt: new Date(Date.now() - 1).toISOString() } }],
|
|
[{ ...original, payload: { ...original.payload, startsAt: new Date(Date.now() + 1000).toISOString() } }],
|
|
[{ ...original, payload: { ...original.payload, expiresAt: "invalid" } }],
|
|
[{ ...original, payload: { ...original.payload, expiresAt: new Date(Date.now() + 25 * 3600000).toISOString() } }],
|
|
[{ ...original, payload: { ...original.payload, unexpected: true } }],
|
|
[{ ...original, payload: { ...original.payload, scope: { ...original.payload.scope, serverIds: [101, 101] } } }],
|
|
[{ ...original, payload: { credentialId } }], [{ ...original, payload: [] }], [null],
|
|
]
|
|
// A null row is not a PostgreSQL row, so its generic adapter rejection is
|
|
// also checked without asserting the database-record error code.
|
|
for (const rows of invalid.slice(0, -1)) await assert.rejects(read(fixture(rows).sql, connectionId, credentialId), denied)
|
|
await assert.rejects(read(fixture([null]).sql, connectionId, credentialId))
|
|
})
|
|
await t.test("captured proof/expiry cannot be extended by later SQL payload mutation or row replacement", async () => {
|
|
const original = row(), f = fixture([original]), value = await read(f.sql, connectionId, credentialId), originalPin = pin(value), expected = structuredClone(value)
|
|
original.payload.expiresAt = new Date(Date.now() + 100000).toISOString(); original.payload.scope.serverIds.push(999)
|
|
assert.deepEqual(value, expected); assert.equal(originalPin.expiresAt, expected.expiresAt); assert.throws(() => { (value as { expiresAt: number }).expiresAt += 100000 })
|
|
await assert.rejects(check(f.sql, connectionId, credentialId, originalPin), denied)
|
|
f.replace([{ ...row(), payload: { ...original.payload, expiresAt: new Date(expected.expiresAt!).toISOString(), scope: { ...original.payload.scope, serverIds: [101, 102] } } }])
|
|
await assert.rejects(check(f.sql, connectionId, credentialId, originalPin), denied)
|
|
})
|
|
await t.test("missing or already expired original pin refuses before any SQL; valid exact original passes", async () => {
|
|
const f = fixture(), original = pin(await read(f.sql, connectionId, credentialId)), count = f.calls.length
|
|
await assert.rejects(check(f.sql, connectionId, credentialId, undefined), denied)
|
|
await assert.rejects(check(f.sql, connectionId, credentialId, Object.freeze({ ...original, expiresAt: Date.now() - 1 })), denied)
|
|
await assert.rejects(check(f.sql, connectionId, credentialId, Object.freeze({ ...original, monotonicEnd: performance.now() - 1 })), denied)
|
|
await assert.rejects(check(f.sql, connectionId, credentialId, Object.freeze({ ...original, admissionExpiresAt: Date.now() - 1 })), denied)
|
|
await assert.rejects(check(f.sql, connectionId, credentialId, Object.freeze({ ...original, admissionMonotonicEnd: performance.now() - 1 })), denied)
|
|
assert.equal(f.calls.length, count); await check(f.sql, connectionId, credentialId, original); assert.equal(f.calls.length, count + 1)
|
|
})
|
|
await t.test("monotonic expiry DURING stalled SQL refuses even when the wall clock rolls back", async () => {
|
|
const originalRow = row()
|
|
originalRow.payload.startsAt = new Date(Date.now() - 120000).toISOString()
|
|
originalRow.payload.expiresAt = new Date(Date.now() + 100).toISOString()
|
|
const f = fixture([originalRow]), captured = await read(f.sql, connectionId, credentialId), entered = deferred(), release = deferred()
|
|
// The real original grant expires while SQL is stalled. startsAt is older
|
|
// than the rollback too, so wall checks alone still accept the grant and
|
|
// cannot accidentally make this monotonic regression pass as "future".
|
|
const original = pin(captured), originalNow = Date.now, baseline = Date.now()
|
|
f.stall(async () => { entered.resolve(); await release.promise })
|
|
const rejected = assert.rejects(check(f.sql, connectionId, credentialId, original), denied)
|
|
try {
|
|
await entered.promise; Date.now = () => baseline - 60000; await delay(125)
|
|
assert.deepEqual(await read(fixture([originalRow]).sql, connectionId, credentialId), captured, "rolled-back wall clock alone still accepts the exact grant")
|
|
release.resolve(); await rejected
|
|
}
|
|
finally { Date.now = originalNow; release.resolve() }
|
|
assert.equal(f.calls.length, 2)
|
|
})
|
|
await t.test("absent grant still has finite admission expiry during stalled SQL; rollback and caller pin mutation cannot renew it", async () => {
|
|
const f = fixture([]), absent = await read(f.sql, connectionId, credentialId), original = { ...pin(absent, 100) }, entered = deferred(), release = deferred()
|
|
assert.equal(original.expiresAt, null); assert.equal(original.monotonicEnd, Infinity); assert(Number.isFinite(original.admissionMonotonicEnd))
|
|
const originalNow = Date.now, baseline = Date.now()
|
|
f.stall(async () => { entered.resolve(); await release.promise })
|
|
const rejected = assert.rejects(check(f.sql, connectionId, credentialId, original), denied)
|
|
try {
|
|
await entered.promise
|
|
// The helper must have captured the original admission before SQL.
|
|
// Mutating this caller-owned object cannot extend the pending check.
|
|
original.admissionExpiresAt += 600000; original.admissionMonotonicEnd += 600000
|
|
Date.now = () => baseline - 60000; await delay(125)
|
|
assert.deepEqual(await read(fixture([]).sql, connectionId, credentialId), absent, "absence still matches, so refusal must come from original admission lifetime")
|
|
release.resolve(); await rejected
|
|
} finally { Date.now = originalNow; release.resolve() }
|
|
assert.equal(f.calls.length, 2)
|
|
})
|
|
await t.test("wall expiry during SQL and descriptor drift after a stalled read refuse", async () => {
|
|
for (const fault of ["wall", "descriptor"] as const) {
|
|
const f = fixture(), original = pin(await read(f.sql, connectionId, credentialId)), entered = deferred(), release = deferred(), originalNow = Date.now
|
|
f.stall(async () => { entered.resolve(); await release.promise })
|
|
const rejected = assert.rejects(check(f.sql, connectionId, credentialId, original), denied)
|
|
try { await entered.promise; if (fault === "wall") Date.now = () => original.expiresAt! + 1; else f.replace([row()]); release.resolve(); await rejected }
|
|
finally { Date.now = originalNow; release.resolve() }
|
|
}
|
|
})
|
|
assert.equal(realSqlCalls, 0)
|
|
console.log("Temporary grant origin: 8 groups, fake read-only SQL only, 0 real DB/network calls")
|
|
} finally { pool.query = originalQuery; pool.connect = originalConnect; await closePool() }
|
|
})
|