Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(codex): bind named grants to OAuth state and per-connection catalogs

Alfredo Lopez60b9bb1aabe0
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index e0697b7ef..86fb0fcd1 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.489",
+ "version": "0.1.490",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.489",
+ "version": "0.1.490",
"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.json
index ed0cabcc0..9b05f4639 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.489",
+ "version": "0.1.490",
"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.ts
index 9e5ac8705..f87df8e7b 100644
--- a/control-api/src/routes/admin/codexSubscription.ts
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -15,6 +15,7 @@ import {
CodexSubscriptionInvalidConnectionKeyError,
assertCodexConnectionKey,
createNamedCodexSubscriptionConnection,
+ generateCodexConnectionKey,
listSafeCodexSubscriptionConnections,
loadCodexSubscriptionSecrets,
normalizeCodexConnectionKey,
@@ -82,7 +83,9 @@ function sendOAuthError(
const status =
err.code === 'disabled'
? 404
- : err.code === 'replacement_required' || err.code === 'fingerprint_in_use'
+ : err.code === 'replacement_required' ||
+ err.code === 'fingerprint_in_use' ||
+ err.code === 'connection_mismatch'
? 409
: err.code === 'refresh_in_flight' || err.code === 'stale_revision'
? 409
@@ -99,16 +102,6 @@ function sendOAuthError(
throw err
}
-function slugFromDisplayName(displayName: string): string {
- const slug = displayName
- .trim()
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '')
- .slice(0, 63)
- return slug || `codex-${Date.now().toString(36)}`
-}
-
function hostConnectionRef(spec: unknown): string | null {
if (!spec || typeof spec !== 'object') return null
const model = (spec as { model?: { provider?: string; connectionRef?: string } }).model
@@ -122,27 +115,43 @@ export function createAdminCodexSubscriptionRouter(
): Router {
const router = Router()
- async function assignedHostsFor(connectionKey: string): Promise<Array<{ name: string }>> {
- if (!gateway) return []
+ async function listHostsOrUnavailable(): Promise<Array<{
+ metadata?: { name?: string }
+ spec?: unknown
+ }> | null> {
+ if (!gateway) return null
try {
- const hosts = (await gateway.listResource('hosts', config.hostsNamespace)) as Array<{
+ return (await gateway.listResource('hosts', config.hostsNamespace)) as Array<{
metadata?: { name?: string }
spec?: unknown
}>
- return hosts
- .filter(host => hostConnectionRef(host.spec) === connectionKey)
- .map(host => ({ name: String(host.metadata?.name ?? '') }))
- .filter(host => host.name)
} catch (err) {
log.warn({ event: 'codex_assigned_hosts_list_failed', err }, 'failed to list assigned hosts')
- return []
+ return null
}
}
- async function withAssignedHosts<T extends { connectionKey: string }>(connection: T) {
+ function hostsForConnection(
+ hosts: Array<{ metadata?: { name?: string }; spec?: unknown }>,
+ connectionKey: string
+ ): Array<{ name: string }> {
+ return hosts
+ .filter(host => hostConnectionRef(host.spec) === connectionKey)
+ .map(host => ({ name: String(host.metadata?.name ?? '') }))
+ .filter(host => host.name)
+ }
+
+ async function withAssignedHosts<T extends { connectionKey: string }>(
+ connection: T,
+ hosts?: Array<{ metadata?: { name?: string }; spec?: unknown }> | null
+ ) {
+ const resolved = hosts === undefined ? await listHostsOrUnavailable() : hosts
+ if (resolved === null) {
+ return { ...connection, assignedHostsUnavailable: true as const }
+ }
return {
...connection,
- assignedHosts: await assignedHostsFor(connection.connectionKey),
+ assignedHosts: hostsForConnection(resolved, connection.connectionKey),
}
}
@@ -280,9 +289,10 @@ export function createAdminCodexSubscriptionRouter(
return
}
const rows = await listSafeCodexSubscriptionConnections(dbClient())
+ const hosts = await listHostsOrUnavailable()
const connections = []
for (const row of rows) {
- connections.push(await withAssignedHosts(row))
+ connections.push(await withAssignedHosts(row, hosts))
}
res.status(200).json({ connections })
})
@@ -302,10 +312,10 @@ export function createAdminCodexSubscriptionRouter(
: 'Codex subscription'
const requestedKey =
typeof req.body?.connectionKey === 'string' && req.body.connectionKey.trim()
- ? req.body.connectionKey.trim()
- : slugFromDisplayName(displayName)
+ ? assertCodexConnectionKey(req.body.connectionKey.trim())
+ : generateCodexConnectionKey()
const created = await createNamedCodexSubscriptionConnection(dbClient(), {
- connectionKey: assertCodexConnectionKey(requestedKey),
+ connectionKey: requestedKey,
displayName,
})
res.status(201).json(await withAssignedHosts(created))
diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
index 4bf7e48ab..ce5cbea39 100644
--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
@@ -4,7 +4,10 @@ import { asyncHandler } from '../../http/asyncHandler.js'
import type { K8sGateway } from '../../k8s.js'
import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'
import { rootLogger } from '../../observability/logger.js'
-import { normalizeCodexConnectionKey } from '../../services/codexSubscriptionConnection.js'
+import {
+ CODEX_SUBSCRIPTION_CONNECTION_KEY,
+ normalizeCodexConnectionKey,
+} from '../../services/codexSubscriptionConnection.js'
import {
LlmProviderAttemptAuthorizeError,
authorizeLlmProviderAttempt,
@@ -41,6 +44,9 @@ export async function resolveHostAssignedConnectionKey(
gateway: Pick<K8sGateway, 'getResource'>,
hostRef: string
): Promise<string> {
+ if (hostRef.includes('/')) {
+ return CODEX_SUBSCRIPTION_CONNECTION_KEY
+ }
try {
const host = (await gateway.getResource('hosts', hostRef, config.hostsNamespace)) as {
spec?: { model?: { connectionRef?: string } }
diff --git a/control-api/src/services/codexSubscriptionCatalog.ts b/control-api/src/services/codexSubscriptionCatalog.ts
index 748efbaed..060651cc3 100644
--- a/control-api/src/services/codexSubscriptionCatalog.ts
+++ b/control-api/src/services/codexSubscriptionCatalog.ts
@@ -175,6 +175,27 @@ export async function isCodexAssignmentAllowed(
return Boolean(state?.enabled && !state.stale)
}
+export async function listEnabledCodexModelsGroupedByConnection(
+ db: DbClient
+): Promise<Record<string, string[]>> {
+ const result = await db.query(
+ `SELECT c.connection_key AS connection_key, m.model
+ FROM codex_catalog_models m
+ JOIN codex_subscription_connections c ON c.id = m.connection_id
+ WHERE c.revoked_at IS NULL
+ AND m.enabled
+ AND m.stale = false
+ ORDER BY c.connection_key ASC, m.model ASC`
+ )
+ const grouped: Record<string, string[]> = {}
+ for (const row of result.rows as Array<{ connection_key: string; model: string }>) {
+ const key = String(row.connection_key)
+ grouped[key] ??= []
+ grouped[key].push(String(row.model))
+ }
+ return grouped
+}
+
export async function listCodexCatalogModels(
db: DbClient,
connectionId: string
@@ -193,6 +214,8 @@ export async function listCodexCatalogModels(
}))
}
+// Derived cache for the LLM Models table. Runtime eligibility uses
+// `codex_catalog_models` per connection, not these global toggles.
export async function rebuildLiveCodexUnionAllowlist(db: DbClient): Promise<void> {
await db.query(
`INSERT INTO llm_allowed_models
diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.ts
index 470fe4800..a04b95b1f 100644
--- a/control-api/src/services/codexSubscriptionConnection.ts
+++ b/control-api/src/services/codexSubscriptionConnection.ts
@@ -1,3 +1,4 @@
+import { randomBytes } from 'node:crypto'
import type { DbClient } from '../db.js'
import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'
@@ -18,6 +19,10 @@ export function assertCodexConnectionKey(value: string): string {
return key
}
+export function generateCodexConnectionKey(): string {
+ return `codex-${randomBytes(8).toString('hex')}`
+}
+
export class CodexSubscriptionInvalidConnectionKeyError extends Error {
readonly code = 'invalid_connection_key'
@@ -587,8 +592,13 @@ export async function recordCodexCatalogOutcome(
}
function remapFingerprintConflict(err: unknown): never | Error {
- const code = (err as { code?: string } | null)?.code
- if (code === '23505') return new CodexSubscriptionFingerprintConflictError()
+ const conflict = err as { code?: string; constraint?: string } | null
+ if (
+ conflict?.code === '23505' &&
+ conflict.constraint === 'codex_subscription_connections_active_fingerprint'
+ ) {
+ return new CodexSubscriptionFingerprintConflictError()
+ }
throw err
}
diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.ts
index d118f8f70..2724a4439 100644
--- a/control-api/src/services/codexSubscriptionOAuth.ts
+++ b/control-api/src/services/codexSubscriptionOAuth.ts
@@ -61,6 +61,7 @@ export type CodexOAuthErrorCode =
| 'invalid_callback'
| 'browser_oauth_unregistered'
| 'fingerprint_in_use'
+ | 'connection_mismatch'
export class CodexSubscriptionOAuthError extends Error {
readonly code: CodexOAuthErrorCode
@@ -86,6 +87,24 @@ function connectionKeyOf(deps: CodexOAuthDeps): string {
return normalizeCodexConnectionKey(deps.connectionKey)
}
+function completionConnectionKey(deps: CodexOAuthDeps, stateKey: string): string {
+ const target = normalizeCodexConnectionKey(stateKey)
+ if (deps.connectionKey !== undefined) {
+ const requested = normalizeCodexConnectionKey(deps.connectionKey)
+ if (requested !== target) {
+ log.warn(
+ { event: 'codex_oauth_connection_mismatch', requested, target },
+ 'OAuth completion key does not match the state'
+ )
+ throw new CodexSubscriptionOAuthError(
+ 'connection_mismatch',
+ 'OAuth state is bound to a different connection'
+ )
+ }
+ }
+ return target
+}
+
export type CodexBrowserStartResult = {
authorizeUrl: string
state: string
@@ -210,7 +229,12 @@ export async function handleCodexBrowserCallback(
throw new CodexSubscriptionOAuthError('invalid_callback', 'state is not a browser PKCE flow')
}
const token = await exchangeAuthorizationCode(deps, input.code, consumed.pkceVerifier)
- return persistGrantedTokens(deps, consumed.safe.intent, token)
+ return persistGrantedTokens(
+ deps,
+ consumed.safe.intent,
+ token,
+ completionConnectionKey(deps, consumed.safe.connectionKey)
+ )
}
export async function pollCodexDevice(
@@ -222,6 +246,7 @@ export async function pollCodexDevice(
if (!pending) {
throw new CodexSubscriptionOAuthError('state_replayed', 'device state is not pending')
}
+ completionConnectionKey(deps, pending.safe.connectionKey)
if (pending.safe.expiresAt.getTime() <= Date.now()) {
await expireCodexSubscriptionOAuthState(deps.db, state)
return { status: 'expired' }
@@ -259,7 +284,12 @@ export async function pollCodexDevice(
'device state was consumed concurrently'
)
}
- const connection = await persistGrantedTokens(deps, consumed.safe.intent, tokenResult.parsed)
+ const connection = await persistGrantedTokens(
+ deps,
+ consumed.safe.intent,
+ tokenResult.parsed,
+ completionConnectionKey(deps, consumed.safe.connectionKey)
+ )
return { status: 'connected', connection }
}
@@ -352,9 +382,10 @@ export async function revokeCodexSubscription(
async function persistGrantedTokens(
deps: CodexOAuthDeps,
intent: CodexSubscriptionOAuthIntent,
- parsed: ParsedCodexToken
+ parsed: ParsedCodexToken,
+ connectionKey: string
): Promise<CodexSubscriptionSafeConnection> {
- const key = connectionKeyOf(deps)
+ const key = normalizeCodexConnectionKey(connectionKey)
const existing = await getSafeCodexSubscriptionConnection(deps.db, key)
if (
existing?.accountFingerprint &&
@@ -381,16 +412,25 @@ async function persistGrantedTokens(
)
}
if (!existing) {
- return insertInitialCodexSubscriptionConnection(deps.db, deps.encryptionKey, write, key)
+ const created = await insertInitialCodexSubscriptionConnection(
+ deps.db,
+ deps.encryptionKey,
+ write,
+ key
+ )
+ log.info({ event: 'codex_oauth_persisted', connectionKey: key }, 'Codex grant persisted')
+ return created
}
try {
- return await rotateCodexSubscriptionCredentials(
+ const rotated = await rotateCodexSubscriptionCredentials(
deps.db,
deps.encryptionKey,
existing.credentialRevision,
write,
key
)
+ log.info({ event: 'codex_oauth_persisted', connectionKey: key }, 'Codex grant persisted')
+ return rotated
} catch (err) {
if (err instanceof CodexSubscriptionStaleRevisionError) {
throw new CodexSubscriptionOAuthError(
diff --git a/control-api/src/services/codexSubscriptionOAuthState.ts b/control-api/src/services/codexSubscriptionOAuthState.ts
index c3103d17e..b9be453da 100644
--- a/control-api/src/services/codexSubscriptionOAuthState.ts
+++ b/control-api/src/services/codexSubscriptionOAuthState.ts
@@ -10,6 +10,7 @@ export type CodexSubscriptionOAuthSafeState = {
flow: CodexSubscriptionOAuthFlow
intent: CodexSubscriptionOAuthIntent
status: CodexSubscriptionOAuthStateStatus
+ connectionKey: string
expiresAt: Date
consumedAt: Date | null
cancelledAt: Date | null
@@ -38,6 +39,7 @@ type SafeOAuthStateRow = {
flow: CodexSubscriptionOAuthFlow
intent: CodexSubscriptionOAuthIntent
status: CodexSubscriptionOAuthStateStatus
+ connection_key: string | null
expires_at: Date | string
consumed_at: Date | string | null
cancelled_at: Date | string | null
@@ -54,6 +56,7 @@ const SAFE_OAUTH_STATE_COLUMNS = `
flow,
intent,
status,
+ connection_key,
expires_at,
consumed_at,
cancelled_at,
@@ -227,6 +230,10 @@ function toSafeOAuthState(row: SafeOAuthStateRow): CodexSubscriptionOAuthSafeSta
flow: row.flow,
intent: row.intent,
status: row.status,
+ connectionKey:
+ typeof row.connection_key === 'string' && row.connection_key.trim()
+ ? row.connection_key.trim()
+ : 'deployment-default',
expiresAt: asDate(row.expires_at) ?? new Date(0),
consumedAt: asDate(row.consumed_at),
cancelledAt: asDate(row.cancelled_at),
diff --git a/control-api/src/services/llmAllowedModelsConfigMap.ts b/control-api/src/services/llmAllowedModelsConfigMap.ts
index 9788f2376..d5912a4ac 100644
--- a/control-api/src/services/llmAllowedModelsConfigMap.ts
+++ b/control-api/src/services/llmAllowedModelsConfigMap.ts
@@ -22,6 +22,7 @@ import { createHash } from 'node:crypto'
import { config } from '../config.js'
import type { DbClient } from '../db.js'
import { pool } from '../db.js'
+import { listEnabledCodexModelsGroupedByConnection } from './codexSubscriptionCatalog.js'
import {
type CodexSubscriptionSafeConnection,
getSafeCodexSubscriptionConnection,
@@ -64,7 +65,8 @@ export function mapCodexConnectionStatusForSnapshot(
export function buildCodexReadinessAnnotations(
connection: CodexSubscriptionSafeConnection | null,
- connections: CodexSubscriptionSafeConnection[] = []
+ connections: CodexSubscriptionSafeConnection[] = [],
+ modelsByKey: Record<string, string[]> = {}
): Record<string, string> {
const annotations: Record<string, string> = {
[CODEX_ENABLED_ANNOTATION]: config.codexSubscriptionEnabled ? 'true' : 'false',
@@ -85,6 +87,7 @@ export function buildCodexReadinessAnnotations(
status: ReturnType<typeof mapCodexConnectionStatusForSnapshot>
catalogRevision: number
connectionRevision: number
+ models: string[]
}
> = {}
for (const row of connections) {
@@ -92,6 +95,7 @@ export function buildCodexReadinessAnnotations(
status: mapCodexConnectionStatusForSnapshot(row),
catalogRevision: row.catalogRevision,
connectionRevision: row.credentialRevision,
+ models: modelsByKey[row.connectionKey] ?? [],
}
}
if (Object.keys(map).length > 0) {
@@ -157,11 +161,13 @@ export class LlmAllowedModelsConfigMapWriter implements AllowedModelsConfigMapMa
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
+ connections,
+ modelsByKey
)
let lastError: unknown
for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 43c66b180..ef560c6fd 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -243,11 +243,11 @@ export async function authorizeLlmProviderAttempt(
)
}
+ const connectionKey = normalizeCodexConnectionKey(
+ await resolvedDeps.resolveConnectionKey(caller.hostRef)
+ )
return resolvedDeps.withTransaction(async tx => {
const db: DbClient = tx
- const connectionKey = normalizeCodexConnectionKey(
- await resolvedDeps.resolveConnectionKey(caller.hostRef)
- )
const connection = await resolvedDeps.getConnection(db, connectionKey)
if (
!connection ||
diff --git a/control-api/src/services/llmProviderAttemptRedemption.ts b/control-api/src/services/llmProviderAttemptRedemption.ts
index 2d67ee96d..b3cf21501 100644
--- a/control-api/src/services/llmProviderAttemptRedemption.ts
+++ b/control-api/src/services/llmProviderAttemptRedemption.ts
@@ -83,16 +83,20 @@ export function opaqueAttemptReceipt(input: {
export type RedeemAttemptDeps = {
enabled: boolean
+ db: { query: (text: string, values?: unknown[]) => Promise<{ rows: unknown[] }> }
withTransaction: typeof withTransaction
loadSecrets: typeof loadCodexSubscriptionSecrets
+ getConnectionById: typeof getSafeCodexSubscriptionConnectionById
encryptionKey: Buffer
ensureFreshAccessToken?: (connectionKey?: string) => Promise<void>
}
const defaultRedeemDeps = (): RedeemAttemptDeps => ({
enabled: config.codexSubscriptionEnabled,
+ db: { query: (text, values) => pool.query(text, values) },
withTransaction,
loadSecrets: loadCodexSubscriptionSecrets,
+ getConnectionById: getSafeCodexSubscriptionConnectionById,
encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),
ensureFreshAccessToken: connectionKey =>
ensureFreshCodexAccessToken({
@@ -134,10 +138,7 @@ export async function redeemLlmProviderAttempt(
try {
let refreshKey: string | undefined
if (claims.connectionId) {
- const assigned = await getSafeCodexSubscriptionConnectionById(
- { query: (text, values) => pool.query(text, values) },
- claims.connectionId
- )
+ const assigned = await deps.getConnectionById(deps.db, claims.connectionId)
refreshKey = assigned?.connectionKey
}
await deps.ensureFreshAccessToken(refreshKey)
diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.ts
index f7bf3c552..048c9f1ad 100644
--- a/control-api/test/routes.admin.codexSubscription.test.ts
+++ b/control-api/test/routes.admin.codexSubscription.test.ts
@@ -30,21 +30,51 @@ vi.mock('../src/db.js', () => ({
pool: { query: vi.fn() },
}))
+const { pool } = await import('../src/db.js')
+
const { config } = await import('../src/config.js')
+const { createCodexCatalogTransportFromEnv } =
+ await import('../src/services/codexSubscriptionCatalog.js')
const { createAdminCodexSubscriptionRouter } =
await import('../src/routes/admin/codexSubscription.js')
-function makeAuthedApp() {
+function makeAuthedApp(gateway?: { listResource: ReturnType<typeof vi.fn> }) {
const app = express()
app.use(express.json())
app.use((req: Request & { adminAuth?: { sub: string } }, _res: Response, next: NextFunction) => {
req.adminAuth = { sub: 'admin-1' }
next()
})
- app.use(createAdminCodexSubscriptionRouter())
+ app.use(
+ gateway
+ ? createAdminCodexSubscriptionRouter(createCodexCatalogTransportFromEnv(), gateway as never)
+ : createAdminCodexSubscriptionRouter()
+ )
return app
}
+function safeCreatedRow(connectionKey: string, displayName: string) {
+ return {
+ id: `id-${connectionKey}`,
+ connection_key: connectionKey,
+ display_name: displayName,
+ created_by: null,
+ status: 'disconnected',
+ credential_revision: 1,
+ catalog_revision: 0,
+ account_fingerprint: null,
+ catalog_status: 'never_synced',
+ catalog_synced_at: null,
+ last_refresh_at: null,
+ last_auth_at: null,
+ refresh_lock_token: null,
+ refresh_lock_expires_at: null,
+ revoked_at: null,
+ created_at: new Date(),
+ updated_at: new Date(),
+ }
+}
+
function assertNoLeak(body: unknown): void {
const serialized = JSON.stringify(body)
expect(serialized).not.toMatch(/sk-|Bearer |eyJ[A-Za-z0-9_-]+\.|refresh-secret|access-secret/i)
@@ -185,4 +215,59 @@ describe('admin Codex subscription routes', () => {
expect(res.body.status).toBe('revoked')
assertNoLeak(res.body)
})
+
+ it('creates two connections with the same display name and distinct generated keys', async () => {
+ vi.mocked(pool.query).mockImplementation(async (_sql: string, values?: unknown[]) => ({
+ rows: [safeCreatedRow(String(values?.[0]), String(values?.[1]))],
+ rowCount: 1,
+ }))
+ const first = await request(app)
+ .post('/admin/llm/providers/codex-subscription/connections')
+ .send({ displayName: 'Codex subscription' })
+ const second = await request(app)
+ .post('/admin/llm/providers/codex-subscription/connections')
+ .send({ displayName: 'Codex subscription' })
+ expect(first.status).toBe(201)
+ expect(second.status).toBe(201)
+ expect(first.body.connectionKey).toMatch(/^codex-[a-f0-9]{16}$/)
+ expect(second.body.connectionKey).toMatch(/^codex-[a-f0-9]{16}$/)
+ expect(first.body.connectionKey).not.toBe(second.body.connectionKey)
+ expect(first.body.displayName).toBe('Codex subscription')
+ expect(second.body.displayName).toBe('Codex subscription')
+ expect(first.body.assignedHostsUnavailable).toBe(true)
+ assertNoLeak(first.body)
+ assertNoLeak(second.body)
+ })
+
+ it('marks assigned hosts unavailable when the Host list fails', async () => {
+ oauth.getConnection.mockResolvedValue({
+ connectionKey: 'team-plus',
+ status: 'connected',
+ credentialRevision: 2,
+ catalogRevision: 1,
+ accountFingerprint: 'fp',
+ })
+ const gateway = { listResource: vi.fn().mockRejectedValue(new Error('k8s down')) }
+ const hosted = makeAuthedApp(gateway)
+ const res = await request(hosted).get(
+ '/admin/llm/providers/codex-subscription/connections/team-plus'
+ )
+ expect(res.status).toBe(200)
+ expect(res.body.assignedHostsUnavailable).toBe(true)
+ expect(res.body.assignedHosts).toBeUndefined()
+ expect(gateway.listResource).toHaveBeenCalled()
+ assertNoLeak(res.body)
+ })
+
+ it('maps a keyed poll connection mismatch to 409', async () => {
+ oauth.pollDevice.mockRejectedValue(
+ new CodexSubscriptionOAuthError('connection_mismatch', 'bound elsewhere')
+ )
+ const res = await request(app).get(
+ '/admin/llm/providers/codex-subscription/connections/other-key/device/poll'
+ )
+ expect(res.status).toBe(409)
+ expect(res.body).toEqual({ error: 'connection_mismatch' })
+ assertNoLeak(res.body)
+ })
})
diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
index 4e21ed934..e45d05f04 100644
--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
@@ -133,6 +133,16 @@ describe('resolveHostAssignedConnectionKey', () => {
)
})
+ it('aliases a recipe caller to deployment-default without a Host GET', async () => {
+ const gateway = {
+ getResource: vi.fn(),
+ }
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')
+ ).resolves.toBe('deployment-default')
+ expect(gateway.getResource).not.toHaveBeenCalled()
+ })
+
it('fails closed when the Host cannot be attested', async () => {
const gateway = {
getResource: vi.fn().mockRejectedValue(Object.assign(new Error('nf'), { code: 404 })),
diff --git a/control-api/test/services.codexSubscriptionConnection.test.ts b/control-api/test/services.codexSubscriptionConnection.test.ts
index 00a44c26f..dc7d33f8a 100644
--- a/control-api/test/services.codexSubscriptionConnection.test.ts
+++ b/control-api/test/services.codexSubscriptionConnection.test.ts
@@ -3,6 +3,7 @@ import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encry
import {
CodexSubscriptionFingerprintConflictError,
CodexSubscriptionStaleRevisionError,
+ generateCodexConnectionKey,
getSafeCodexSubscriptionConnection,
insertInitialCodexSubscriptionConnection,
rotateCodexSubscriptionCredentials,
@@ -112,7 +113,12 @@ describe('codex subscription connection repository', () => {
})
it('maps a unique active fingerprint violation to fingerprint_in_use', async () => {
- query.mockRejectedValueOnce(Object.assign(new Error('duplicate'), { code: '23505' }))
+ query.mockRejectedValueOnce(
+ Object.assign(new Error('duplicate'), {
+ code: '23505',
+ constraint: 'codex_subscription_connections_active_fingerprint',
+ })
+ )
await expect(
insertInitialCodexSubscriptionConnection(
{ query },
@@ -126,6 +132,25 @@ describe('codex subscription connection repository', () => {
).rejects.toBeInstanceOf(CodexSubscriptionFingerprintConflictError)
})
+ it('does not remap an unrelated unique violation to fingerprint_in_use', async () => {
+ const err = Object.assign(new Error('duplicate key'), {
+ code: '23505',
+ constraint: 'codex_subscription_connections_pkey',
+ })
+ query.mockRejectedValueOnce(err)
+ await expect(
+ insertInitialCodexSubscriptionConnection(
+ { query },
+ KEY,
+ {
+ refreshToken: 'plain-refresh',
+ accountFingerprint: 'fp_other',
+ },
+ 'team-plus'
+ )
+ ).rejects.toBe(err)
+ })
+
it('rejects a stale credential_revision writer', async () => {
query.mockResolvedValueOnce({ rows: [], rowCount: 0 })
await expect(
@@ -137,4 +162,12 @@ describe('codex subscription connection repository', () => {
const [sql] = query.mock.calls[0] as [string]
expect(sql).toMatch(/credential_revision = \$/)
})
+
+ it('generates distinct identity keys that are not derived from the display name', () => {
+ const keys = new Set(Array.from({ length: 8 }, () => generateCodexConnectionKey()))
+ expect(keys.size).toBe(8)
+ for (const key of keys) {
+ expect(key).toMatch(/^codex-[a-f0-9]{16}$/)
+ }
+ })
})
diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.ts
index 548f05759..6bb1bada3 100644
--- a/control-api/test/services.codexSubscriptionOAuth.test.ts
+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts
@@ -521,4 +521,130 @@ describe('codex subscription OAuth broker', () => {
expect(err).toBeInstanceOf(Error)
expect(err.code).toBe('replacement_required')
})
+
+ it('persists a named browser grant from the OAuth state, not from empty deps', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ access_token: 'access-secret',
+ refresh_token: 'refresh-secret',
+ expires_in: 60,
+ id_token: idTokenFor('acct_raw_123'),
+ }),
+ })
+ repos.consumeState.mockResolvedValue({
+ safe: {
+ state: 'state-named',
+ flow: 'browser',
+ intent: 'connect',
+ status: 'consumed',
+ connectionKey: 'team-plus',
+ expiresAt: new Date(Date.now() + 1000),
+ consumedAt: new Date(),
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ pkceVerifier: 'verifier',
+ })
+ repos.getSafe.mockResolvedValue(null)
+ repos.insertInitial.mockResolvedValue({
+ connectionKey: 'team-plus',
+ status: 'connected',
+ credentialRevision: 1,
+ })
+ const result = await handleCodexBrowserCallback(deps(fetchFn), {
+ code: 'code-1',
+ state: 'state-named',
+ })
+ expect(result.connectionKey).toBe('team-plus')
+ expect(repos.insertInitial.mock.calls[0]?.[3]).toBe('team-plus')
+ expect(repos.getSafe.mock.calls[0]?.[1]).toBe('team-plus')
+ })
+
+ it('rejects a device poll whose route key does not match the state', async () => {
+ repos.peekState.mockResolvedValue({
+ safe: {
+ state: 'state-1',
+ flow: 'device',
+ intent: 'connect',
+ status: 'pending',
+ connectionKey: 'team-plus',
+ expiresAt: new Date(Date.now() + 60_000),
+ consumedAt: null,
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ deviceCode: JSON.stringify({ deviceAuthId: 'id', userCode: 'ABCD' }),
+ })
+ await expect(
+ pollCodexDevice({ ...deps(vi.fn()), connectionKey: 'deployment-default' }, 'state-1')
+ ).rejects.toMatchObject({
+ code: 'connection_mismatch',
+ })
+ expect(repos.consumeState).not.toHaveBeenCalled()
+ })
+
+ it('persists a keyed device poll onto the matching state connection', async () => {
+ const handle = JSON.stringify({ deviceAuthId: 'deviceauth_secret', userCode: 'ABCD-EFGH' })
+ repos.peekState.mockResolvedValue({
+ safe: {
+ state: 'state-match',
+ flow: 'device',
+ intent: 'connect',
+ status: 'pending',
+ connectionKey: 'team-plus',
+ expiresAt: new Date(Date.now() + 60_000),
+ consumedAt: null,
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ deviceCode: handle,
+ })
+ repos.consumeState.mockResolvedValue({
+ safe: {
+ state: 'state-match',
+ flow: 'device',
+ intent: 'connect',
+ status: 'consumed',
+ connectionKey: 'team-plus',
+ expiresAt: new Date(Date.now() + 60_000),
+ consumedAt: new Date(),
+ cancelledAt: null,
+ createdAt: new Date(),
+ },
+ deviceCode: handle,
+ })
+ repos.getSafe.mockResolvedValue(null)
+ repos.insertInitial.mockResolvedValue({
+ connectionKey: 'team-plus',
+ status: 'connected',
+ credentialRevision: 1,
+ })
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ authorization_code: 'authz-code',
+ code_verifier: 'pkce-from-poll',
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ access_token: 'access-secret',
+ refresh_token: 'refresh-secret',
+ expires_in: 60,
+ id_token: idTokenFor('acct_raw_123'),
+ }),
+ })
+ const result = await pollCodexDevice(
+ { ...deps(fetchFn), connectionKey: 'team-plus' },
+ 'state-match'
+ )
+ expect(result).toMatchObject({ status: 'connected' })
+ expect(repos.insertInitial.mock.calls[0]?.[3]).toBe('team-plus')
+ })
})
diff --git a/control-api/test/services.llmAllowedModelsConfigMap.test.ts b/control-api/test/services.llmAllowedModelsConfigMap.test.ts
index 55f347e14..09ab3112d 100644
--- a/control-api/test/services.llmAllowedModelsConfigMap.test.ts
+++ b/control-api/test/services.llmAllowedModelsConfigMap.test.ts
@@ -281,13 +281,18 @@ describe('Codex readiness annotations', () => {
catalogStatus: 'ready' as const,
}
expect(mapCodexConnectionStatusForSnapshot(revoked)).toBe('revoked')
- const annotations = buildCodexReadinessAnnotations(live, [revoked, live])
+ const annotations = buildCodexReadinessAnnotations(live, [revoked, live], {
+ 'personal-pro': ['gpt-5.3-codex'],
+ 'team-plus': ['gpt-5.1'],
+ })
const map = JSON.parse(annotations['clerum.io/codex-connections'] as string) as Record<
string,
- { status: string }
+ { status: string; models: string[] }
>
expect(map['team-plus'].status).toBe('revoked')
expect(map['personal-pro'].status).toBe('connected')
+ expect(map['personal-pro'].models).toEqual(['gpt-5.3-codex'])
+ expect(map['team-plus'].models).toEqual(['gpt-5.1'])
})
it('omits revision annotations when the connection row is absent', () => {
diff --git a/control-api/test/services.llmProviderAttemptRedemption.test.ts b/control-api/test/services.llmProviderAttemptRedemption.test.ts
index 4c8ec1a69..dbe698e68 100644
--- a/control-api/test/services.llmProviderAttemptRedemption.test.ts
+++ b/control-api/test/services.llmProviderAttemptRedemption.test.ts
@@ -90,6 +90,8 @@ describe('redeemLlmProviderAttempt', () => {
{ executionTicket: 'ticket', requestHash: CLAIMS.requestHash },
{
enabled: true,
+ db: { query: vi.fn() },
+ getConnectionById: vi.fn(),
withTransaction: async work => work({ query: vi.fn() } as never),
loadSecrets: async () => ({
refreshToken: 'refresh-secret',
@@ -123,6 +125,8 @@ describe('redeemLlmProviderAttempt', () => {
{ executionTicket: 'ticket', requestHash: CLAIMS.requestHash },
{
enabled: true,
+ db: { query: vi.fn() },
+ getConnectionById: vi.fn(),
withTransaction: async work => work({ query: vi.fn() } as never),
loadSecrets: async () => {
throw new Error('should not load secrets')
@@ -163,6 +167,8 @@ describe('redeemLlmProviderAttempt', () => {
{ executionTicket: 'ticket', requestHash: CLAIMS.requestHash },
{
enabled: true,
+ db: { query: vi.fn() },
+ getConnectionById: vi.fn(),
withTransaction: async work => work({ query: vi.fn() } as never),
loadSecrets: async () => {
throw new Error('should not load secrets after revoke')
@@ -179,6 +185,8 @@ describe('redeemLlmProviderAttempt', () => {
{ executionTicket: 'ticket', requestHash: CLAIMS.requestHash },
{
enabled: false,
+ db: { query: vi.fn() },
+ getConnectionById: vi.fn(),
withTransaction: async () => {
throw new Error('should not run')
},
@@ -195,6 +203,8 @@ describe('redeemLlmProviderAttempt', () => {
{ executionTicket: 'ticket', requestHash: CLAIMS.requestHash },
{
enabled: true,
+ db: { query: vi.fn() },
+ getConnectionById: vi.fn(),
withTransaction: async work => work({ query: vi.fn() } as never),
loadSecrets: async () => ({
refreshToken: 'refresh-secret',
diff --git a/control-ui/components/CodexAgentAssignment/index.tsx b/control-ui/components/CodexAgentAssignment/index.tsx
index 02c551e7d..1b4cad18d 100644
--- a/control-ui/components/CodexAgentAssignment/index.tsx
+++ b/control-ui/components/CodexAgentAssignment/index.tsx
@@ -51,26 +51,23 @@ export function CodexAgentAssignment({
if (!isCodexSubscriptionUiEnabled()) return
const rows = await listCodexSubscriptionConnections()
setConnections(rows)
- const current =
- rows.find(row => row.connectionKey === connectionRef) ??
- rows.find(row => row.connectionKey === 'deployment-default') ??
- rows[0] ??
- null
+ const current = rows.find(row => row.connectionKey === connectionRef) ?? null
setSelected(current)
- if (current && current.connectionKey !== connectionRef) {
- onConnectionRefChange(current.connectionKey)
- }
if (current?.status === 'connected') {
const models = await listCodexConnectionModels(current.connectionKey)
onModelsChange?.(models.filter(row => row.enabled && !row.stale).map(row => row.model))
} else {
onModelsChange?.([])
}
- }, [connectionRef, onConnectionRefChange, onModelsChange])
+ }, [connectionRef, onModelsChange])
useEffect(() => {
- void load().catch(() => undefined)
- }, [load])
+ void load().catch(err => {
+ showToast(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions', {
+ tone: 'error',
+ })
+ })
+ }, [load, showToast])
const assignable = connections.filter(
row => row.status !== 'revoked' || row.connectionKey === connectionRef
@@ -87,10 +84,8 @@ export function CodexAgentAssignment({
onConnectionRefChange(created.connectionKey)
await load()
} catch (err) {
- showToast({
- type: 'error',
- title: 'Could not create subscription',
- message: err instanceof Error ? err.message : 'Request failed',
+ showToast(err instanceof Error ? err.message : 'Could not create subscription', {
+ tone: 'error',
})
} finally {
setBusy(false)
@@ -120,11 +115,7 @@ export function CodexAgentAssignment({
if (polled.status === 'expired' || polled.status === 'denied') break
}
} catch (err) {
- showToast({
- type: 'error',
- title: 'ChatGPT sign-in failed',
- message: err instanceof Error ? err.message : 'Request failed',
- })
+ showToast(err instanceof Error ? err.message : 'ChatGPT sign-in failed', { tone: 'error' })
} finally {
setBusy(false)
}
@@ -136,18 +127,19 @@ export function CodexAgentAssignment({
try {
await syncCodexSubscriptionCatalog(selected.connectionKey)
await load()
- showToast({
- type: 'success',
- title: 'Catalog synced',
- message: selected.displayName ?? selected.connectionKey,
+ showToast(`Catalog synced: ${selected.displayName ?? selected.connectionKey}`, {
+ tone: 'success',
})
} catch (err) {
const code = (err as { code?: string } | null)?.code
- showToast({
- type: 'error',
- title: code === 'no_grant' ? 'Connect ChatGPT first' : 'Catalog sync failed',
- message: err instanceof Error ? err.message : 'Request failed',
- })
+ showToast(
+ err instanceof Error
+ ? err.message
+ : code === 'no_grant'
+ ? 'Connect ChatGPT first'
+ : 'Catalog sync failed',
+ { tone: 'error' }
+ )
} finally {
setBusy(false)
}
@@ -158,8 +150,9 @@ export function CodexAgentAssignment({
const names = assignedHostNames(selected)
const confirmed = await confirm({
title: 'Revoke this ChatGPT subscription?',
- message:
- names.length > 0
+ message: selected.assignedHostsUnavailable
+ ? 'The agent assignment list could not be loaded. Revoke still fail-closes every Host that points at this grant.'
+ : names.length > 0
? `This subscription is used by ${names.length} agent(s): ${names.join(', ')}. Revoke disconnects all of them.${
selected.connectionKey === 'deployment-default'
? ' Workflow recipes that use a ChatGPT subscription also fail closed on this grant.'
@@ -189,10 +182,13 @@ export function CodexAgentAssignment({
<label htmlFor="codex-subscription">ChatGPT subscription</label>
<select
id="codex-subscription"
- value={selected?.connectionKey ?? ''}
+ value={selected?.connectionKey ?? connectionRef}
disabled={disabled || busy}
onChange={event => onConnectionRefChange(event.target.value)}
>
+ {!selected && connectionRef ? (
+ <option value={connectionRef}>{connectionRef} (unavailable)</option>
+ ) : null}
{assignable.map(row => (
<option
key={row.connectionKey}
diff --git a/control-ui/components/LlmModelForm/index.tsx b/control-ui/components/LlmModelForm/index.tsx
index a6c4f9ec1..91d6aef0d 100644
--- a/control-ui/components/LlmModelForm/index.tsx
+++ b/control-ui/components/LlmModelForm/index.tsx
@@ -158,10 +158,14 @@ export function LlmModelForm({
<FormSection title="Settings">
<CheckboxField
label="Enabled"
- description="Only enabled models can be selected for agents and served at runtime. Disable to retire a model without deleting it."
+ description={
+ provider === 'codex-subscription'
+ ? 'ChatGPT subscription models are enabled by the assigned grant catalog after sync, not from this table.'
+ : 'Only enabled models can be selected for agents and served at runtime. Disable to retire a model without deleting it.'
+ }
checked={enabled}
onChange={event => setEnabled(event.target.checked)}
- disabled={saving}
+ disabled={saving || provider === 'codex-subscription'}
/>
</FormSection>
diff --git a/control-ui/components/__tests__/CodexAgentAssignment.test.tsx b/control-ui/components/__tests__/CodexAgentAssignment.test.tsx
new file mode 100644
index 000000000..06c6ae7e9
--- /dev/null
+++ b/control-ui/components/__tests__/CodexAgentAssignment.test.tsx
@@ -0,0 +1,146 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import type { CodexSubscriptionConnectionView } from '@lib/codexSubscription'
+import {
+ createCodexSubscriptionConnection,
+ listCodexConnectionModels,
+ listCodexSubscriptionConnections,
+} from '@lib/codexSubscription'
+import { CodexAgentAssignment } from '../CodexAgentAssignment'
+import { ToastProvider } from '../Toast'
+
+const confirmMock = vi.fn()
+
+vi.mock('@components/ConfirmDialog', () => ({
+ useConfirmDialog: () => ({
+ confirm: confirmMock,
+ confirmDialog: null,
+ }),
+}))
+
+vi.mock('@lib/codexSubscriptionFeature', () => ({
+ isCodexSubscriptionUiEnabled: () => true,
+}))
+
+vi.mock('@lib/codexSubscription', async importOriginal => {
+ const actual = await importOriginal<typeof import('@lib/codexSubscription')>()
+ return {
+ ...actual,
+ listCodexSubscriptionConnections: vi.fn(),
+ listCodexConnectionModels: vi.fn(),
+ createCodexSubscriptionConnection: vi.fn(),
+ startCodexDeviceConnect: vi.fn(),
+ pollCodexDevice: vi.fn(),
+ revokeCodexSubscription: vi.fn(),
+ syncCodexSubscriptionCatalog: vi.fn(),
+ }
+})
+
+function connection(
+ overrides: Partial<CodexSubscriptionConnectionView> &
+ Pick<CodexSubscriptionConnectionView, 'connectionKey'>
+): CodexSubscriptionConnectionView {
+ return {
+ status: 'connected',
+ credentialRevision: 1,
+ catalogRevision: 1,
+ accountFingerprint: 'fp',
+ catalogStatus: 'ready',
+ catalogSyncedAt: '2026-08-20T00:00:00.000Z',
+ lastRefreshAt: '2026-08-20T00:00:00.000Z',
+ lastAuthAt: '2026-08-20T00:00:00.000Z',
+ refreshLockHeld: false,
+ displayName: overrides.connectionKey,
+ ...overrides,
+ }
+}
+
+function renderAssignment(connectionRef: string, onConnectionRefChange = vi.fn()) {
+ return {
+ onConnectionRefChange,
+ ...render(
+ <ToastProvider>
+ <CodexAgentAssignment
+ connectionRef={connectionRef}
+ onConnectionRefChange={onConnectionRefChange}
+ />
+ </ToastProvider>
+ ),
+ }
+}
+
+describe('CodexAgentAssignment', () => {
+ beforeEach(() => {
+ vi.mocked(listCodexConnectionModels).mockResolvedValue([])
+ confirmMock.mockReset()
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ })
+
+ it('keeps an unknown connectionRef and does not rematch on load', async () => {
+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'deployment-default', displayName: 'Default deployment' }),
+ ])
+ const { onConnectionRefChange } = renderAssignment('ghost-grant')
+ await waitFor(() => {
+ expect(screen.getByRole('option', { name: 'ghost-grant (unavailable)' })).toBeInTheDocument()
+ })
+ expect((screen.getByLabelText('ChatGPT subscription') as HTMLSelectElement).value).toBe(
+ 'ghost-grant'
+ )
+ expect(onConnectionRefChange).not.toHaveBeenCalled()
+ })
+
+ it('does not rewrite connectionRef when the connection list fails', async () => {
+ vi.mocked(listCodexSubscriptionConnections).mockRejectedValue(new Error('list failed'))
+ const { onConnectionRefChange } = renderAssignment('team-plus')
+ await waitFor(() => {
+ expect(screen.getByText('list failed')).toBeInTheDocument()
+ })
+ expect(onConnectionRefChange).not.toHaveBeenCalled()
+ expect((screen.getByLabelText('ChatGPT subscription') as HTMLSelectElement).value).toBe(
+ 'team-plus'
+ )
+ })
+
+ it('keeps a revoked current grant visible instead of replacing it', async () => {
+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
+ connection({
+ connectionKey: 'team-plus',
+ displayName: 'Team Plus',
+ status: 'revoked',
+ }),
+ connection({ connectionKey: 'deployment-default', displayName: 'Default deployment' }),
+ ])
+ const { onConnectionRefChange } = renderAssignment('team-plus')
+ await waitFor(() => {
+ expect(screen.getByRole('option', { name: 'Team Plus (revoked)' })).toBeInTheDocument()
+ })
+ expect((screen.getByLabelText('ChatGPT subscription') as HTMLSelectElement).value).toBe(
+ 'team-plus'
+ )
+ expect(onConnectionRefChange).not.toHaveBeenCalled()
+ })
+
+ it('changes connectionRef only after a successful create', async () => {
+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
+ connection({ connectionKey: 'deployment-default', displayName: 'Default deployment' }),
+ ])
+ vi.mocked(createCodexSubscriptionConnection).mockResolvedValue(
+ connection({ connectionKey: 'codex-aabbccddeeff0011', displayName: 'Codex subscription' })
+ )
+ const { onConnectionRefChange } = renderAssignment('deployment-default')
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'New subscription' })).toBeInTheDocument()
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'New subscription' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))
+ await waitFor(() => {
+ expect(onConnectionRefChange).toHaveBeenCalledWith('codex-aabbccddeeff0011')
+ })
+ expect(onConnectionRefChange).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/control-ui/components/__tests__/LlmModelForm.test.tsx b/control-ui/components/__tests__/LlmModelForm.test.tsx
new file mode 100644
index 000000000..3f355aed7
--- /dev/null
+++ b/control-ui/components/__tests__/LlmModelForm.test.tsx
@@ -0,0 +1,54 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { cleanup, render, screen } from '@testing-library/react'
+import type { LlmAllowedModel } from '@lib/api'
+import { LlmModelForm } from '../LlmModelForm'
+
+afterEach(cleanup)
+
+const model: LlmAllowedModel = {
+ id: 'model-1',
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ vendor: 'OpenAI',
+ display_name: 'GPT-5.3 Codex',
+ context_window_tokens: 200000,
+ enabled: true,
+ source: 'discovery',
+ stale: false,
+ discovered_at: null,
+ last_seen_at: null,
+ created_at: '2026-01-01T00:00:00.000Z',
+ updated_at: '2026-01-01T00:00:00.000Z',
+}
+
+describe('LlmModelForm', () => {
+ it('disables the Enabled toggle for ChatGPT subscription models', () => {
+ render(
+ <LlmModelForm
+ mode="edit"
+ initial={model}
+ saving={false}
+ onSubmit={() => undefined}
+ onCancel={() => undefined}
+ />
+ )
+ const toggle = screen.getByRole('checkbox')
+ expect(toggle).toBeDisabled()
+ expect(
+ screen.getByText(/enabled by the assigned grant catalog after sync/i)
+ ).toBeInTheDocument()
+ })
+
+ it('keeps the Enabled toggle editable for API-key providers', () => {
+ render(
+ <LlmModelForm
+ mode="edit"
+ initial={{ ...model, provider: 'openai', model: 'gpt-5.4' }}
+ saving={false}
+ onSubmit={() => undefined}
+ onCancel={() => undefined}
+ />
+ )
+ expect(screen.getByRole('checkbox')).toBeEnabled()
+ })
+})
diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.ts
index c663e41bb..10f49906b 100644
--- a/control-ui/lib/codexSubscription.ts
+++ b/control-ui/lib/codexSubscription.ts
@@ -29,6 +29,7 @@ export type CodexSubscriptionConnectionView = {
lastAuthAt: string | null
refreshLockHeld: boolean
assignedHosts?: CodexAssignedHost[]
+ assignedHostsUnavailable?: boolean
}
export type CodexBrowserStartView = {
@@ -129,6 +130,7 @@ export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnecti
)
.map(entry => ({ name: entry.name }))
: undefined,
+ assignedHostsUnavailable: raw.assignedHostsUnavailable === true,
status,
credentialRevision: pickNumber(raw.credentialRevision),
catalogRevision: pickNumber(raw.catalogRevision),
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index c6b258943..cb12f538b 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.446",
+ "version": "0.1.447",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.446",
+ "version": "0.1.447",
"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.json
index 73e7bf984..a389c6693 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.446",
+ "version": "0.1.447",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 470d48e14..228cc22ad 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.233",
+ "version": "0.1.234",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.233",
+ "version": "0.1.234",
"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.json
index bebc9f50a..bc1e9d0e4 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.233",
+ "version": "0.1.234",
"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/hostReconciler.codexScopeProvenance.test.ts b/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts
index 3d8e8a5fb..6d98aa3e1 100644
--- a/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts
+++ b/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts
@@ -97,9 +97,20 @@ function eligibleCodexConfigMap(stale = false) {
status: 'connected',
catalogRevision: 1,
connectionRevision: 1,
+ models: ['gpt-5.3-codex'],
+ },
+ 'team-plus': {
+ status: 'revoked',
+ catalogRevision: 3,
+ connectionRevision: 8,
+ models: ['gpt-5.3-codex'],
+ },
+ 'personal-pro': {
+ status: 'connected',
+ catalogRevision: 4,
+ connectionRevision: 2,
+ models: ['gpt-5.3-codex'],
},
- 'team-plus': { status: 'revoked', catalogRevision: 3, connectionRevision: 8 },
- 'personal-pro': { status: 'connected', catalogRevision: 4, connectionRevision: 2 },
}),
},
},
diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.test.ts b/host-context-controller/src/llmAllowedModelsSnapshot.test.ts
index 22de5fbd8..e01fdb9c6 100644
--- a/host-context-controller/src/llmAllowedModelsSnapshot.test.ts
+++ b/host-context-controller/src/llmAllowedModelsSnapshot.test.ts
@@ -16,9 +16,20 @@ function multiGrantConfigMap() {
status: 'connected',
catalogRevision: 1,
connectionRevision: 1,
+ models: ['gpt-5.3-codex'],
+ },
+ 'team-plus': {
+ status: 'revoked',
+ catalogRevision: 3,
+ connectionRevision: 8,
+ models: ['gpt-5.3-codex'],
+ },
+ 'personal-pro': {
+ status: 'connected',
+ catalogRevision: 4,
+ connectionRevision: 2,
+ models: ['gpt-5.3-codex'],
},
- 'team-plus': { status: 'revoked', catalogRevision: 3, connectionRevision: 8 },
- 'personal-pro': { status: 'connected', catalogRevision: 4, connectionRevision: 2 },
}),
},
},
@@ -49,4 +60,17 @@ describe('parseAllowedModelsSnapshot per assigned connection', () => {
expect(snapshot.connectionStatus).toBe('connected')
expect(snapshot.catalogRevision).toBe(1)
})
+
+ it('does not mark a Host eligible for a model that only another grant serves', () => {
+ const cm = multiGrantConfigMap()
+ const parsed = JSON.parse(
+ String(cm.metadata.annotations['clerum.io/codex-connections'])
+ ) as Record<string, { models: string[] }>
+ parsed['personal-pro'].models = ['gpt-5.1']
+ cm.metadata.annotations['clerum.io/codex-connections'] = JSON.stringify(parsed)
+ const snapshot = parseAllowedModelsSnapshot(cm, 'personal-pro')
+ const spec = { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } }
+ expect(projectCodexExecution(spec, snapshot).eligibility).toBe('ineligible')
+ expect(projectCodexExecution(spec, snapshot).derivedScopes).toEqual([])
+ })
})
diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.ts b/host-context-controller/src/llmAllowedModelsSnapshot.ts
index 61ce30148..1bee89510 100644
--- a/host-context-controller/src/llmAllowedModelsSnapshot.ts
+++ b/host-context-controller/src/llmAllowedModelsSnapshot.ts
@@ -13,6 +13,38 @@ export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCata
return { flagEnabled: false, snapshotError: error }
}
+const CODEX_PROVIDER_PREFIX = 'codex-subscription:'
+
+function dropCodexModels(enabledModels: Set<string>, staleModels: Set<string>): void {
+ for (const key of [...enabledModels]) {
+ if (key.startsWith(CODEX_PROVIDER_PREFIX)) {
+ enabledModels.delete(key)
+ staleModels.delete(key)
+ }
+ }
+}
+
+function intersectCodexModels(
+ enabledModels: Set<string>,
+ staleModels: Set<string>,
+ models: string[] | undefined,
+ connectionKey: string
+): void {
+ if (!Array.isArray(models)) {
+ if (connectionKey !== 'deployment-default') dropCodexModels(enabledModels, staleModels)
+ return
+ }
+ const allowed = new Set(models.filter(model => typeof model === 'string' && model.trim()))
+ for (const key of [...enabledModels]) {
+ if (!key.startsWith(CODEX_PROVIDER_PREFIX)) continue
+ const model = key.slice(CODEX_PROVIDER_PREFIX.length)
+ if (!allowed.has(model)) {
+ enabledModels.delete(key)
+ staleModels.delete(key)
+ }
+ }
+}
+
function parseOptionalIntegerAnnotation(
annotations: Record<string, string>,
key: string
@@ -61,7 +93,12 @@ export function parseAllowedModelsSnapshot(
try {
const parsed = JSON.parse(rawMap) as Record<
string,
- { status?: string; catalogRevision?: number; connectionRevision?: number }
+ {
+ status?: string
+ catalogRevision?: number
+ connectionRevision?: number
+ models?: string[]
+ }
>
const assigned = parsed[connectionKey]
if (assigned) {
@@ -73,8 +110,10 @@ export function parseAllowedModelsSnapshot(
if (Number.isInteger(assigned.connectionRevision)) {
connectionRevision = assigned.connectionRevision as number
}
+ intersectCodexModels(enabledModels, staleModels, assigned.models, connectionKey)
} else if (connectionKey !== 'deployment-default') {
connectionStatus = 'disconnected'
+ dropCodexModels(enabledModels, staleModels)
}
} catch {
return snapshotFromConfigMapError('malformed')
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index b09432d2f..51e4613f3 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.279",
+ "version": "0.1.280",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.279",
+ "version": "0.1.280",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 0888f4e9a..59d40026f 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.279",
+ "version": "0.1.280",
"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.ts
index 1b2aa7145..315a99bb2 100644
--- a/mcp-host/src/config/configStore.test.ts
+++ b/mcp-host/src/config/configStore.test.ts
@@ -106,7 +106,8 @@ function makeFakeCoreApi(initial: {
function build(opts: {
llmSecretRef?: string | null
- provider?: 'openai' | 'claude' | 'zai' | 'bailian' | null
+ provider?: 'openai' | 'claude' | 'zai' | 'bailian' | 'codex-subscription' | null
+ connectionRef?: string | null
secrets?: Record<string, Record<string, string>>
configMaps?: Record<string, Record<string, string>>
configMapAnnotations?: Record<string, Record<string, string>>
@@ -123,6 +124,7 @@ function build(opts: {
hostRef: 'trader',
llmSecretRef: opts.llmSecretRef ?? 'chatllm-api-keys',
provider: opts.provider ?? 'openai',
+ connectionRef: opts.connectionRef,
allowlistConfigMapName: opts.allowlistConfigMapName,
coreApi: api as unknown as ConstructorParameters<typeof ConfigStore>[0]['coreApi'],
watch: watch as unknown as ConstructorParameters<typeof ConfigStore>[0]['watch'],
@@ -788,4 +790,41 @@ describe('ConfigStore — allowlist tier (R3)', () => {
handle!.emit('DELETED', { metadata: { name: ALLOWLIST_CM } })
expect(await counterValue('clerum_llm_allowlist_missing_total')).toBe(before + 2)
})
+
+ it('filters Codex models to the assigned grant catalog, not the union', async () => {
+ const built = build({
+ provider: 'codex-subscription',
+ connectionRef: 'personal-pro',
+ secrets: { 'chatllm-api-keys': { 'openai-api-key': 'sk' } },
+ allowlistConfigMapName: ALLOWLIST_CM,
+ configMaps: {
+ [ALLOWLIST_CM]: {
+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex' }, { model: 'gpt-5.1' }]),
+ },
+ },
+ 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.1'],
+ },
+ 'team-plus': {
+ catalogRevision: 3,
+ connectionRevision: 8,
+ models: ['gpt-5.3-codex'],
+ },
+ }),
+ },
+ },
+ })
+ store = built.store
+ await store.start()
+ expect(store.allowedModels().get('codex-subscription')).toEqual([{ model: 'gpt-5.1' }])
+ expect(store.codexPolicyBinding()?.connectionKey).toBe('personal-pro')
+ expect(store.codexPolicyBinding()?.models).toEqual(['gpt-5.1'])
+ })
})
diff --git a/mcp-host/src/config/configStore.ts b/mcp-host/src/config/configStore.ts
index fe952bc39..ca564aaac 100644
--- a/mcp-host/src/config/configStore.ts
+++ b/mcp-host/src/config/configStore.ts
@@ -117,6 +117,7 @@ export type CodexPolicyBinding = {
catalogRevision: number
credentialRevision: number
connectionKey: string
+ models?: string[]
}
export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'
@@ -558,11 +559,11 @@ export class ConfigStore {
data?: Record<string, string>
metadata?: { annotations?: Record<string, string> }
}): boolean {
- const modelsChanged = this.applyAllowlistData(cm.data ?? {})
const nextBinding = parseCodexPolicyBinding(
cm.metadata?.annotations,
this.opts.connectionRef?.trim() || 'deployment-default'
)
+ const modelsChanged = this.applyAllowlistData(cm.data ?? {}, nextBinding)
const bindingChanged = !codexBindingsEqual(this.codexBinding, nextBinding)
this.codexBinding = nextBinding
return modelsChanged || bindingChanged
@@ -578,7 +579,10 @@ export class ConfigStore {
* allowlist — callers use this to notify subscribers only on a real content
* change (so routine watch reconnects don't re-fire the R3.7 signal).
*/
- private applyAllowlistData(data: Record<string, string>): boolean {
+ private applyAllowlistData(
+ data: Record<string, string>,
+ binding: CodexPolicyBinding | null = null
+ ): boolean {
const next = new Map<string, AllowedModelEntry[]>()
for (const [provider, raw] of Object.entries(data)) {
let parsed: unknown
@@ -598,7 +602,7 @@ export class ConfigStore {
console.error(`[ConfigStore] allowlist key '${provider}' is not a JSON array — skipping`)
continue
}
- const entries: AllowedModelEntry[] = []
+ let entries: AllowedModelEntry[] = []
for (const item of parsed) {
if (!item || typeof item !== 'object') {
console.error(
@@ -624,6 +628,14 @@ export class ConfigStore {
if (typeof rec.vendor === 'string') entry.vendor = rec.vendor
entries.push(entry)
}
+ if (provider === 'codex-subscription') {
+ 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') {
+ entries = []
+ }
+ }
next.set(provider, entries)
}
const changed = !allowlistMapsEqual(this.allowedModelsMap, next)
@@ -933,7 +945,7 @@ function parseCodexPolicyBinding(
try {
const parsed = JSON.parse(rawMap) as Record<
string,
- { catalogRevision?: number; connectionRevision?: number }
+ { catalogRevision?: number; connectionRevision?: number; models?: string[] }
>
const assigned = parsed[connectionKey]
if (
@@ -943,6 +955,12 @@ function parseCodexPolicyBinding(
) {
catalogRevision = assigned.catalogRevision as number
credentialRevision = assigned.connectionRevision as number
+ return {
+ catalogRevision,
+ credentialRevision,
+ connectionKey,
+ models: Array.isArray(assigned.models) ? assigned.models.filter(Boolean) : undefined,
+ }
}
} catch {
return null
@@ -965,7 +983,8 @@ function codexBindingsEqual(a: CodexPolicyBinding | null, b: CodexPolicyBinding
return (
a.catalogRevision === b.catalogRevision &&
a.credentialRevision === b.credentialRevision &&
- a.connectionKey === b.connectionKey
+ a.connectionKey === b.connectionKey &&
+ JSON.stringify(a.models ?? null) === JSON.stringify(b.models ?? null)
)
}
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index d0b7c8711..7b3bf0136 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.303",
+ "version": "0.1.304",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.303",
+ "version": "0.1.304",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 0aa0dc5f4..58baf4235 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.303",
+ "version": "0.1.304",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
index 1b32272f5..668783a5e 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
@@ -15,8 +15,14 @@ function multiGrantConfigMap() {
status: 'revoked',
catalogRevision: 1,
connectionRevision: 9,
+ models: [],
+ },
+ 'personal-pro': {
+ status: 'connected',
+ catalogRevision: 4,
+ connectionRevision: 2,
+ models: ['gpt-5.3-codex'],
},
- 'personal-pro': { status: 'connected', catalogRevision: 4, connectionRevision: 2 },
}),
},
},
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
index 06c018cac..6d3a3f581 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
@@ -14,6 +14,38 @@ export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCata
return { flagEnabled: false, snapshotError: error }
}
+const CODEX_PROVIDER_PREFIX = 'codex-subscription:'
+
+function dropCodexModels(enabledModels: Set<string>, staleModels: Set<string>): void {
+ for (const key of [...enabledModels]) {
+ if (key.startsWith(CODEX_PROVIDER_PREFIX)) {
+ enabledModels.delete(key)
+ staleModels.delete(key)
+ }
+ }
+}
+
+function intersectCodexModels(
+ enabledModels: Set<string>,
+ staleModels: Set<string>,
+ models: string[] | undefined,
+ connectionKey: string
+): void {
+ if (!Array.isArray(models)) {
+ if (connectionKey !== 'deployment-default') dropCodexModels(enabledModels, staleModels)
+ return
+ }
+ const allowed = new Set(models.filter(model => typeof model === 'string' && model.trim()))
+ for (const key of [...enabledModels]) {
+ if (!key.startsWith(CODEX_PROVIDER_PREFIX)) continue
+ const model = key.slice(CODEX_PROVIDER_PREFIX.length)
+ if (!allowed.has(model)) {
+ enabledModels.delete(key)
+ staleModels.delete(key)
+ }
+ }
+}
+
function parseOptionalIntegerAnnotation(
annotations: Record<string, string>,
key: string
@@ -62,7 +94,12 @@ export function parseAllowedModelsSnapshot(
try {
const parsed = JSON.parse(rawMap) as Record<
string,
- { status?: string; catalogRevision?: number; connectionRevision?: number }
+ {
+ status?: string
+ catalogRevision?: number
+ connectionRevision?: number
+ models?: string[]
+ }
>
const assigned = parsed[connectionKey]
if (assigned) {
@@ -74,8 +111,10 @@ export function parseAllowedModelsSnapshot(
if (Number.isInteger(assigned.connectionRevision)) {
connectionRevision = assigned.connectionRevision as number
}
+ intersectCodexModels(enabledModels, staleModels, assigned.models, connectionKey)
} else if (connectionKey !== 'deployment-default') {
connectionStatus = 'disconnected'
+ dropCodexModels(enabledModels, staleModels)
}
} catch {
return snapshotFromConfigMapError('malformed')