Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(control-api): r1-l3 seed real membership in real-PG suites
Diego Zacarias16c4ee335315
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 7598627b7..5a1d149f9 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.745",+ "version": "0.1.746","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.745",+ "version": "0.1.746","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex d7791d50f..00003d11b 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.745",+ "version": "0.1.746","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/test/fixtures/contextAllowlist.ts b/control-api/test/fixtures/contextAllowlist.tsindex c4c635e63..e5b4fe4c0 100644--- a/control-api/test/fixtures/contextAllowlist.ts+++ b/control-api/test/fixtures/contextAllowlist.ts@@ -1,6 +1,10 @@import type { Mock } from 'vitest'+import { randomUUID } from 'node:crypto'import { config } from '../../src/config.js'+import type { DbClient } from '../../src/db.js'import { attachServerToContext } from '../../src/services/contextAllowlist.js'+import { setUserAgents } from '../../src/services/directory/agentAccess.js'+import { setUserContexts } from '../../src/services/directory/contextAccess.js'import type { MockGateway } from '../mockGateway.js'/**@@ -100,3 +104,38 @@ export function membership(return answered ? Promise.resolve(answered) : otherwise(sql, values)})}++/**+ * Real-Postgres seed: an active user whose direct Context and agent access is+ * written by the production writers (`setUserContexts`, `setUserAgents`), so+ * the readers the gates use run against the rows production writes. Only the+ * two direct tables are touched: a seed that also wrote team_contexts /+ * team_agents would hide a reader that wrongly counted team access.+ *+ * Requires the suite's db mock to route `pool` and `withTransaction` to the+ * test database. Returns the user id.+ */+export async function seedActiveMember(+ db: Pick<DbClient, 'query'>,+ access: { contexts?: string[]; agents?: string[] }+): Promise<string> {+ const operatorId = await seedControlAdmin(db)+ const created = await db.query(`INSERT INTO users (email) VALUES ($1) RETURNING id::text AS id`, [+ `member-${randomUUID()}@example.test`,+ ])+ const userId = String((created.rows[0] as { id: string }).id)+ if (access.contexts?.length) await setUserContexts(userId, access.contexts, operatorId)+ if (access.agents?.length) await setUserAgents(userId, access.agents, operatorId)+ return userId+}++/** Real-Postgres seed: an active control admin, usable as a writer's operator. */+export async function seedControlAdmin(db: Pick<DbClient, 'query'>): Promise<string> {+ const id = randomUUID()+ await db.query(+ `INSERT INTO control_admin_users (id, username, password_hash, role, status)+ VALUES ($1, $2, 'real-pg-fixture', 'admin', 'active')`,+ [id, `fixture-admin-${id}`]+ )+ return id+}diff --git a/control-api/test/oauth.perServerCallback.realPostgres.integration.test.ts b/control-api/test/oauth.perServerCallback.realPostgres.integration.test.tsindex d2e6b1aeb..94c968a13 100644--- a/control-api/test/oauth.perServerCallback.realPostgres.integration.test.ts+++ b/control-api/test/oauth.perServerCallback.realPostgres.integration.test.ts@@ -15,8 +15,10 @@* Real producers (T1): discovery by `discoverRemoteOAuth` over probe fixtures; CR,* uid, row and nonce by the real install route; the state by the real authorize-url* mint; teardown by the uninstall's own store call. The AS registration response and- * the token endpoint are the only external edges. Context membership is answered on the- * app pool as the sibling route suites do (it is not what this suite certifies).+ * the token endpoint are the only external edges. The consenting user is a real row whose+ * Context and agent access is written by the production writers (`seedActiveMember`), so+ * the per-user gate's readers run against real tables: a retired user, or one whose+ * access only comes through a team, is refused.** CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \* test/oauth.perServerCallback.realPostgres.integration.test.ts@@ -37,6 +39,11 @@ import {import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'import { attachServerToContext } from '../src/services/contextAllowlist.js'+import { setTeamAgents } from '../src/services/directory/agentAccess.js'+import { setTeamContexts } from '../src/services/directory/contextAccess.js'+import { createTeamForUser } from '../src/services/directory/teams.js'+import { retireDesktopUser } from '../src/services/directory/users.js'+import { seedActiveMember, seedAgentHost, seedControlAdmin } from './fixtures/contextAllowlist.js'import { discoverPilot, installRemoteServer, seedContext } from './fixtures/perServerInstall.js'import {ATLASSIAN_V2_PILOT,@@ -48,7 +55,6 @@ import { MockGateway } from './mockGateway.js'const testDb = vi.hoisted(() => ({pool: undefined as import('pg').Pool | undefined,- context: 'ctx-a',}))vi.mock('../src/db.js', async () => {@@ -60,14 +66,11 @@ vi.mock('../src/db.js', async () => {return {...actual,pool: {- query: (text: string, values?: unknown[]) => {- if (text.includes('FROM user_contexts')) {- return Promise.resolve({ rows: [{ context_id: testDb.context }], rowCount: 1 })- }- return current().query(text, values)- },+ query: (text: string, values?: unknown[]) => current().query(text, values),connect: () => current().connect(),},+ withTransaction: (work: Parameters<typeof actual.withTransaction>[0]) =>+ actual.withTransaction(work, current()),}})@@ -145,6 +148,7 @@ describeRealPostgres('per-server remote callback (real Postgres)', () => {let gateway: MockGatewaylet app: ReturnType<typeof createApp>let savedBaseUrl: string+ let memberId: stringbeforeAll(async () => {if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')@@ -181,6 +185,7 @@ describeRealPostgres('per-server remote callback (real Postgres)', () => {config.oauthCallbackBaseUrl = ORIGINgateway = new MockGateway(NS)await seedContext(gateway, NS, CONTEXT)+ memberId = await seedActiveMember(db, { contexts: [CONTEXT] })app = createApp(gateway as never)tokenEndpoint.posts.length = 0})@@ -208,13 +213,17 @@ describeRealPostgres('per-server remote callback (real Postgres)', () => {return { registered, reported: String(res.body.redirectUri) }}- /** The authorize URL the real mint returns; its state is what the AS round-trips. */- async function mint(name: string): Promise<{ redirectUri: string; state: string }> {- const res = await request(app)+ function mintRequest(name: string, userId: string) {+ return request(app).post('/api/v1/internal/mcp-oauth/authorize-url').set('Authorization', 'Bearer dev-rpc-proxy-token').set('x-service-token', 'rpc-proxy')- .send({ mcpServerName: name, userId: 'user-9' })+ .send({ mcpServerName: name, userId })+ }++ /** The authorize URL the real mint returns; its state is what the AS round-trips. */+ async function mint(name: string): Promise<{ redirectUri: string; state: string }> {+ const res = await mintRequest(name, memberId)if (res.status !== 200)throw new Error(`mint failed: ${res.status} ${JSON.stringify(res.body)}`)const url = new URL(res.body.authorizeUrl)@@ -347,7 +356,7 @@ describeRealPostgres('per-server remote callback (real Postgres)', () => {.post('/api/v1/internal/mcp-oauth/authorize-url').set('Authorization', 'Bearer dev-rpc-proxy-token').set('x-service-token', 'rpc-proxy')- .send({ mcpServerName: 'legacy', userId: 'user-9' })+ .send({ mcpServerName: 'legacy', userId: memberId })expect(mintRes.status).toBe(503)expect(mintRes.body).toMatchObject({ error: 'integration_not_configured' })@@ -416,6 +425,52 @@ describeRealPostgres('per-server remote callback (real Postgres)', () => {expect(tokenEndpoint.posts).toHaveLength(0)})+ // Per-user gate against the real membership tables: the readers' SQL, not a fake,+ // decides who reaches the Context that allowlists the server.+ it('per-user gate: a user reaching the Context only through an assigned agent mints', async () => {+ await installAtlassian('atlassian')+ await seedAgentHost(gateway, 'host-c', CONTEXT)+ const agentOnly = await seedActiveMember(db, { agents: ['host-c'] })+ const res = await mintRequest('atlassian', agentOnly)+ expect(res.status).toBe(200)+ expect(res.body.authorizeUrl).toEqual(expect.any(String))+ })++ it('per-user gate: a retired user is refused although their Context rows remain', async () => {+ await installAtlassian('atlassian')+ const retirer = await seedControlAdmin(db)+ await retireDesktopUser(+ { kind: 'control_admin', controlAdminId: retirer },+ memberId,+ 'real-pg per-user gate',+ `gate-${memberId}`,+ null,+ { retainWithoutLinkHistory: true }+ )+ const rows = await dbPool.query('SELECT context_id FROM user_contexts WHERE user_id = $1', [+ memberId,+ ])+ expect(rows.rows).toEqual([{ context_id: CONTEXT }])++ const res = await mintRequest('atlassian', memberId)+ expect(res.status).toBe(403)+ expect(res.body).toEqual({ error: 'context_membership_denied' })+ })++ it('per-user gate: access only through a team (team_contexts, team_agents) is refused', async () => {+ await installAtlassian('atlassian')+ await seedAgentHost(gateway, 'host-c', CONTEXT)+ const teamOnly = await seedActiveMember(db, {})+ const operator = await seedControlAdmin(db)+ const team = await createTeamForUser(teamOnly, `team-${teamOnly}`)+ await setTeamContexts(team.id, [CONTEXT], operator)+ await setTeamAgents(team.id, ['host-c'], operator)++ const res = await mintRequest('atlassian', teamOnly)+ expect(res.status).toBe(403)+ expect(res.body).toEqual({ error: 'context_membership_denied' })+ })+/*** A state for a server the mint refuses (no usable registration). Signed by the same* signer the mint uses, with the CR's current client id — what a state minted just@@ -429,7 +484,7 @@ describeRealPostgres('per-server remote callback (real Postgres)', () => {return signOAuthState(config.oauthStateHmacSecret, {subjectKind: 'mcp',mcpServerName: name,- userId: 'user-9',+ userId: memberId,oauthClientId: cr.spec.oauth.id,grantKind: 'user',background: false,diff --git a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts b/control-api/test/routes.registryUninstall.realPostgres.integration.test.tsindex 73da4a66a..a3ec58301 100644--- a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts+++ b/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts@@ -50,25 +50,22 @@ vi.mock('../src/services/registryClient.js', () => ({}))const dbHolder = vi.hoisted(() => ({- target: null as null | { query: (text: string, values?: unknown[]) => Promise<unknown> },+ pool: null as null | import('pg').Pool,}))vi.mock('../src/db.js', async importActual => {const actual = await importActual<typeof import('../src/db.js')>()+ const current = () => {+ if (!dbHolder.pool) throw new Error('test database not ready')+ return dbHolder.pool+ }return {...actual,pool: {- query: async (text: string, values?: unknown[]) => {- // The consenting user belongs to the Context the install enables the- // server in: the per-user callback re-checks that access before the- // code exchange. Same membership stand-in as the per-server callback- // suite.- if (text.includes('FROM user_contexts')) {- return { rows: [{ context_id: 'default-context' }], rowCount: 1 }- }- if (!dbHolder.target) throw new Error('test database not ready')- return dbHolder.target.query(text, values)- },+ query: async (text: string, values?: unknown[]) => current().query(text, values),+ connect: () => current().connect(),},+ withTransaction: (work: Parameters<typeof actual.withTransaction>[0]) =>+ actual.withTransaction(work, current()),}})@@ -82,6 +79,7 @@ const { createOAuthCallbackRouter } = await import('../src/routes/external/oauthconst { resolveBatchGrantExistence } = await import('../src/routes/mcpOauth.js')const { getCredentialSchema, getDigest, getEntryVersion, reportInstall } =await import('../src/services/registryClient.js')+const { seedActiveMember } = await import('./fixtures/contextAllowlist.js')const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skip@@ -94,7 +92,6 @@ function databaseUrl(baseUrl: string, database: string): string {const NS = 'mcp-server'const SERVER = 'my-gmail'-const USER = 'user-9'/** Baked-OAuth catalog entry, same shape as the registry OAuth install tests. */const GMAIL_ENTRY = {@@ -133,6 +130,9 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)let prevCallbackBase = ''let prevMcpNs = ''let prevContextsNs = ''+ // The consenting user: a real row whose Context access is written by the+ // production writer; the per-user callback re-checks it before the exchange.+ let user = ''beforeAll(async () => {if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')@@ -141,12 +141,12 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })await initDb({ connect: () => dbPool.connect() })db = { query: (text, values) => dbPool.query(text, values) }- dbHolder.target = db+ dbHolder.pool = dbPool})afterAll(async () => {try {- dbHolder.target = null+ dbHolder.pool = nullawait endPoolAndWaitForClients(dbPool)if (adminPool) {await adminPool.query(@@ -227,7 +227,7 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)subjectKind: 'mcp',mcpServerName: SERVER,oauthClientId: SERVER,- userId: USER,+ userId: user,grantKind: 'user',redirectUri: `https://control.example.com/api/v1/oauth-callback/${SERVER}`,},@@ -266,7 +266,7 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)const sweep = (gw: MockGateway) =>resolveBatchGrantExistence({ db, gateway: gw as unknown as K8sGateway, mcpServersNamespace: NS },- [{ mcpServerName: SERVER, userId: USER }]+ [{ mcpServerName: SERVER, userId: user }])it('a same-name reinstall starts with no connected user after a registry uninstall', async () => {@@ -276,12 +276,13 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)spec: { contextId: 'default-context', mcpServers: [] },})const app = makeApp(gw)+ user = await seedActiveMember(db, { contexts: ['default-context'] })expect((await install(app)).status).toBe(201)expect((await consent(app, gw)).status).toBe(200)// Precondition: the consent produced a connected user, visible to both readers.expect(await listUserGrantsForServer(db, { namespace: NS, name: SERVER })).toHaveLength(1)- expect(await sweep(gw)).toEqual([{ mcpServerName: SERVER, userId: USER, exists: true }])+ expect(await sweep(gw)).toEqual([{ mcpServerName: SERVER, userId: user, exists: true }])const uninstall = await request(app).delete(`/admin/registry/uninstall/${SERVER}`)expect(uninstall.status).toBe(200)@@ -289,6 +290,6 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)// The reinstall has the same oauth_client_id; no user may appear connected to it.expect(await listUserGrantsForServer(db, { namespace: NS, name: SERVER })).toEqual([])- expect(await sweep(gw)).toEqual([{ mcpServerName: SERVER, userId: USER, exists: false }])+ expect(await sweep(gw)).toEqual([{ mcpServerName: SERVER, userId: user, exists: false }])})})