Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(oauth): refresh shared context grants in the proactive sweep (B1)
Diego Zacarias9eb774bb9a8a
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 457f61f6a..cc624b3db 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.598",+ "version": "0.1.599","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.598",+ "version": "0.1.599","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 393630037..944361935 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.598",+ "version": "0.1.599","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/services/oauthProactiveRefreshCron.ts b/control-api/src/services/oauthProactiveRefreshCron.tsindex f78a0cd61..07450ada7 100644--- a/control-api/src/services/oauthProactiveRefreshCron.ts+++ b/control-api/src/services/oauthProactiveRefreshCron.ts@@ -8,9 +8,11 @@** The refresh machinery is NOT reimplemented: each candidate is fed to the* existing reactive `getAccessToken` with `refreshBufferMs = Bp` and- * `requireBackground: true`, and the returned access token is DISCARDED — only- * the side effect (persisted renewed token) and the outcome label matter- * (mini-spec §6.2). The decision layer is the pure `proactiveRefreshPolicy`+ * `requireBackground` set per grantKind (`true` for `user` grants — SEC-5;+ * `false` for `shared` context identity, which is unattended by design), and the+ * returned access token is DISCARDED — only the side effect (persisted renewed+ * token) and the outcome label matter (mini-spec §6.2). The decision layer is+ * the pure `proactiveRefreshPolicy`* module; this file is the thin orchestrator: enumerate → claim → refresh →* classify, plus the time-based DCR sweep.*@@ -201,13 +203,22 @@ export async function runProactiveRefreshSweep(// reactive path already renewed it out of the window since the snapshot.const claimed = await claimRemoteGrantForRefresh(txDb, key, window)if (!claimed) return 'skipped' as const- // requireBackground:true — unattended use (SEC-5). The access token is- // discarded; only the persisted refresh + the kind matter. refreshBufferMs- // = Bp so `getAccessToken` treats an in-proactive-window token as stale- // and refreshes it. resolveDns/pinnedTransport left undefined ⇒ production- // resolve + node:https (the remote lane's own IP-pinned path).+ // requireBackground is PER-grantKind, not fixed. SEC-5 governs `user`+ // grants only (unattended reuse needs explicit background consent), so+ // those keep `true` — redundant with the enumeration filter, kept as+ // defense in depth. `shared` grants are context identity, unattended by+ // design and created by `bootstrapSharedOAuthGrant` with `background`+ // defaulting to false; forcing `true` here would make `getOAuthGrant`'s+ // shared branch add `AND background = true`, return `no_grant`, and never+ // refresh the context grant — the mini-spec's headline case. Mirrors the+ // interactive shared broker (`routes/mcpOauth.ts`, requireBackground:false).+ // The access token is discarded; only the persisted refresh + the kind+ // matter. refreshBufferMs = Bp so `getAccessToken` treats an+ // in-proactive-window token as stale and refreshes it.+ // resolveDns/pinnedTransport left undefined ⇒ production resolve ++ // node:https (the remote lane's own IP-pinned path).const result = await getAccessToken(- { ...key, requireBackground: true },+ { ...key, requireBackground: key.grantKind === 'user' },{db: txDb,recipeReader: ownerDeclReader,diff --git a/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts b/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.tsindex e0d539bf0..b7b0f84b2 100644--- a/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts+++ b/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts@@ -14,15 +14,24 @@ import { Pool } from 'pg'import { config } from '../src/config.js'import type { DbClient } from '../src/db.js'import { initDb } from '../src/db.js'+import type {+ PinnedRawResponse,+ PinnedTransport,+ PinnedTransportInput,+} from '../src/http/pinnedFetch.js'+import type { RecipeWithOAuthClients } from '../src/oauth/callback.js'import { listExpiringDynamicClients, upsertDynamicClient } from '../src/oauth/dynamicClientStore.js'import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'import {type OAuthGrantKey,bootstrapSharedOAuthGrant,claimRemoteGrantForRefresh,+ getOAuthGrant,listRemoteGrantsInProactiveWindow,upsertOAuthGrant,} from '../src/oauth/store.js'+import { getAccessToken } from '../src/oauth/tokenHelper.js'const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skip@@ -124,6 +133,88 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post}}+ // Remote owner decl produced by the REAL resolver (T1), so the refresh path+ // reads the same public/remote routing the mint + callback do.+ const REMOTE_TOKEN_ENDPOINT = 'https://as.example.com/token'+ const REMOTE_VALIDATED_IP = '93.184.216.34'+ function remoteOwnerDecl(): RecipeWithOAuthClients {+ const resolved = resolveServerOAuthSubject({+ spec: {+ contextRef: 'ctx-1',+ oauth: {+ source: 'remote',+ id: 'https://control.example.com/.well-known/evenfire-mcp-client',+ clientMode: 'public',+ authorizationEndpoint: 'https://as.example.com/authorize',+ tokenEndpoint: REMOTE_TOKEN_ENDPOINT,+ issuer: 'https://as.example.com',+ resource: 'https://as.example.com',+ grantScope: 'user',+ scopes: ['read'],+ bearerInBody: false,+ supportsRefresh: true,+ },+ },+ })+ if (!resolved) throw new Error('fixture: remote resolve returned null')+ return { spec: { oauthClients: [resolved.decl] } }+ }+ const constTransport =+ (responseJson: string): PinnedTransport =>+ async (_input: PinnedTransportInput): Promise<PinnedRawResponse> => ({+ status: 200,+ headers: { 'content-type': 'application/json' },+ bodyText: responseJson,+ })+ const refreshDeps = (transport: PinnedTransport) => ({+ db,+ recipeReader: { read: async () => remoteOwnerDecl() },+ secretReader: { read: async () => ({}) },+ fetchFn: (async () => {+ throw new Error('remote refresh must not use fetchFn')+ }) as unknown as typeof fetch,+ encryptionKey: KEY,+ resolveDns: async () => [REMOTE_VALIDATED_IP],+ pinnedTransport: transport,+ // Bp so an in-proactive-window token is treated as stale, exactly as the cron.+ refreshBufferMs: WINDOW.proactiveBufferMs,+ })++ it('T4/B1: a background=false shared context grant is refreshed end-to-end (only with requireBackground:false)', async () => {+ await seedShared('e2e-shared', 'ctx-1', 'remote', IN_WINDOW_SEC)+ const key = sharedKey('e2e-shared', 'ctx-1')+ const before = await getOAuthGrant(db, KEY, key)+ expect(before?.background).toBe(false) // bootstrapSharedOAuthGrant defaults false++ // B1 root cause: with requireBackground:true the shared grant is invisible to+ // getOAuthGrant, so the refresh returns no_grant and the row is untouched.+ const gatedOut = await getAccessToken(+ { ...key, requireBackground: true },+ refreshDeps(constTransport('{}'))+ )+ expect(gatedOut).toEqual({ kind: 'no_grant' })+ const afterGated = await getOAuthGrant(db, KEY, key)+ expect(afterGated?.accessToken).toBe(before?.accessToken) // unchanged++ // The fix: requireBackground:false (what the cron now passes for shared) →+ // refreshes and persists a new token with an advanced expiry (T4 observable).+ const result = await getAccessToken(+ { ...key, requireBackground: false },+ refreshDeps(+ constTransport(+ JSON.stringify({ access_token: 'NEW-AT', refresh_token: 'NEW-RT', expires_in: 3600 })+ )+ )+ )+ expect(result.kind).toBe('ok')+ const after = await getOAuthGrant(db, KEY, key)+ expect(after?.accessToken).toBe('NEW-AT')+ expect(after?.refreshToken).toBe('NEW-RT')+ expect(after?.accessTokenExpiresAt?.getTime()).toBeGreaterThan(+ before?.accessTokenExpiresAt?.getTime() ?? 0+ )+ })+it('enumerates only remote mcpserver grants (shared + background user) inside the window', async () => {await seedShared('e-shared-in', 'ctx-in', 'remote', IN_WINDOW_SEC)await seedShared('e-shared-healthy', 'ctx-h', 'remote', HEALTHY_SEC)diff --git a/control-api/test/services.oauthProactiveRefreshCron.test.ts b/control-api/test/services.oauthProactiveRefreshCron.test.tsindex c8d74c86e..fa61d6222 100644--- a/control-api/test/services.oauthProactiveRefreshCron.test.ts+++ b/control-api/test/services.oauthProactiveRefreshCron.test.ts@@ -69,6 +69,15 @@ const sharedKey = (server: string, ctx: string): OAuthGrantKey => ({oauthClientId: 'cid',})+const userKey = (server: string, userId: string): OAuthGrantKey => ({+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: 'mcp-server',+ recipeName: server,+ userId,+ oauthClientId: 'cid',+})+const mockedEnumerate = vi.mocked(listRemoteGrantsInProactiveWindow)const mockedClaim = vi.mocked(claimRemoteGrantForRefresh)const mockedGetToken = vi.mocked(getAccessToken)@@ -102,16 +111,35 @@ describe('runProactiveRefreshSweep — token candidates', () => {})it('claimed + ok → outcome ok, and the refresh runs on the transaction client', async () => {- mockedEnumerate.mockResolvedValue([sharedKey('srv-a', 'ctx-1')])+ mockedEnumerate.mockResolvedValue([userKey('srv-a', 'u-1')])const summary = await runProactiveRefreshSweep(gateway, OPTS, deps)expect(summary.outcomes.ok).toBe(1)- // requireBackground:true (SEC-5) and refreshBufferMs = Bp, db = the tx client.+ // refreshBufferMs = Bp, db = the tx client (per-grantKind requireBackground is+ // asserted by the B1 test below).expect(mockedGetToken).toHaveBeenCalledWith(- expect.objectContaining({ grantKind: 'shared', requireBackground: true }),+ expect.objectContaining({ grantKind: 'user' }),expect.objectContaining({ db: fakeTx, refreshBufferMs: OPTS.proactiveBufferMs }))})+ it('B1: requireBackground is per-grantKind — false for shared (context identity), true for user', async () => {+ // B1 regression: passing requireBackground:true for shared keys makes+ // getOAuthGrant's shared branch add `AND background = true` and return+ // no_grant, so the headline context grant is never refreshed. This asserts+ // the exact flag the cron hands the getAccessToken seam per key. Fails+ // against the pre-fix head (which passed `true` for every key).+ mockedEnumerate.mockResolvedValue([sharedKey('srv-s', 'ctx-1'), userKey('srv-u', 'u-1')])+ await runProactiveRefreshSweep(gateway, OPTS, deps)++ const flagFor = (grantKind: 'shared' | 'user') =>+ mockedGetToken.mock.calls.find(+ ([input]) => (input as OAuthGrantKey).grantKind === grantKind+ )?.[0].requireBackground++ expect(flagFor('shared')).toBe(false)+ expect(flagFor('user')).toBe(true)+ })+it('claim returns false (locked / renewed out of window) → skipped, no refresh', async () => {mockedEnumerate.mockResolvedValue([sharedKey('srv-a', 'ctx-1')])mockedClaim.mockResolvedValue(false)