Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(codex): close late-review lock gaps and remaining CodeQL alerts
Alfredo Lopez51645ba385f0
diff --git a/codex-llm-proxy/src/logger.ts b/codex-llm-proxy/src/logger.tsindex 0191fd1be..2abf726fd 100644--- a/codex-llm-proxy/src/logger.ts+++ b/codex-llm-proxy/src/logger.ts@@ -3,6 +3,8 @@ import pino, { type DestinationStream } from 'pino'export const REDACT_PATHS = ['accessToken','refreshToken',+ 'chatgptAccountId',+ 'accountId','executionTicket','authorization','headers.authorization',diff --git a/codex-llm-proxy/test/redaction.test.ts b/codex-llm-proxy/test/redaction.test.tsindex a01b1c114..2b6f9e85f 100644--- a/codex-llm-proxy/test/redaction.test.ts+++ b/codex-llm-proxy/test/redaction.test.ts@@ -13,6 +13,8 @@ describe('proxy redaction', () => {probe.info({accessToken: 'sk-live-secret',refreshToken: 'rt-secret',+ chatgptAccountId: 'acct_live_secret',+ accountId: 'acct_live_secret',executionTicket: 'ticket-secret',attemptReceipt: 'receipt-secret',authorization: 'Bearer secret',@@ -23,6 +25,7 @@ describe('proxy redaction', () => {expect(joined).toContain('codex_proxy_probe')expect(joined).not.toContain('sk-live-secret')expect(joined).not.toContain('rt-secret')+ expect(joined).not.toContain('acct_live_secret')expect(joined).not.toContain('ticket-secret')expect(joined).not.toContain('receipt-secret')expect(joined).not.toContain('Bearer secret')diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 94cfb9c8d..29d4d00c4 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.495",+ "version": "0.1.496","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.495",+ "version": "0.1.496","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 99acf8119..ad4671e58 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.495",+ "version": "0.1.496","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex 0d6d7d974..bc5c03bd0 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -72,7 +72,9 @@ function oauthDeps(}function keyFromReq(req: { params?: { key?: string } }): string {- return normalizeCodexConnectionKey(req.params?.key)+ const raw = typeof req.params?.key === 'string' ? req.params.key.trim() : ''+ if (!raw) return normalizeCodexConnectionKey(raw)+ return assertCodexConnectionKey(raw)}function parseIntent(value: unknown): CodexSubscriptionOAuthIntent {@@ -83,6 +85,10 @@ function sendOAuthError(res: { status: (n: number) => { json: (body: unknown) => void } },err: unknown) {+ if (err instanceof CodexSubscriptionInvalidConnectionKeyError) {+ res.status(400).json({ error: 'invalid_connection_key' })+ return+ }if (err instanceof CodexSubscriptionOAuthError) {const status =err.code === 'disabled'diff --git a/control-api/src/routes/admin/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.tsindex deafd9da2..e2c2be756 100644--- a/control-api/src/routes/admin/hostSpecValidation.ts+++ b/control-api/src/routes/admin/hostSpecValidation.ts@@ -339,14 +339,7 @@ export async function validateHostSpec(}}const connectionRef =- provider === 'codex-subscription' && isPlainObject(model)- ? typeof model.connectionRef === 'string' && model.connectionRef.trim()- ? model.connectionRef.trim()- : 'deployment-default'- : undefined- if (provider === 'codex-subscription' && isPlainObject(model) && !model.connectionRef) {- model.connectionRef = 'deployment-default'- }+ provider === 'codex-subscription' ? resolvedCodexConnectionRef(model) : undefinedconst allowed = await deps.isModelAllowed(provider, name, connectionRef)// Switching connectionRef is a new assignment even when (provider, model)// already lived on the Host. A revoked/unknown grant must not ride the@@ -381,13 +374,16 @@ export async function validateHostSpec(// (same fail-closed gate as spec.model.name), so a broken fallback is caught// on write instead of surfacing only during the incident it was meant to// absorb (spec V16). `credentialSlot`, when present, is format-checked only.- const policyErrors = await validateLlmPolicy(spec.llmPolicy, deps, tol)+ const hostCodexConnectionRef = resolvedCodexConnectionRef(+ isPlainObject(spec.model) ? spec.model : undefined+ )+ const policyErrors = await validateLlmPolicy(spec.llmPolicy, deps, tol, hostCodexConnectionRef)if (policyErrors) return policyErrors// Topic 3a per-host allowlist. Runs AFTER the global-allowlist gates above, so// by the time coherence is checked the primary + fallbacks are already known// to be valid GLOBAL pairs; this narrows them to the host's offered subset.- const allowedModelsErrors = await validateAllowedModels(spec, deps, tol)+ const allowedModelsErrors = await validateAllowedModels(spec, deps, tol, hostCodexConnectionRef)if (allowedModelsErrors) return allowedModelsErrors// The write PASSED validation: hand the queued tolerations to the caller via@@ -546,6 +542,17 @@ async function maybeWarnStale(* audit event (not emitted until the whole write persists) and returns true so* the gate skips its rejection.*/+function resolvedCodexConnectionRef(model: unknown): string {+ if (+ isPlainObject(model) &&+ typeof model.connectionRef === 'string' &&+ model.connectionRef.trim()+ ) {+ return model.connectionRef.trim()+ }+ return 'deployment-default'+}+function storedCodexConnectionRef(stored: Record<string, unknown> | undefined): string | undefined {if (!isPlainObject(stored) || !isPlainObject(stored.model)) return undefinedconst provider = typeof stored.model.provider === 'string' ? stored.model.provider.trim() : ''@@ -603,7 +610,8 @@ function toleratePair(async function validateAllowedModels(spec: Record<string, unknown>,deps: HostSpecValidationDeps,- tol: HostToleranceBundle+ tol: HostToleranceBundle,+ connectionRef: string): Promise<{ errors: Array<{ field: string; message: string }> } | null> {const allowedModels = spec.allowedModelsif (allowedModels === undefined) return null@@ -645,7 +653,11 @@ async function validateAllowedModels(// catalog can never be offered by a host — unless tolerating a pre-existing// incoherence this write does not worsen (Pieza D). A tolerated pair is still// added to `offered` so the coherence gate below sees the host as offering it.- const allowed = await deps.isModelAllowed(provider, model)+ const allowed = await deps.isModelAllowed(+ provider,+ model,+ provider === 'codex-subscription' ? connectionRef : undefined+ )if (!allowed && !toleratePair(provider, model, 'subset', tol)) {return {errors: [@@ -724,7 +736,8 @@ async function validateAllowedModels(async function validateLlmPolicy(llmPolicy: unknown,deps: HostSpecValidationDeps,- tol: HostToleranceBundle+ tol: HostToleranceBundle,+ connectionRef: string): Promise<{ errors: Array<{ field: string; message: string }> } | null> {if (llmPolicy === undefined) return nullif (!isPlainObject(llmPolicy)) {@@ -813,7 +826,11 @@ async function validateLlmPolicy(// Allowlist gate LAST: it is the only async (DB) check, so cheap structural// rejections above avoid a needless query. Tolerated (Pieza D) when the pair// is a pre-existing incoherence this write does not worsen.- const allowed = await deps.isModelAllowed(provider, model)+ const allowed = await deps.isModelAllowed(+ provider,+ model,+ provider === 'codex-subscription' ? connectionRef : undefined+ )if (!allowed && !toleratePair(provider, model, 'fallback', tol)) {return {errors: [diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.tsindex 3c658fd89..2e1ad593a 100644--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts@@ -65,8 +65,8 @@ export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Routconst router = Router()router.post('/mcp-host/llm/provider-attempts/authorize',- requireMcpHostJwt,...llmProviderAttemptAuthorizeRateLimits(),+ requireMcpHostJwt,asyncHandler(async (req: Request, res: Response) => {const claims = req.mcpHostJwtif (!claims) {diff --git a/control-api/src/routes/workflows/shared/rateLimit.ts b/control-api/src/routes/workflows/shared/rateLimit.tsindex 2345a574f..77d5914ab 100644--- a/control-api/src/routes/workflows/shared/rateLimit.ts+++ b/control-api/src/routes/workflows/shared/rateLimit.ts@@ -186,6 +186,17 @@ export function codexOAuthCallbackRateLimits() {] as const}+function mcpHostAttemptRateLimitKey(req: Request): string {+ const claims = req.mcpHostJwt+ if (claims?.sub) return `llm_provider_attempt:${claims.sub}`+ const bearer = extractBearerToken(req)+ if (bearer) {+ const hash = createHash('sha256').update(bearer).digest('hex').slice(0, 32)+ return `llm_provider_attempt:bearer:${hash}`+ }+ return `llm_provider_attempt:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`+}+export function llmProviderAttemptAuthorizeRateLimits() {return [rateLimit({@@ -193,22 +204,13 @@ export function llmProviderAttemptAuthorizeRateLimits() {limit: LLM_PROVIDER_ATTEMPT_AUTHORIZE_PER_MINUTE,standardHeaders: 'draft-7',legacyHeaders: false,- skip: (req: Request) => !req.mcpHostJwt,- keyGenerator: (req: Request) => {- const claims = req.mcpHostJwt- if (!claims) return `llm_provider_attempt:anon:${ipKeyGenerator(req.ip ?? 'unknown')}`- return `llm_provider_attempt:${claims.sub}`- },+ keyGenerator: mcpHostAttemptRateLimitKey,handler: workflowGrantEdgeRateLimitHandler,}),rateLimitMiddleware({bucketType: 'llm_provider_attempt_authorize',maxPerMinute: LLM_PROVIDER_ATTEMPT_AUTHORIZE_PER_MINUTE,- getBucketKey: (req: Request) => {- const claims = req.mcpHostJwt- if (!claims) return null- return `llm_provider_attempt:${claims.sub}`- },+ getBucketKey: mcpHostAttemptRateLimitKey,}),] as const}diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.tsindex a04b95b1f..d4c9544b9 100644--- a/control-api/src/services/codexSubscriptionConnection.ts+++ b/control-api/src/services/codexSubscriptionConnection.ts@@ -361,10 +361,10 @@ export async function rotateCodexSubscriptionCredentials(credential_revision = credential_revision + 1,last_refresh_at = now(),last_auth_at = now(),- revoked_at = NULL,updated_at = now()WHERE connection_key = $7AND credential_revision = $8+ AND revoked_at IS NULLRETURNING ${SAFE_CONNECTION_COLUMNS}`,[refreshTokenEncrypted,@@ -397,7 +397,7 @@ export async function revokeCodexSubscriptionConnection(access_token_encrypted = NULL,access_token_expires_at = NULL,chatgpt_account_id_encrypted = NULL,- account_fingerprint = NULL,+ catalog_status = 'never_synced',credential_revision = credential_revision + 1,refresh_lock_token = NULL,refresh_lock_expires_at = NULL,@@ -409,7 +409,15 @@ export async function revokeCodexSubscriptionConnection([key])const row = result.rows[0] as SafeConnectionRow | undefined- return row ? toSafeConnection(row) : getSafeCodexSubscriptionConnection(db, key)+ if (!row) return getSafeCodexSubscriptionConnection(db, key)+ await db.query(+ `UPDATE codex_catalog_models+ SET enabled = false,+ stale = true+ WHERE connection_id = $1`,+ [row.id]+ )+ return toSafeConnection(row)}export async function acquireCodexSubscriptionRefreshLock(diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.tsindex 2724a4439..57cf474b2 100644--- a/control-api/src/services/codexSubscriptionOAuth.ts+++ b/control-api/src/services/codexSubscriptionOAuth.ts@@ -387,6 +387,12 @@ async function persistGrantedTokens(): Promise<CodexSubscriptionSafeConnection> {const key = normalizeCodexConnectionKey(connectionKey)const existing = await getSafeCodexSubscriptionConnection(deps.db, key)+ if (existing?.revokedAt || existing?.status === 'revoked') {+ throw new CodexSubscriptionOAuthError(+ 'not_connected',+ 'revoked grant cannot be reused; create a new connection'+ )+ }if (existing?.accountFingerprint &&existing.accountFingerprint !== parsed.accountFingerprint &&@@ -487,7 +493,21 @@ export async function ensureFreshCodexAccessToken(deps: CodexOAuthDeps): Promise)if (!locked) {await new Promise(resolve => setTimeout(resolve, 400))- return+ const latest = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey, key)+ if (!latest) {+ throw new CodexSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')+ }+ const waitedAccountId = latest.chatgptAccountId || chatgptAccountIdFromJwt(latest.accessToken)+ const stillExpiring =+ latest.accessTokenExpiresAt != null &&+ latest.accessTokenExpiresAt.getTime() - Date.now() < ACCESS_TOKEN_REFRESH_SKEW_MS+ if (latest.accessToken && !stillExpiring && waitedAccountId) {+ if (!latest.chatgptAccountId) {+ await persistCodexChatgptAccountId(deps.db, deps.encryptionKey, waitedAccountId, key)+ }+ return+ }+ throw new CodexSubscriptionOAuthError('refresh_in_flight', 'another refresh holds the lock')}try {const latest = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey, key)diff --git a/control-api/src/services/llmAllowedModelsConfigMap.ts b/control-api/src/services/llmAllowedModelsConfigMap.tsindex d5912a4ac..806ee6999 100644--- a/control-api/src/services/llmAllowedModelsConfigMap.ts+++ b/control-api/src/services/llmAllowedModelsConfigMap.ts@@ -25,7 +25,6 @@ import { pool } from '../db.js'import { listEnabledCodexModelsGroupedByConnection } from './codexSubscriptionCatalog.js'import {type CodexSubscriptionSafeConnection,- getSafeCodexSubscriptionConnection,listSafeCodexSubscriptionConnections,} from './codexSubscriptionConnection.js'import { type AllowedModelEntry, listEnabledGroupedByProvider } from './llmAllowedModels.js'@@ -117,14 +116,6 @@ export interface AllowedModelsConfigMapMaterializer {* ordered by the query (provider, model), so the serialized form — and thus the* hash — is stable for a given allowlist state.*/-async function loadCodexConnection(db: DbClient): Promise<CodexSubscriptionSafeConnection | null> {- try {- return await getSafeCodexSubscriptionConnection(db)- } catch {- return null- }-}-export function buildConfigMapData(grouped: Record<string, AllowedModelEntry[]>): {data: Record<string, string>contentHash: string@@ -160,15 +151,11 @@ export class LlmAllowedModelsConfigMapWriter implements AllowedModelsConfigMapMaasync materialize(db: DbClient = pool): Promise<void> {const grouped = await listEnabledGroupedByProvider(db)const { data, contentHash } = buildConfigMapData(grouped)- const connections = await listSafeCodexSubscriptionConnections(db).catch(() => [])- const modelsByKey = await listEnabledCodexModelsGroupedByConnection(db).catch(() => ({}))- const readiness = buildCodexReadinessAnnotations(- connections.find(row => row.connectionKey === 'deployment-default') ??- connections[0] ??- (await loadCodexConnection(db)),- connections,- modelsByKey- )+ const connections = await listSafeCodexSubscriptionConnections(db)+ const modelsByKey = await listEnabledCodexModelsGroupedByConnection(db)+ const defaultConnection =+ connections.find(row => row.connectionKey === 'deployment-default') ?? null+ const readiness = buildCodexReadinessAnnotations(defaultConnection, connections, modelsByKey)let lastError: unknownfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {try {diff --git a/control-api/src/utils/log/redact.ts b/control-api/src/utils/log/redact.tsindex 9f4c52484..eb50c0f18 100644--- a/control-api/src/utils/log/redact.ts+++ b/control-api/src/utils/log/redact.ts@@ -9,6 +9,8 @@ export const TOKEN_LEAK_REDACT_PATHS: readonly string[] = ['token','accessToken','refreshToken',+ 'chatgptAccountId',+ 'accountId','voucher','password','password_hash',@@ -26,6 +28,8 @@ export const REQUIRED_REDACT_PATHS: readonly string[] = ['headers.authorization','accessToken','refreshToken',+ 'chatgptAccountId',+ 'accountId','claim_token','claimToken','client_secret',diff --git a/control-api/test/hostSpecValidation.codexSubscription.test.ts b/control-api/test/hostSpecValidation.codexSubscription.test.tsindex 5f683fc15..cf318c37e 100644--- a/control-api/test/hostSpecValidation.codexSubscription.test.ts+++ b/control-api/test/hostSpecValidation.codexSubscription.test.ts@@ -60,7 +60,25 @@ describe('codex-subscription Host admission', () => {'gpt-5.1','deployment-default')- expect((spec.model as { connectionRef?: string }).connectionRef).toBe('deployment-default')+ expect((spec.model as { connectionRef?: string }).connectionRef).toBeUndefined()+ })++ it('evaluates allowedModels and fallbacks against the Host connectionRef', async () => {+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'+ const isModelAllowed = vi.fn().mockResolvedValue(true)+ const res = await validateHostSpec(+ {+ model: { provider: 'codex-subscription', name: 'gpt-5.1', connectionRef: 'team-plus' },+ allowedModels: [+ { provider: 'codex-subscription', model: 'gpt-5.1' },+ { provider: 'codex-subscription', model: 'gpt-5.3-codex' },+ ],+ },+ { isModelAllowed }+ )+ expect(res).toBeNull()+ expect(isModelAllowed).toHaveBeenCalledWith('codex-subscription', 'gpt-5.1', 'team-plus')+ expect(isModelAllowed).toHaveBeenCalledWith('codex-subscription', 'gpt-5.3-codex', 'team-plus')})it('does not tolerate switching to a revoked connectionRef with the same model', async () => {diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.tsindex 048c9f1ad..d90339470 100644--- a/control-api/test/routes.admin.codexSubscription.test.ts+++ b/control-api/test/routes.admin.codexSubscription.test.ts@@ -188,6 +188,15 @@ describe('admin Codex subscription routes', () => {assertNoLeak(refresh.body)})+ it('rejects a malformed nested connection key before starting OAuth', async () => {+ const res = await request(app)+ .post('/admin/llm/providers/codex-subscription/connections/Bad%20Key/device/start')+ .send({ intent: 'connect' })+ expect(res.status).toBe(400)+ expect(res.body).toEqual({ error: 'invalid_connection_key' })+ expect(oauth.startDevice).not.toHaveBeenCalled()+ })+it('maps a live fingerprint collision on a keyed device start to 409', async () => {oauth.startDevice.mockRejectedValue(new CodexSubscriptionOAuthError('fingerprint_in_use', 'account already connected')diff --git a/control-api/test/routes.hostSpecValidation.test.ts b/control-api/test/routes.hostSpecValidation.test.tsindex b2085e700..e8b3de874 100644--- a/control-api/test/routes.hostSpecValidation.test.ts+++ b/control-api/test/routes.hostSpecValidation.test.ts@@ -126,8 +126,8 @@ describe('validateHostSpec', () => {{ isModelAllowed })expect(res).toBeNull()- expect(isModelAllowed).toHaveBeenCalledWith('claude', 'claude-haiku-4-5')- expect(isModelAllowed).toHaveBeenCalledWith('openai', 'gpt-5.4')+ expect(isModelAllowed).toHaveBeenCalledWith('claude', 'claude-haiku-4-5', undefined)+ expect(isModelAllowed).toHaveBeenCalledWith('openai', 'gpt-5.4', undefined)})it('rejects a fallback model not in the allowlist (model_not_allowed, with index path)', async () => {@@ -162,7 +162,7 @@ describe('validateHostSpec', () => {{ isModelAllowed })expect(res).toBeNull()- expect(isModelAllowed).toHaveBeenCalledWith('groq', 'llama-3.3-70b-versatile')+ expect(isModelAllowed).toHaveBeenCalledWith('groq', 'llama-3.3-70b-versatile', undefined)})it('rejects an unknown fallback provider (fail-closed, no allowlist lookup)', async () => {diff --git a/control-api/test/services.codexSubscriptionConnection.test.ts b/control-api/test/services.codexSubscriptionConnection.test.tsindex dc7d33f8a..f51a5a107 100644--- a/control-api/test/services.codexSubscriptionConnection.test.ts+++ b/control-api/test/services.codexSubscriptionConnection.test.ts@@ -161,6 +161,8 @@ describe('codex subscription connection repository', () => {).rejects.toBeInstanceOf(CodexSubscriptionStaleRevisionError)const [sql] = query.mock.calls[0] as [string]expect(sql).toMatch(/credential_revision = \$/)+ expect(sql).toMatch(/revoked_at IS NULL/)+ expect(sql).not.toMatch(/revoked_at = NULL/)})it('generates distinct identity keys that are not derived from the display name', () => {diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.tsindex 6bb1bada3..582b2a9a3 100644--- a/control-api/test/services.codexSubscriptionOAuth.test.ts+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts@@ -222,6 +222,50 @@ describe('codex subscription OAuth broker', () => {expect(repos.rotate).toHaveBeenCalledTimes(1)})+ it('refuses to persist tokens onto a revoked connection', async () => {+ const fetchFn = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({+ access_token: 'access-secret',+ refresh_token: 'refresh-secret',+ id_token: idTokenFor('acct_other'),+ }),+ })+ repos.consumeState.mockResolvedValue({+ safe: {+ state: 'state-revoked',+ flow: 'browser',+ intent: 'connect',+ status: 'consumed',+ expiresAt: new Date(Date.now() + 1000),+ consumedAt: new Date(),+ cancelledAt: null,+ createdAt: new Date(),+ },+ pkceVerifier: 'verifier',+ })+ repos.getSafe.mockResolvedValue({+ connectionKey: 'team-plus',+ status: 'revoked',+ credentialRevision: 4,+ catalogRevision: 2,+ accountFingerprint: fingerprint('acct_raw_123'),+ catalogStatus: 'ready',+ catalogSyncedAt: null,+ lastRefreshAt: null,+ lastAuthAt: null,+ refreshLockHeld: false,+ revokedAt: new Date(),+ createdAt: new Date(),+ updatedAt: new Date(),+ })+ await expect(+ handleCodexBrowserCallback(deps(fetchFn), { code: 'code-r', state: 'state-revoked' })+ ).rejects.toMatchObject({ code: 'not_connected' })+ expect(repos.rotate).not.toHaveBeenCalled()+ expect(repos.insertInitial).not.toHaveBeenCalled()+ })+it('persists a different account only with explicit replace intent', async () => {const fetchFn = vi.fn().mockResolvedValue({ok: true,@@ -459,6 +503,21 @@ describe('codex subscription OAuth broker', () => {expect(repos.releaseLock).toHaveBeenCalled()})+ it('fails loud when the refresh lock is held and the token stays stale', async () => {+ repos.loadSecrets.mockResolvedValue({+ refreshToken: 'refresh-secret',+ accessToken: 'stale-access',+ accessTokenExpiresAt: new Date(Date.now() + 30_000),+ chatgptAccountId: null,+ credentialRevision: 3,+ })+ repos.acquireLock.mockResolvedValue(false)+ await expect(ensureFreshCodexAccessToken(deps(vi.fn()))).rejects.toMatchObject({+ code: 'refresh_in_flight',+ })+ expect(repos.updateInPlace).not.toHaveBeenCalled()+ })+it('revokes locally even when upstream revoke fails', async () => {repos.loadSecrets.mockResolvedValue({refreshToken: 'refresh-secret',diff --git a/control-api/test/utils.log.redact.test.ts b/control-api/test/utils.log.redact.test.tsindex 6fbcd69c8..ed47f927e 100644--- a/control-api/test/utils.log.redact.test.ts+++ b/control-api/test/utils.log.redact.test.ts@@ -22,6 +22,13 @@ describe('token-leak redaction', () => {expect(TOKEN_LEAK_REDACT_PATHS).toContain('refreshToken')})+ it('redacts ChatGPT account identifiers', () => {+ expect(TOKEN_LEAK_REDACT_PATHS).toContain('chatgptAccountId')+ expect(TOKEN_LEAK_REDACT_PATHS).toContain('accountId')+ expect(REQUIRED_REDACT_PATHS).toContain('chatgptAccountId')+ expect(REQUIRED_REDACT_PATHS).toContain('accountId')+ })+it('redacts the registry voucher field (defense-in-depth)', () => {expect(TOKEN_LEAK_REDACT_PATHS).toContain('voucher')})diff --git a/control-api/test/workflows.shared.rateLimit.test.ts b/control-api/test/workflows.shared.rateLimit.test.tsindex 07e616f0b..df31632b9 100644--- a/control-api/test/workflows.shared.rateLimit.test.ts+++ b/control-api/test/workflows.shared.rateLimit.test.ts@@ -72,6 +72,25 @@ describe('routes/workflows/shared/rateLimit', () => {expect(adminWorkflowRateLimitCredential(req)).toBe('admin-cookie-token')})+ it('llmProviderAttemptAuthorizeRateLimits meters callers before JWT is attached', async () => {+ mockCheckAndIncrement.mockReset()+ const app = express()+ app.post('/authorize', ...llmProviderAttemptAuthorizeRateLimits(), (_req, res) => {+ res.status(200).json({ ok: true })+ })++ for (let i = 0; i < 60; i++) {+ pgAllows()+ await request(app).post('/authorize').expect(200)+ }+ pgAllows()+ const res = await request(app).post('/authorize').expect(429)+ expect(res.body).toMatchObject({+ error: 'Too Many Requests',+ retryAfterSeconds: expect.any(Number),+ })+ })+it('rate-limit factories pair an edge backstop with the PG limiter', () => {expect(workflowGrantReadRateLimits()).toHaveLength(2)expect(workflowGrantWriteRateLimits()).toHaveLength(2)diff --git a/control-ui/components/CodexAgentAssignment/index.tsx b/control-ui/components/CodexAgentAssignment/index.tsxindex 0c401c06f..98310c125 100644--- a/control-ui/components/CodexAgentAssignment/index.tsx+++ b/control-ui/components/CodexAgentAssignment/index.tsx@@ -122,9 +122,17 @@ export function CodexAgentAssignment({await load()return}- if (polled.status === 'expired' || polled.status === 'denied') break+ if (polled.status === 'expired' || polled.status === 'denied') {+ setUserCode(null)+ setVerificationUri(null)+ break+ }}+ setUserCode(null)+ setVerificationUri(null)} catch (err) {+ setUserCode(null)+ setVerificationUri(null)showToast(err instanceof Error ? err.message : 'ChatGPT sign-in failed', { tone: 'error' })} finally {setBusy(false)@@ -176,6 +184,8 @@ export function CodexAgentAssignment({try {await revokeCodexSubscription(selected.connectionKey)await load()+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Revoke failed', { tone: 'error' })} finally {setBusy(false)}diff --git a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx b/control-ui/components/__tests__/CodexAgentAssignment.test.tsxindex e82ed6573..b9ec6770d 100644--- a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx+++ b/control-ui/components/__tests__/CodexAgentAssignment.test.tsx@@ -5,6 +5,9 @@ import {createCodexSubscriptionConnection,listCodexConnectionModels,listCodexSubscriptionConnections,+ pollCodexDevice,+ revokeCodexSubscription,+ startCodexDeviceConnect,} from '@lib/codexSubscription'import { CodexAgentAssignment } from '../CodexAgentAssignment'import { ToastProvider } from '../Toast'@@ -145,4 +148,44 @@ describe('CodexAgentAssignment', () => {})expect(onConnectionRefChange).toHaveBeenCalledTimes(1)})++ it('clears the device-code banner after the poll expires', async () => {+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([+ connection({ connectionKey: 'team-plus', displayName: 'Team Plus' }),+ ])+ vi.mocked(startCodexDeviceConnect).mockResolvedValue({+ userCode: 'ABCD-1234',+ verificationUri: 'https://auth.openai.com/codex/device',+ intervalSeconds: 0.01,+ state: 'device-state',+ intent: 'connect',+ })+ vi.mocked(pollCodexDevice).mockResolvedValue({ status: 'expired' })+ renderAssignment('team-plus')+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeEnabled()+ })+ fireEvent.click(screen.getByRole('button', { name: 'Sign in with ChatGPT' }))+ await waitFor(() => {+ expect(pollCodexDevice).toHaveBeenCalled()+ })+ expect(screen.queryByTestId('codex-device-code')).not.toBeInTheDocument()+ })++ it('surfaces a revoke API error instead of swallowing it', async () => {+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([+ connection({ connectionKey: 'team-plus', displayName: 'Team Plus' }),+ ])+ confirmMock.mockResolvedValue(true)+ vi.mocked(revokeCodexSubscription).mockRejectedValue(new Error('revoke exploded'))+ const { onConnectionRefChange } = renderAssignment('team-plus')+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Revoke' })).toBeEnabled()+ })+ fireEvent.click(screen.getByRole('button', { name: 'Revoke' }))+ await waitFor(() => {+ expect(screen.getByText('revoke exploded')).toBeInTheDocument()+ })+ expect(onConnectionRefChange).not.toHaveBeenCalled()+ })})diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 2c6910463..6a2c37b1d 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.452",+ "version": "0.1.453","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.452",+ "version": "0.1.453","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 24b4ddf96..5d0f54fc2 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.452",+ "version": "0.1.453","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/deploy/base/control-plane/networkpolicies.yaml b/deploy/base/control-plane/networkpolicies.yamlindex 059b05927..a0c3bfb47 100644--- a/deploy/base/control-plane/networkpolicies.yaml+++ b/deploy/base/control-plane/networkpolicies.yaml@@ -841,7 +841,7 @@ spec:kubernetes.io/metadata.name: sandbox-recipespodSelector:matchLabels:- clerum.io/managed-by: host-context-controller+ clerum.io/component: workflow-mcp-hostports:- port: 8080protocol: TCPdiff --git a/docs/how-to/codeql-js-missing-rate-limiting.md b/docs/how-to/codeql-js-missing-rate-limiting.mdindex fcd12632b..368bb8640 100644--- a/docs/how-to/codeql-js-missing-rate-limiting.md+++ b/docs/how-to/codeql-js-missing-rate-limiting.md@@ -43,6 +43,7 @@ Tier defaults (requests/minute, per verified admin session identity unless noted| [#82](https://github.com/evenfire-ai/evenfire/security/code-scanning/82) | `grants.routes.ts:197` | Fixed: same || [#83](https://github.com/evenfire-ai/evenfire/security/code-scanning/83) | `grants.routes.ts:236` | Fixed: same || [#63](https://github.com/evenfire-ai/evenfire/security/code-scanning/63) | `outputs.ts:35` | Fixed: `adminOutputsReadRateLimits()` PG + edge backstop (30/min) |+| [#1157](https://github.com/evenfire-ai/evenfire/security/code-scanning/1157) | `llmProviderAttempts.routes.ts` | Fixed: `express-rate-limit` + PG **before** `requireMcpHostJwt` |Edge backstop keys: a **verified admin session identity hash** for signedControl UI sessions/bearers and a **source-IP fallback** for credentials that@@ -61,7 +62,7 @@ Additional tiers shipped in PR #428:| Admin workflow trigger | 10 | `adminWorkflowTriggerRateLimit` || Admin Codex read / write | 30 / 20 | `adminCodexReadRateLimits` / `adminCodexWriteRateLimits` || Codex OAuth callback | 20 | `codexOAuthCallbackRateLimits` (IP) |-| mcp-host attempt authorize | 60 | `llmProviderAttemptAuthorizeRateLimits` |+| mcp-host attempt authorize | 60 | `llmProviderAttemptAuthorizeRateLimits` (edge before JWT) |## Out-of-scope dispositions (Layer 3)diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 98f09c301..b75c7ef2b 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.235",+ "version": "0.1.236","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.235",+ "version": "0.1.236","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 7fc86e36c..b02f8befc 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.235",+ "version": "0.1.236","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/codexExecutionProjection.test.ts b/host-context-controller/src/codexExecutionProjection.test.tsindex 949b403de..c62420120 100644--- a/host-context-controller/src/codexExecutionProjection.test.ts+++ b/host-context-controller/src/codexExecutionProjection.test.ts@@ -77,6 +77,30 @@ describe('projectCodexExecution', () => {expect(projection.requiresCodexProxyEgress).toBe(false)})+ it('keeps the runtime drift hash stable across catalog content refreshes', () => {+ const spec = { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } }+ const first = projectCodexExecution(spec, {+ flagEnabled: true,+ connectionStatus: 'connected',+ catalogContentHash: 'aaa',+ catalogRevision: 1,+ connectionRevision: 4,+ enabledModels: ['codex-subscription:gpt-5.3-codex'],+ staleModels: [],+ })+ const second = projectCodexExecution(spec, {+ flagEnabled: true,+ connectionStatus: 'connected',+ catalogContentHash: 'bbb',+ catalogRevision: 9,+ connectionRevision: 4,+ enabledModels: ['codex-subscription:gpt-5.3-codex'],+ staleModels: [],+ })+ expect(first.driftHashInput).toBe(second.driftHashInput)+ expect(first.catalogContentHash).not.toBe(second.catalogContentHash)+ })+it('anti-false-positive: uncertain never defaults to eligible', () => {// A reversible mutation that defaulted eligibility to `eligible` must make// this assertion RED. The committed code stays fail-closed.diff --git a/host-context-controller/src/codexExecutionProjection.ts b/host-context-controller/src/codexExecutionProjection.tsindex 371b69712..685ea7e86 100644--- a/host-context-controller/src/codexExecutionProjection.ts+++ b/host-context-controller/src/codexExecutionProjection.ts@@ -158,8 +158,6 @@ function freezeProjection(const driftHashInput = JSON.stringify({eligibleTargets: input.eligibleTargets,derivedScopes: input.derivedScopes,- catalogContentHash: input.catalogContentHash,- catalogRevision: input.catalogRevision,connectionRevision: input.connectionRevision,eligibility: input.eligibility,})diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 4869ca0d5..2558ff3fe 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -3955,7 +3955,9 @@ export class HostReconciler {}private async reconcileMcpHostCodexProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {- if (this.projectCodexForHost(host).requiresCodexProxyEgress) {+ const projection = this.projectCodexForHost(host)+ if (projection.eligibility === 'uncertain') return+ if (projection.requiresCodexProxyEgress) {await this.ensureMcpHostCodexProxyEgressNetworkPolicy(host)return}diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.test.ts b/host-context-controller/src/llmAllowedModelsSnapshot.test.tsindex e01fdb9c6..dcf4716a2 100644--- a/host-context-controller/src/llmAllowedModelsSnapshot.test.ts+++ b/host-context-controller/src/llmAllowedModelsSnapshot.test.ts@@ -61,6 +61,18 @@ describe('parseAllowedModelsSnapshot per assigned connection', () => {expect(snapshot.catalogRevision).toBe(1)})+ it('does not rematch a missing deployment-default onto another grant in the map', () => {+ const cm = multiGrantConfigMap()+ const parsed = JSON.parse(+ String(cm.metadata.annotations['clerum.io/codex-connections'])+ ) as Record<string, unknown>+ delete parsed['deployment-default']+ cm.metadata.annotations['clerum.io/codex-connections'] = JSON.stringify(parsed)+ const snapshot = parseAllowedModelsSnapshot(cm, 'deployment-default')+ expect(snapshot.connectionStatus).toBe('disconnected')+ expect(snapshot.enabledModels?.has('codex-subscription:gpt-5.3-codex')).toBe(false)+ })+it('does not mark a Host eligible for a model that only another grant serves', () => {const cm = multiGrantConfigMap()const parsed = JSON.parse(diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.ts b/host-context-controller/src/llmAllowedModelsSnapshot.tsindex 1bee89510..2ae8da7ee 100644--- a/host-context-controller/src/llmAllowedModelsSnapshot.ts+++ b/host-context-controller/src/llmAllowedModelsSnapshot.ts@@ -111,13 +111,16 @@ export function parseAllowedModelsSnapshot(connectionRevision = assigned.connectionRevision as number}intersectCodexModels(enabledModels, staleModels, assigned.models, connectionKey)- } else if (connectionKey !== 'deployment-default') {+ } else {connectionStatus = 'disconnected'dropCodexModels(enabledModels, staleModels)}} catch {return snapshotFromConfigMapError('malformed')}+ } else if (connectionKey !== 'deployment-default') {+ connectionStatus = 'disconnected'+ dropCodexModels(enabledModels, staleModels)}return {flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 980716b1a..b2baff575 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 dc686fc87..890a54720 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/config/configStore.test.ts b/mcp-host/src/config/configStore.test.tsindex 315a99bb2..34faf1c4a 100644--- a/mcp-host/src/config/configStore.test.ts+++ b/mcp-host/src/config/configStore.test.ts@@ -827,4 +827,35 @@ describe('ConfigStore — allowlist tier (R3)', () => {expect(store.codexPolicyBinding()?.connectionKey).toBe('personal-pro')expect(store.codexPolicyBinding()?.models).toEqual(['gpt-5.1'])})++ it('does not inherit another grant when the assigned connection is missing from the map', async () => {+ const built = build({+ provider: 'codex-subscription',+ connectionRef: 'ghost-grant',+ secrets: { 'chatllm-api-keys': { 'openai-api-key': 'sk' } },+ allowlistConfigMapName: ALLOWLIST_CM,+ configMaps: {+ [ALLOWLIST_CM]: {+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex' }]),+ },+ },+ configMapAnnotations: {+ [ALLOWLIST_CM]: {+ 'clerum.io/catalog-revision': '4',+ 'clerum.io/connection-revision': '2',+ 'clerum.io/codex-connections': JSON.stringify({+ 'personal-pro': {+ catalogRevision: 4,+ connectionRevision: 2,+ models: ['gpt-5.3-codex'],+ },+ }),+ },+ },+ })+ store = built.store+ await store.start()+ expect(store.codexPolicyBinding()).toBeNull()+ expect(store.allowedModels().get('codex-subscription')).toEqual([])+ })})diff --git a/mcp-host/src/config/configStore.ts b/mcp-host/src/config/configStore.tsindex ca564aaac..db57da08a 100644--- a/mcp-host/src/config/configStore.ts+++ b/mcp-host/src/config/configStore.ts@@ -632,7 +632,7 @@ export class ConfigStore {if (Array.isArray(binding?.models)) {const allowed = new Set(binding.models)entries = entries.filter(entry => allowed.has(entry.model))- } else if (binding && binding.connectionKey !== 'deployment-default') {+ } else if (!binding || binding.connectionKey !== 'deployment-default') {entries = []}}@@ -962,10 +962,12 @@ function parseCodexPolicyBinding(models: Array.isArray(assigned.models) ? assigned.models.filter(Boolean) : undefined,}}+ return null} catch {return null}}+ if (connectionKey !== 'deployment-default') return nullif (catalogRevision === null ||catalogRevision === 'invalid' ||diff --git a/mcp-host/src/llm/index.ts b/mcp-host/src/llm/index.tsindex bad16dd1d..36272b562 100644--- a/mcp-host/src/llm/index.ts+++ b/mcp-host/src/llm/index.ts@@ -63,7 +63,7 @@ export function createLLMProvider(const modelName = modelConfig?.nameif (!isLlmProvider(provider)) {- console.error(`[LLM] Unknown provider: ${provider}`)+ console.error('[LLM] Unknown provider: %s', provider)return null}@@ -74,7 +74,7 @@ export function createLLMProvider(const credentials = keys[provider] ?? {}for (const slot of descriptorFor(provider).credentialSlots) {if (slot.required && !credentials[slot.dataKey]) {- console.error(`[LLM] ${provider} credential '${slot.dataKey}' not found in secrets`)+ console.error('[LLM] %s credential %s not found in secrets', provider, slot.dataKey)return null}}@@ -94,8 +94,9 @@ export function createLLMProvider()} catch (err) {console.error(- `[LLM] failed to construct ${provider}:`,- err instanceof Error ? err.message : String(err)+ '[LLM] failed to construct %s: %s',+ provider,+ err instanceof Error ? err.message : 'error')return null}diff --git a/mcp-host/src/logger.test.ts b/mcp-host/src/logger.test.tsnew file mode 100644index 000000000..7dbc0a97b--- /dev/null+++ b/mcp-host/src/logger.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest'+import { redactUnknown } from './logger.js'++describe('mcp-host structured logger redaction', () => {+ it('does not serialize process.env or secret-bearing fields', () => {+ process.env.MCP_HOST_LOGGER_PROBE = 'env-secret-value'+ expect(redactUnknown(process.env)).toBe('[Redacted]')+ expect(redactUnknown({ accessToken: 'sk-live', ok: true })).toEqual({+ accessToken: '[Redacted]',+ ok: true,+ })+ delete process.env.MCP_HOST_LOGGER_PROBE+ })+})diff --git a/mcp-host/src/logger.ts b/mcp-host/src/logger.tsindex 9d08f78b0..75321acc9 100644--- a/mcp-host/src/logger.ts+++ b/mcp-host/src/logger.ts@@ -14,48 +14,62 @@* import "./logger";*/-const COMPONENT_RE = /^\[([^\]]+)\]\s*/;+const COMPONENT_RE = /^\[([^\]]+)\]\s*/+const SENSITIVE_KEY_RE =+ /password|secret|token|authorization|cookie|api[_-]?key|dsn|private|refresh|credential/i-const originalLog = console.log.bind(console);-const originalError = console.error.bind(console);-const originalWarn = console.warn.bind(console);+const originalLog = console.log.bind(console)+const originalError = console.error.bind(console)+const originalWarn = console.warn.bind(console)++export function redactUnknown(value: unknown, key?: string): unknown {+ if (value === process.env) return '[Redacted]'+ if (key && SENSITIVE_KEY_RE.test(key)) return '[Redacted]'+ if (Array.isArray(value)) return value.map(item => redactUnknown(item))+ if (value && typeof value === 'object') {+ const out: Record<string, unknown> = {}+ for (const [childKey, childValue] of Object.entries(value as Record<string, unknown>)) {+ out[childKey] = redactUnknown(childValue, childKey)+ }+ return out+ }+ return value+}function formatArgs(args: unknown[]): string {- return args- .map((a) => (typeof a === "string" ? a : JSON.stringify(a)))- .join(" ");+ return args.map(a => (typeof a === 'string' ? a : JSON.stringify(redactUnknown(a)))).join(' ')}function emit(level: string, args: unknown[]): void {- const raw = formatArgs(args);+ const raw = formatArgs(args)// Skip empty lines and separator lines (====, ----)- const trimmed = raw.trim();- if (!trimmed || /^[=\-]{3,}$/.test(trimmed)) return;+ const trimmed = raw.trim()+ if (!trimmed || /^[=\-]{3,}$/.test(trimmed)) return- let component = "";- let msg = raw;+ let component = ''+ let msg = raw- const match = raw.match(COMPONENT_RE);+ const match = raw.match(COMPONENT_RE)if (match) {- component = match[1];- msg = raw.slice(match[0].length);+ component = match[1]+ msg = raw.slice(match[0].length)}const entry: Record<string, string> = {timestamp: new Date().toISOString(),level,msg: msg.trim(),- };+ }if (component) {- entry.component = component;+ entry.component = component}- const writer = level === "error" ? originalError : originalLog;- writer(JSON.stringify(entry));+ const writer = level === 'error' ? originalError : originalLog+ writer(JSON.stringify(entry))}-console.log = (...args: unknown[]) => emit("info", args);-console.error = (...args: unknown[]) => emit("error", args);-console.warn = (...args: unknown[]) => emit("warn", args);+console.log = (...args: unknown[]) => emit('info', args)+console.error = (...args: unknown[]) => emit('error', args)+console.warn = (...args: unknown[]) => emit('warn', args)diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 14c63a7c8..90ec643e3 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -28,7 +28,6 @@ import { ConfigStore } from './config/configStore'import {contextWindowForModel,hostSubsetAllowlistView,- isModelAllowed,projectModels,resolveSessionModel,} from './config/modelResolution'@@ -98,9 +97,9 @@ import {import { PluginWorkloadSdkBootstrapServer } from './pluginWorkloadSdk/bootstrapServer'import { maybeCreatePluginWorkloadSdkServer } from './pluginWorkloadSdk/server'import type { PluginWorkloadSdkServer } from './pluginWorkloadSdk/server/sdkServer'-import { getDisplayName, sanitizeError } from './progress/intentExtraction'+import { sanitizeError } from './progress/intentExtraction'import { progressReporterRegistry } from './progress/sseProgressReporter'-import { MessageQueue, Task, TaskResponsePayload } from './queue'+import { MessageQueue, Task } from './queue'import { ResultStore } from './resultStore'import { markFileAttachmentsDelivered } from './runtime/fileAttachmentDelivery'import { isUndeliveredResult, markResultDelivered } from './runtime/resultDelivery'diff --git a/tests/e2e/integration/network-policies.test.ts b/tests/e2e/integration/network-policies.test.tsindex 8eedc50ba..d103a2fa1 100644--- a/tests/e2e/integration/network-policies.test.ts+++ b/tests/e2e/integration/network-policies.test.ts@@ -190,6 +190,9 @@ describe('Codex LLM proxy NetworkPolicy contract (static)', () => {expect(rendered).toContain('name: codex-llm-proxy-ingress')expect(rendered).toContain('name: codex-llm-proxy-egress')expect(rendered).toMatch(/port: 8080[\s\S]*clerum.io\/managed-by: host-context-controller/)+ expect(rendered).toMatch(+ /kubernetes.io\/metadata.name: sandbox-recipes[\s\S]*clerum.io\/component: workflow-mcp-host/+ )expect(rendered).toMatch(/app: control-api[\s\S]*port: 8081/)expect(rendered).toContain('kubernetes.io/metadata.name: monitoring')expect(rendered).not.toMatch(/codex-llm-proxy-ingress[\s\S]*namespaceSelector: \{\}/)diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.jsonindex 5d46fa2b3..7198158b0 100644--- a/tests/e2e/package-lock.json+++ b/tests/e2e/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-e2e-tests",- "version": "0.1.70",+ "version": "0.1.71","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-e2e-tests",- "version": "0.1.70",+ "version": "0.1.71","devDependencies": {"@types/jsonwebtoken": "^9.0.10","@types/node": "^22.0.0",diff --git a/tests/e2e/package.json b/tests/e2e/package.jsonindex ba921241d..7ede287f0 100644--- a/tests/e2e/package.json+++ b/tests/e2e/package.json@@ -1,6 +1,6 @@{"name": "clerum-e2e-tests",- "version": "0.1.70",+ "version": "0.1.71","private": true,"type": "module","scripts": {diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex a8648f947..2d128d296 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.305",+ "version": "0.1.306","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.305",+ "version": "0.1.306","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 7adc743ca..4a6681ac1 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.305",+ "version": "0.1.306","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.test.ts b/workflow-recipes/src/workflow/codexExecutionProjection.test.tsindex 32d94e3ec..cd005d03e 100644--- a/workflow-recipes/src/workflow/codexExecutionProjection.test.ts+++ b/workflow-recipes/src/workflow/codexExecutionProjection.test.ts@@ -75,16 +75,22 @@ describe('projectCodexExecution (WRC)', () => {}})- it('anti-false-positive: changing the catalog revision used in the hash must drift', () => {+ it('does not roll the drift hash on catalog refresh; credential revision still drifts', () => {const eligible = fixture.cases.find(testCase => testCase.id === 'flag-on-connected-ready')expect(eligible).toBeDefined()const baseline = projectCodexExecution(eligible!.spec, eligible!.snapshot)- const mutated = projectCodexExecution(eligible!.spec, {+ const catalogOnly = projectCodexExecution(eligible!.spec, {...eligible!.snapshot,catalogRevision: (eligible!.snapshot.catalogRevision ?? 1) + 99,+ catalogContentHash: 'catalog-only-refresh',})- expect(mutated.derivedScopes).toEqual(baseline.derivedScopes)- expect(mutated.driftHashInput).not.toBe(baseline.driftHashInput)+ const credentialChanged = projectCodexExecution(eligible!.spec, {+ ...eligible!.snapshot,+ connectionRevision: (eligible!.snapshot.connectionRevision ?? 1) + 1,+ })+ expect(catalogOnly.derivedScopes).toEqual(baseline.derivedScopes)+ expect(catalogOnly.driftHashInput).toBe(baseline.driftHashInput)+ expect(credentialChanged.driftHashInput).not.toBe(baseline.driftHashInput)})it('treats a malformed empty broker model as ineligible', () => {diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.ts b/workflow-recipes/src/workflow/codexExecutionProjection.tsindex 91a149315..b069dae99 100644--- a/workflow-recipes/src/workflow/codexExecutionProjection.ts+++ b/workflow-recipes/src/workflow/codexExecutionProjection.ts@@ -205,8 +205,6 @@ function freezeProjection(const driftHashInput = JSON.stringify({eligibleTargets: input.eligibleTargets,derivedScopes: input.derivedScopes,- catalogContentHash: input.catalogContentHash,- catalogRevision: input.catalogRevision,connectionRevision: input.connectionRevision,eligibility: input.eligibility,})diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.tsindex 668783a5e..06004ba76 100644--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts@@ -44,4 +44,16 @@ describe('WRC parseAllowedModelsSnapshot per assigned connection', () => {expect(snapshot.connectionStatus).toBe('connected')expect(snapshot.catalogRevision).toBe(4)})++ it('does not rematch a missing deployment-default onto another grant in the map', () => {+ const cm = multiGrantConfigMap()+ const parsed = JSON.parse(+ String(cm.metadata.annotations['clerum.io/codex-connections'])+ ) as Record<string, unknown>+ delete parsed['deployment-default']+ cm.metadata.annotations['clerum.io/codex-connections'] = JSON.stringify(parsed)+ const snapshot = parseAllowedModelsSnapshot(cm, 'deployment-default')+ expect(snapshot.connectionStatus).toBe('disconnected')+ expect(snapshot.enabledModels?.has('codex-subscription:gpt-5.3-codex')).toBe(false)+ })})diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.tsindex 6d3a3f581..eb6ead455 100644--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts@@ -112,13 +112,16 @@ export function parseAllowedModelsSnapshot(connectionRevision = assigned.connectionRevision as number}intersectCodexModels(enabledModels, staleModels, assigned.models, connectionKey)- } else if (connectionKey !== 'deployment-default') {+ } else {connectionStatus = 'disconnected'dropCodexModels(enabledModels, staleModels)}} catch {return snapshotFromConfigMapError('malformed')}+ } else if (connectionKey !== 'deployment-default') {+ connectionStatus = 'disconnected'+ dropCodexModels(enabledModels, staleModels)}return {flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',