Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): bound broker token cache re-consult for non-expiring grants (R1-M1)
Diego Zacarias0175488a435e
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 703d22a0a..97de1d0cf 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.282",+ "version": "0.1.283","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.282",+ "version": "0.1.283","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex b1c80442f..ad79efaaf 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.282",+ "version": "0.1.283","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/mcp/__tests__/brokerTokenProvider.test.ts b/mcp-host/src/mcp/__tests__/brokerTokenProvider.test.tsindex ce8c0f162..6aeeef05e 100644--- a/mcp-host/src/mcp/__tests__/brokerTokenProvider.test.ts+++ b/mcp-host/src/mcp/__tests__/brokerTokenProvider.test.ts@@ -68,6 +68,38 @@ describe('createBrokerTokenProvider — fail-closed contract', () => {expect(f).toHaveBeenCalledTimes(2)})+ it('re-consults the broker for a non-expiring (expiresAt:null) token once its max age elapses (R1-M1)', async () => {+ // control-api emits expiresAt:null for non-expiring upstream tokens (Notion/+ // ClickUp always). An ACTIVE partition never idle-evicts and such a token+ // never 401s upstream, so without a hard re-consult cap a grant revoked in+ // control-api would be honored forever. Assert the cap re-consults the broker+ // and fails closed once the grant is gone.+ let clock = 1_000_000+ let revoked = false+ const f = stubFetch(() =>+ revoked+ ? jsonResponse(404, { error: 'no_grant' })+ : jsonResponse(200, { token: 'tok', expiresAt: null })+ )+ const p = createBrokerTokenProvider(+ { name: 'gh' },+ { userId: 'alice' },+ deps(f, { now: () => clock })+ )+ expect(await p.resolve()).toBe('tok')+ expect(f).toHaveBeenCalledTimes(1)+ // Still within the max age → cached, no re-consult.+ clock += 60_000+ expect(await p.resolve()).toBe('tok')+ expect(f).toHaveBeenCalledTimes(1)+ // Past the max age (1h ≫ NULL_EXPIRY_MAX_AGE_MS) → re-consults the broker;+ // the grant is now revoked → fail-closed undefined, call not forwarded.+ clock += 3_600_000+ revoked = true+ expect(await p.resolve()).toBeUndefined()+ expect(f).toHaveBeenCalledTimes(2)+ })+it('refresh() forces a fresh POST even when a valid token is cached', async () => {const f = stubFetch(() => jsonResponse(200, { token: 'tok', expiresAt: null }))const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))diff --git a/mcp-host/src/mcp/brokerTokenProvider.ts b/mcp-host/src/mcp/brokerTokenProvider.tsindex 883038aca..b81f588e0 100644--- a/mcp-host/src/mcp/brokerTokenProvider.ts+++ b/mcp-host/src/mcp/brokerTokenProvider.ts@@ -28,6 +28,18 @@ import type { McpTokenProvider } from './client'export const DEFAULT_BROKER_FETCH_TIMEOUT_MS = 10_000/** Reuse a cached token only with this much headroom before its expiry. */const CACHE_EXPIRY_HEADROOM_MS = 30_000+/**+ * Hard re-consult interval for a NON-expiring token (`expiresAt:null`). control-api+ * emits this shape for providers whose upstream token never expires — Notion and+ * ClickUp always (`parseTokenResponse` hard-codes `expiresIn: undefined`), any+ * other provider when its response omits `expires_in`. Without a cap, an ACTIVE+ * partition (used within the manager idle window, so never evicted) would keep+ * serving such a token forever, and because a non-expiring upstream never 401s,+ * the mcp-server-401 → refresh → no_grant revocation backstop never fires either:+ * a grant revoked in control-api would be honored indefinitely. Re-consulting the+ * broker at least this often bounds that revocation latency (R1-M1).+ */+export const NULL_EXPIRY_MAX_AGE_MS = 5 * 60_000export interface BrokerTokenSubject {userId?: string@@ -66,7 +78,7 @@ export function createBrokerTokenProvider(const fetchImpl = deps.fetchImpl ?? fetchconst timeoutMs = deps.timeoutMs ?? DEFAULT_BROKER_FETCH_TIMEOUT_MSconst now = deps.now ?? (() => Date.now())- let cached: { token: string; expiresAtMs: number | null } | undefined+ let cached: { token: string; expiresAtMs: number | null; cachedAtMs: number } | undefinedconst fetchToken = async (): Promise<string | undefined> => {const gatewayUrl = deps.gatewayUrl()?.trim()@@ -126,13 +138,20 @@ export function createBrokerTokenProvider(}if (res.status === 200) {+ // Reset up front so ANY throw below (a malformed JSON body from res.json(),+ // or the empty-token guard) leaves no stale entry behind — no error branch+ // may keep a token the caller can later reuse (R1-L1).+ cached = undefinedconst data = (await res.json()) as { token?: unknown; expiresAt?: unknown }if (typeof data.token !== 'string' || data.token.length === 0) {- cached = undefinedthrow new Error(`mcp-oauth broker returned malformed 200 body for ${server.name}`)}const parsed = typeof data.expiresAt === 'string' ? Date.parse(data.expiresAt) : NaN- cached = { token: data.token, expiresAtMs: Number.isNaN(parsed) ? null : parsed }+ cached = {+ token: data.token,+ expiresAtMs: Number.isNaN(parsed) ? null : parsed,+ cachedAtMs: now(),+ }return data.token}// no_grant / insufficient_scope → fail closed as "no token".@@ -147,13 +166,20 @@ export function createBrokerTokenProvider(return {resolve: async () => {- // Re-validate the grant on every (re)connect; only reuse a cached token- // with comfortable headroom before expiry.- if (- cached &&- (cached.expiresAtMs === null || cached.expiresAtMs - now() > CACHE_EXPIRY_HEADROOM_MS)- ) {- return cached.token+ // Reuse a cached token only while it is demonstrably fresh; otherwise+ // re-consult the broker so a revoked grant stops being honored within a+ // bounded window. Two freshness regimes:+ // - expiring token → reuse while it keeps CACHE_EXPIRY_HEADROOM_MS of+ // headroom before its own expiry.+ // - non-expiring token (expiresAtMs === null) → reuse only within+ // NULL_EXPIRY_MAX_AGE_MS of when it was cached; see that constant for+ // why an unbounded reuse would honor a revoked grant forever (R1-M1).+ if (cached) {+ const fresh =+ cached.expiresAtMs === null+ ? now() - cached.cachedAtMs < NULL_EXPIRY_MAX_AGE_MS+ : cached.expiresAtMs - now() > CACHE_EXPIRY_HEADROOM_MS+ if (fresh) return cached.token}return fetchToken()},