Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(oauth): validate remote callback iss against pinned issuer (H-1)
Diego Zacarias0c8d0fba1a80
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 900dc4ee9..6ae781fe2 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.592",+ "version": "0.1.594","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.592",+ "version": "0.1.594","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 68e2a3c02..5b35eb47d 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.593",+ "version": "0.1.594","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/__tests__/callbackRemoteIss.test.ts b/control-api/src/oauth/__tests__/callbackRemoteIss.test.tsnew file mode 100644index 000000000..e6fe861bd--- /dev/null+++ b/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it, vi } from 'vitest'+import type { PinnedRawResponse, PinnedTransport } from '../../http/pinnedFetch.js'+import type { DnsResolver } from '../../http/validateMcpServerSpec.js'+import {+ type CallbackDeps,+ type CallbackInput,+ type McpServerOAuthSubject,+ REMOTE_CALLBACK_CLIENT_SEGMENT,+ handleOAuthCallback,+} from '../callback.js'+// State is derived from the REAL producer (T1): never hand-write the signed+// wire format. `signOAuthState` is the same signer the authorize-URL path uses.+import { signOAuthState } from '../state.js'++/**+ * RFC 9207 issuer validation on the remote OAuth lane (H-1).+ *+ * The remote AS issuer is discovered and pinned on the McpServer CR+ * (`spec.oauth.issForCallback`), surfaced as `subject.decl.remote.issForCallback`.+ * The callback must read the authorization-response `iss` (`input.iss`) and, when+ * an issuer was advertised, require an exact match BEFORE the single-use auth-code+ * is exchanged — the AS mix-up defence. When no issuer was advertised the check is+ * skipped (fail-open by absence of producer data). These tests pin the observable+ * outcome (T4): a mismatch/absent `iss` short-circuits to `issuer_mismatch` with no+ * exchange and no persist; a match (or a not-advertised issuer) exchanges normally.+ */++const STATE_SECRET = 'test-state-secret-0123456789abcdef' // ≥ 32 chars+const ENCRYPTION_KEY = Buffer.alloc(32, 7) // AES-256-GCM key++const OAUTH_CLIENT_ID = 'remote-client'+const MCP_SERVER_NAME = 'remote-gdrive'+const USER_ID = 'user-42'+const ADVERTISED_ISS = 'https://as.example.test'+const TOKEN_ENDPOINT = 'https://as.example.test/token'+const AUTHORIZE_ENDPOINT = 'https://as.example.test/authorize'++/** A REMOTE (discovery-derived) OAuth subject. `public` secretSource ⇒ no Secret read. */+function remoteSubject(+ overrides: {+ issForCallback?: string+ } = {}+): McpServerOAuthSubject {+ return {+ namespace: 'mcp-servers',+ grantScope: 'user',+ decl: {+ id: OAUTH_CLIENT_ID,+ provider: 'remote',+ remote: {+ authorizationEndpoint: AUTHORIZE_ENDPOINT,+ tokenEndpoint: TOKEN_ENDPOINT,+ clientMode: 'public',+ bearerInBody: false,+ supportsRefresh: true,+ // Present iff advertised; `undefined` models an AS that did not carry `iss`.+ ...('issForCallback' in overrides ? { issForCallback: overrides.issForCallback } : {}),+ },+ secretSource: { kind: 'public' },+ },+ }+}++function signedMcpState(): string {+ return signOAuthState(STATE_SECRET, {+ subjectKind: 'mcp',+ mcpServerName: MCP_SERVER_NAME,+ userId: USER_ID,+ oauthClientId: OAUTH_CLIENT_ID,+ grantKind: 'user',+ background: false,+ })+}++function input(overrides: Partial<CallbackInput> = {}): CallbackInput {+ return {+ // Stable remote callback: the URL segment is the reserved constant, the real+ // client id rides the signed state.+ oauthClientId: REMOTE_CALLBACK_CLIENT_SEGMENT,+ code: 'auth-code-single-use',+ state: signedMcpState(),+ redirectUri: 'https://callback.example.test/api/v1/oauth-callback/remote',+ ...overrides,+ }+}++/** A pinned transport that returns a valid token response if the exchange is reached. */+function okPinnedTransport(): PinnedTransport {+ return vi.fn(+ async (): Promise<PinnedRawResponse> => ({+ status: 200,+ headers: { 'content-type': 'application/json' },+ bodyText: JSON.stringify({+ access_token: 'at',+ refresh_token: 'rt',+ expires_in: 3600,+ token_type: 'Bearer',+ }),+ })+ )+}++/** Fixed public IPv4 so the token endpoint host passes the SSRF kernel. */+function publicResolveDns(): DnsResolver {+ return vi.fn(async () => ['93.184.216.34'])+}++function buildDeps(+ opts: {+ subject?: McpServerOAuthSubject+ pinnedTransport?: PinnedTransport+ resolveDns?: DnsResolver+ db?: CallbackDeps['db']+ } = {}+): CallbackDeps {+ const db =+ opts.db ??+ ({+ query: vi.fn(async () => ({ rowCount: 1, rows: [{ id: 'grant-1' }] })),+ } as unknown as CallbackDeps['db'])+ return {+ db,+ recipeReader: { read: vi.fn(async () => null) },+ secretReader: {+ // Public client ⇒ never read; a call here would be a regression.+ read: vi.fn(async () => ({}) as Record<string, string>),+ } as unknown as CallbackDeps['secretReader'],+ mcpServerReader: { read: vi.fn(async () => opts.subject ?? remoteSubject()) },+ // Remote lane never touches globalThis fetch (DEC-17); a call is a regression.+ fetchFn: vi.fn() as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey: ENCRYPTION_KEY,+ resolveDns: opts.resolveDns ?? publicResolveDns(),+ pinnedTransport: opts.pinnedTransport ?? okPinnedTransport(),+ }+}++describe('handleOAuthCallback — remote lane RFC 9207 iss validation (H-1)', () => {+ it('rejects a mismatched iss WITHOUT exchanging the auth-code or persisting', async () => {+ const pinnedTransport = okPinnedTransport()+ const deps = buildDeps({+ subject: remoteSubject({ issForCallback: ADVERTISED_ISS }),+ pinnedTransport,+ })++ const result = await handleOAuthCallback(input({ iss: 'https://evil.example.test' }), deps)++ // Observable outcome (T4).+ expect(result.kind).toBe('issuer_mismatch')+ // The single-use code is NOT burned and nothing is persisted.+ expect(pinnedTransport).not.toHaveBeenCalled()+ expect(deps.db.query as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()+ })++ it('rejects an absent iss when an issuer was advertised (fail closed)', async () => {+ const pinnedTransport = okPinnedTransport()+ const deps = buildDeps({+ subject: remoteSubject({ issForCallback: ADVERTISED_ISS }),+ pinnedTransport,+ })++ const result = await handleOAuthCallback(input({ iss: undefined }), deps)++ expect(result.kind).toBe('issuer_mismatch')+ expect(pinnedTransport).not.toHaveBeenCalled()+ expect(deps.db.query as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()+ })++ it('accepts a matching iss: exchange runs once and the grant is persisted', async () => {+ const pinnedTransport = okPinnedTransport()+ const deps = buildDeps({+ subject: remoteSubject({ issForCallback: ADVERTISED_ISS }),+ pinnedTransport,+ })++ const result = await handleOAuthCallback(input({ iss: ADVERTISED_ISS }), deps)++ expect(result.kind).toBe('ok')+ expect(pinnedTransport).toHaveBeenCalledTimes(1)+ const query = deps.db.query as ReturnType<typeof vi.fn>+ expect(query).toHaveBeenCalledTimes(1)+ expect(String(query.mock.calls[0][0])).toContain('INSERT INTO oauth_grants')+ })++ it('skips the check when no issuer was advertised: exchange proceeds', async () => {+ const pinnedTransport = okPinnedTransport()+ // Subject WITHOUT issForCallback (AS did not advertise `iss`) + absent input.iss.+ const deps = buildDeps({+ subject: remoteSubject(),+ pinnedTransport,+ })++ const result = await handleOAuthCallback(input({ iss: undefined }), deps)++ expect(result.kind).toBe('ok')+ expect(pinnedTransport).toHaveBeenCalledTimes(1)+ const query = deps.db.query as ReturnType<typeof vi.fn>+ expect(query).toHaveBeenCalledTimes(1)+ expect(String(query.mock.calls[0][0])).toContain('INSERT INTO oauth_grants')+ })+})diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.tsindex da4ba5104..d6e3d73fa 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -188,6 +188,12 @@ export interface CallbackInput {state: string/** Public URL we registered with the provider; included in the token POST. */redirectUri: string+ /**+ * RFC 9207 `iss` from the authorization-response redirect (`req.query.iss`);+ * validated on the remote lane against the pinned `issForCallback`. Absent on+ * the baked lane (baked ASes do not advertise `iss`), where it is ignored.+ */+ iss?: string}export interface CallbackDeps {@@ -268,6 +274,13 @@ export type CallbackResult =mcpServerName?: string}| { kind: 'invalid_state'; reason: string }+ /**+ * RFC 9207 authorization-server mix-up defence: the callback `iss` did not+ * match the AS issuer pinned on the remote server (`issForCallback`), or was+ * absent when one was advertised. Fail closed BEFORE the single-use code is+ * exchanged. No value fields — the issuer strings are NEVER echoed back.+ */+ | { kind: 'issuer_mismatch' }| { kind: 'unknown_oauth_client' }| { kind: 'recipe_not_found' }/** mcp subject: the McpServer named in the signed state does not exist / is not OAuth. */@@ -451,6 +464,26 @@ async function handleMcpOAuthCallback(return { kind: 'invalid_state', reason: 'binding_mismatch' }}+ // ─── RFC 9207 issuer check (remote lane only) ─────────────────────────────+ // Authorization-server mix-up defence: an attacker who controls one AS in a+ // multi-AS deployment can trick a client into sending a code minted by the+ // honest AS to the attacker's token endpoint (or vice versa). RFC 9207 binds+ // the authorization response to its issuer via the `iss` query param; we pin+ // the honest issuer at discovery (`issForCallback`) and require the callback's+ // `iss` to match it here — BEFORE the single-use code is ever exchanged.+ //+ // Skip when `issForCallback` is absent/empty: the AS did not advertise `iss`+ // in its discovery document, so there is nothing to compare against. This is+ // fail-open by ABSENCE OF PRODUCER DATA, not a lax choice. The baked lane has+ // no `decl.remote`, so `expectedIss` is always absent there and it never runs.+ const expectedIss = subject.decl.remote?.issForCallback+ if (typeof expectedIss === 'string' && expectedIss.length > 0) {+ // Fail closed on any deviation, INCLUDING an absent/empty callback `iss`.+ if (input.iss !== expectedIss) {+ return { kind: 'issuer_mismatch' }+ }+ }+// ─── Membership guards run BEFORE the token exchange (R3-L1) ──────────────// These guards depend only on the signed claims + the resolved subject// (`subject.contextRef`, `deps.userContextsReader`, `claims.userId`) — neverdiff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.tsindex 2e0618d13..0d9fd6cf6 100644--- a/control-api/src/routes/external/oauthCallback.ts+++ b/control-api/src/routes/external/oauthCallback.ts@@ -105,6 +105,9 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {const { oauthClientId } = req.paramsconst code = typeof req.query.code === 'string' ? req.query.code : ''const state = typeof req.query.state === 'string' ? req.query.state : ''+ // RFC 9207 issuer — validated on the remote lane against the pinned+ // `issForCallback` inside handleOAuthCallback (AS mix-up defence).+ const iss = typeof req.query.iss === 'string' ? req.query.iss : undefinedif (!code || !state) {return res.status(400).json({ error: 'missing_code_or_state' })@@ -113,7 +116,7 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {const redirectUri = buildPublicCallbackUrl(req, oauthClientId, config.oauthCallbackBaseUrl)const result = await handleOAuthCallback(- { oauthClientId, code, state, redirectUri },+ { oauthClientId, code, state, redirectUri, iss },{db: { query: (text, values) => pool.query(text, values) },recipeReader,@@ -143,6 +146,10 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {)case 'invalid_state':return res.status(400).json({ error: 'invalid_state', reason: result.reason })+ case 'issuer_mismatch':+ // RFC 9207 mix-up defence — no issuer echo. 400, consistent with the+ // sibling invalid_state mapping.+ return res.status(400).json({ error: 'issuer_mismatch' })case 'unknown_oauth_client':return res.status(400).json({ error: 'unknown_oauth_client' })case 'recipe_not_found':