Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): audit revocation with actor and deleted-count (R1-M1)
Diego Zacarias514f716a8760
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 73cd7fa1f..ef2da0e91 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.507",+ "version": "0.1.508","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.507",+ "version": "0.1.508","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex 7e2fe6f5d..1d80aea3f 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.507",+ "version": "0.1.508","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.tsindex db19fc7bf..79639cb18 100644--- a/control-api/src/oauth/store.ts+++ b/control-api/src/oauth/store.ts@@ -521,32 +521,38 @@ export async function oauthGrantExists(db: DbClient, input: GetOAuthGrantInput):return result.rows.length > 0}-export async function deleteOAuthGrant(db: DbClient, input: GetOAuthGrantInput): Promise<void> {+/**+ * Delete a grant row by its flavored key. Returns the number of rows deleted so+ * callers can audit "did this actually revoke something" (0 ⇒ the grant was+ * already gone; the endpoint stays idempotent either way).+ */+export async function deleteOAuthGrant(db: DbClient, input: GetOAuthGrantInput): Promise<number> {const ownerKind = resolveOwnerKind(input)if (input.grantKind === 'user') {- await db.query(+ const result = await db.query(`DELETE FROM oauth_grantsWHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3AND user_id = $4 AND oauth_client_id = $5 AND grant_kind = 'user'`,[ownerKind, input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId])- return+ return result.rowCount ?? 0}if (input.grantKind === 'shared') {- await db.query(+ const result = await db.query(`DELETE FROM oauth_grantsWHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3AND user_id IS NULL AND context_id = $4 AND oauth_client_id = $5 AND grant_kind = 'shared'`,[ownerKind, input.recipeNamespace, input.recipeName, input.contextId, input.oauthClientId])- return+ return result.rowCount ?? 0}- await db.query(+ const result = await db.query(`DELETE FROM oauth_grantsWHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'`,[ownerKind, input.recipeNamespace, input.recipeName, input.oauthClientId])+ return result.rowCount ?? 0}/**diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.tsindex 886f9f910..9be233e67 100644--- a/control-api/src/routes/internal/oauth.ts+++ b/control-api/src/routes/internal/oauth.ts@@ -366,16 +366,25 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {return res.status(400).json({ error: 'server_missing_context' })}- await deleteOAuthGrant({ query: (text, values) => pool.query(text, values) }, key)+ const deletedRows = await deleteOAuthGrant(+ { query: (text, values) => pool.query(text, values) },+ key+ )// Audit trail (sensitive: a revocation). Structured, pino-redacted; no- // tokens/secrets are read or logged here.+ // tokens/secrets are read or logged here. `userId` is the acting+ // principal, `contextRef` the server's authoritative Context, and+ // `deleted` records whether a row was actually removed (false on an+ // idempotent no-op) so the audit trail is honest about what happened.req.log?.info({event: 'mcp_oauth_grant_revoked',mcpServerName,grantScope: resolved.grantScope,oauthClientId: resolved.oauthClientId,+ userId,+ contextRef: resolved.contextRef,+ deleted: deletedRows > 0,},'mcp oauth grant revoked')diff --git a/control-api/test/routes.internal.mcpOauthDisconnect.audit.test.ts b/control-api/test/routes.internal.mcpOauthDisconnect.audit.test.tsnew file mode 100644index 000000000..5db6ca891--- /dev/null+++ b/control-api/test/routes.internal.mcpOauthDisconnect.audit.test.ts@@ -0,0 +1,141 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import request from 'supertest'+import { createApp } from '../src/app.js'+import { config } from '../src/config.js'+import { rootLogger } from '../src/observability/logger.js'+import { MockGateway } from './mockGateway.js'++/**+ * R1-M1 — the revocation audit log must name the acting principal and record+ * whether a row was actually deleted. At the parent sha the+ * `mcp_oauth_grant_revoked` log carries neither `userId` nor `deleted`, and is+ * emitted even on a 0-row no-op with no way to tell. This test spies the+ * per-request child logger (`rootLogger.child`, the source of `req.log`) and+ * asserts the audit payload.+ */++const RPC_PROXY_TOKEN = 'dev-rpc-proxy-token'+const MCP_NS = config.mcpServersNamespace+const URL = '/api/v1/internal/mcp-oauth/grant'++const mockPoolQuery = vi.fn()+vi.mock('../src/db.js', () => ({+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },+}))++// Capture every `req.log.info(...)` call. `req.log` is `rootLogger.child(...)`,+// created per request AT RUNTIME — so a runtime spy on `rootLogger.child`+// intercepts it without disturbing the import-time module children.+const infoSpy = vi.fn()+const fakeChild = {+ info: infoSpy,+ error: vi.fn(),+ warn: vi.fn(),+ debug: vi.fn(),+ trace: vi.fn(),+ fatal: vi.fn(),+ child() {+ return fakeChild+ },+}++function seedOauthServer(+ gateway: MockGateway,+ opts: { name: string; grantScope?: 'user' | 'context'; contextRef?: string }+): void {+ void gateway.createResource(+ 'mcpservers',+ {+ metadata: { name: opts.name },+ spec: {+ contextRef: opts.contextRef ?? 'ctx-9',+ auth: { type: 'oauth' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ ...(opts.grantScope ? { grantScope: opts.grantScope } : {}),+ },+ },+ },+ MCP_NS+ )+}++function mockDb(opts: { memberContexts: string[]; deleteRowCount: number }): void {+ mockPoolQuery.mockImplementation((sql: unknown) => {+ const text = typeof sql === 'string' ? sql : ''+ if (text.includes('FROM user_contexts')) {+ return Promise.resolve({+ rows: opts.memberContexts.map(context_id => ({ context_id })),+ rowCount: opts.memberContexts.length,+ })+ }+ if (text.includes('DELETE FROM oauth_grants')) {+ return Promise.resolve({ rows: [], rowCount: opts.deleteRowCount })+ }+ return Promise.resolve({ rows: [], rowCount: 0 })+ })+}++function revokeAuditPayload(): Record<string, unknown> | undefined {+ const call = infoSpy.mock.calls.find(+ ([obj]) =>+ obj &&+ typeof obj === 'object' &&+ (obj as { event?: unknown }).event === 'mcp_oauth_grant_revoked'+ )+ return call?.[0] as Record<string, unknown> | undefined+}++function del(app: ReturnType<typeof createApp>) {+ return request(app)+ .delete(URL)+ .set('Authorization', `Bearer ${RPC_PROXY_TOKEN}`)+ .set('x-service-token', 'rpc-proxy')+}++describe('DELETE /internal/mcp-oauth/grant — revocation audit (R1-M1)', () => {+ let gateway: MockGateway+ let app: ReturnType<typeof createApp>+ let childSpy: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ gateway = new MockGateway(MCP_NS)+ app = createApp(gateway as never)+ mockPoolQuery.mockReset()+ infoSpy.mockReset()+ childSpy = vi.spyOn(rootLogger, 'child').mockReturnValue(fakeChild as never)+ })++ afterEach(() => {+ childSpy.mockRestore()+ })++ it('logs userId + contextRef + deleted:false on a 0-row (idempotent) revoke', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })+ mockDb({ memberContexts: ['ctx-9'], deleteRowCount: 0 })++ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-7' })+ expect(res.status).toBe(204)++ const payload = revokeAuditPayload()+ expect(payload).toBeDefined()+ expect(payload).toMatchObject({+ event: 'mcp_oauth_grant_revoked',+ userId: 'user-7',+ contextRef: 'ctx-9',+ deleted: false,+ })+ })++ it('records deleted:true when a row was actually removed', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })+ mockDb({ memberContexts: ['ctx-9'], deleteRowCount: 1 })++ await del(app).send({ mcpServerName: 'gdrive', userId: 'user-7' })++ expect(revokeAuditPayload()).toMatchObject({ userId: 'user-7', deleted: true })+ })+})