Files
MikrotikManager/backend/src/modules/mcp/poll-runtime-policy-source.owned-helper.test.ts
T

65 lines
6.2 KiB
TypeScript

/** Called only by the guarded disposable principal-source SQL entry. */
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import type { Pool } from "pg"
import { mcpTemporaryGrantSchema } from "@mmapp/contracts/mcp"
import { pollRuntimePolicySql, readPollRuntimePolicySource } from "./poll-runtime-policy-source.js"
export async function checkOwnedPollPolicySource(pool: Pool, connectionId: string, credentialId: string) {
const protectionId = randomUUID(), grantId = randomUUID(), leaseId = randomUUID(), extraIds: string[] = []
const protection = { kind: "界".repeat(200), id: "測".repeat(200), serverId: 1, protection: "deny" }
const grant = mcpTemporaryGrantSchema.parse({ id: grantId, startsAt: new Date(Date.now() - 1000).toISOString(), expiresAt: new Date(Date.now() + 600000).toISOString(),
scope: { serverIds: [1], operationIds: Array.from({ length: 1000 }, (_, index) => String(index).padStart(4, "0") + "界".repeat(196)), allowGlobal: false } })
const owner = await pool.connect()
try {
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'owned-policy-source')", [protectionId, JSON.stringify(protection)])
await pool.query("INSERT INTO mcp_grants(id,connection_id,payload) VALUES($1,$2,$3::jsonb)", [grantId, connectionId, JSON.stringify({ ...grant, credentialId })])
await owner.query("BEGIN")
assert.equal((await owner.query("SHOW transaction_isolation")).rows[0].transaction_isolation, "read committed")
const clock = (await owner.query("SELECT now()::text AS clock,pg_backend_pid() AS pid")).rows[0]
await owner.query("INSERT INTO mcp_budget_buckets(connection_id,kind,bucket,used) VALUES($1,'calls',date_trunc('minute',now()),7),($1,'mutations',date_trunc('hour',now()),9)", [connectionId])
await owner.query("INSERT INTO mcp_read_leases(id,connection_id,expires_at) VALUES($1,$2,now()+interval '1 hour')", [leaseId, connectionId])
const first = await readPollRuntimePolicySource(owner, connectionId, credentialId)
assert.deepEqual(first.usage, { calls: 7, mutations: 9, reads: 1 })
assert.deepEqual(first.protections, [{ object_ref: protection }]); assert.deepEqual(first.temporaryGrant, grant)
// Execute the old independent reads against the same transaction clock.
assert.deepEqual(first.protections, (await owner.query("SELECT object_ref FROM mcp_protections LIMIT 1001")).rows)
const raw = (await owner.query("SELECT payload FROM mcp_grants WHERE connection_id=$1 AND revoked_at IS NULL AND payload->>'credentialId'=$2", [connectionId, credentialId])).rows[0].payload
delete raw.credentialId; assert.deepEqual(first.temporaryGrant, mcpTemporaryGrantSchema.parse(raw))
await pool.query("UPDATE mcp_protections SET object_ref=jsonb_set(object_ref,'{protection}','\"human-approval-required\"'::jsonb) WHERE id=$1", [protectionId])
await pool.query("UPDATE mcp_grants SET revoked_at=clock_timestamp() WHERE id=$1", [grantId])
const second = await readPollRuntimePolicySource(owner, connectionId, credentialId)
assert.equal(second.temporaryGrant, undefined); assert.equal(second.protections[0].object_ref.protection, "human-approval-required")
assert.deepEqual((await owner.query("SELECT now()::text AS clock,pg_backend_pid() AS pid")).rows[0], clock)
await owner.query("COMMIT")
// Separate owners and credentials cannot inherit another source's usage/grant.
const other = await readPollRuntimePolicySource(pool, randomUUID(), randomUUID())
assert.deepEqual(other.usage, { calls: 0, mutations: 0, reads: 0 }); assert.equal(other.temporaryGrant, undefined)
await pool.query("UPDATE mcp_grants SET revoked_at=NULL WHERE id=$1", [grantId])
const duplicate = randomUUID(); extraIds.push(duplicate)
await pool.query("INSERT INTO mcp_grants(id,connection_id,payload) SELECT $1,connection_id,payload FROM mcp_grants WHERE id=$2", [duplicate, grantId])
await assert.rejects(readPollRuntimePolicySource(pool, connectionId, credentialId), { code: "GRANT_INACTIVE" })
await pool.query("DELETE FROM mcp_grants WHERE id=$1", [duplicate])
await pool.query("UPDATE mcp_grants SET payload=payload||jsonb_build_object('opaque',repeat('x',1048577)) WHERE id=$1", [grantId])
const boundedGrant = (await pool.query(pollRuntimePolicySql, [connectionId, credentialId])).rows[0]
assert.equal(boundedGrant.grant_oversize, true); assert.deepEqual(boundedGrant.grants, [null])
await assert.rejects(readPollRuntimePolicySource(pool, connectionId, credentialId), { code: "GRANT_INACTIVE" })
await pool.query("UPDATE mcp_protections SET object_ref=jsonb_build_object('opaque',repeat('x',8193)) WHERE id=$1", [protectionId])
const boundedProtection = (await pool.query(pollRuntimePolicySql, [connectionId, credentialId])).rows[0]
assert.equal(boundedProtection.protection_oversize, true); assert.deepEqual(boundedProtection.protections, [null])
await assert.rejects(readPollRuntimePolicySource(pool, connectionId, credentialId), { code: "STATE_UNAVAILABLE" })
await pool.query("UPDATE mcp_protections SET object_ref=$2::jsonb WHERE id=$1", [protectionId, JSON.stringify(protection)])
for (let index = 0; index < 1000; index++) extraIds.push(randomUUID())
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) SELECT id,$2::jsonb,'owned-policy-source' FROM unnest($1::uuid[]) AS id", [extraIds.slice(1), JSON.stringify(protection)])
await assert.rejects(readPollRuntimePolicySource(pool, connectionId, credentialId), { code: "STATE_UNAVAILABLE" })
return { unicodeMaxProtectionAndGrant: true, actualTransactionClockAndBackendPreserved: true, independentCommittedChangesVisible: true,
noGrantOrUsageCrossConnection: true, ambiguityAndOversizeRefused: true, protectionOverflowRefused: true }
} finally {
await owner.query("ROLLBACK"); owner.release()
await pool.query("DELETE FROM mcp_protections WHERE id=ANY($1::uuid[])", [[protectionId, ...extraIds]])
await pool.query("DELETE FROM mcp_grants WHERE id=ANY($1::uuid[])", [[grantId, ...extraIds]])
await pool.query("DELETE FROM mcp_read_leases WHERE id=$1", [leaseId])
await pool.query("DELETE FROM mcp_budget_buckets WHERE connection_id=$1", [connectionId])
}
}