Skip to content

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

TypeScript

fix(codex): close jozer review gaps for recipes, SDK grants, and runtime auth

Alfredo Lopezcbae76b814b9
diff --git a/codex-llm-proxy/src/auth/platformJwtVerifier.ts b/codex-llm-proxy/src/auth/platformJwtVerifier.ts
index 947619c5a..3fd38321c 100644
--- a/codex-llm-proxy/src/auth/platformJwtVerifier.ts
+++ b/codex-llm-proxy/src/auth/platformJwtVerifier.ts
@@ -26,6 +26,7 @@ export function verifyPlatformJwt(
return null
}
if (typeof claims.exp !== 'number') return null
+ if (claims.scope !== 'workflow:approval:request') return null
if (claims.hostRefs.some(ref => String(ref) === '*')) return null
if (!claims.workflowControlScopes.includes('llm:codex:execute')) return null
return {
diff --git a/codex-llm-proxy/src/server.ts b/codex-llm-proxy/src/server.ts
index 86a73a49b..219a780d6 100644
--- a/codex-llm-proxy/src/server.ts
+++ b/codex-llm-proxy/src/server.ts
@@ -16,7 +16,11 @@ import type { CodexLlmProxyConfig } from './config.js'
import { ControlApiClient, ControlApiClientError } from './controlApiClient.js'
import { logger } from './logger.js'
import { createProxyMetrics } from './metrics.js'
-import { defaultAddressLookup, OriginDeniedError } from './originPolicy.js'
+import {
+ defaultAddressLookup,
+ OriginDeniedError,
+ type OriginPolicyOptions,
+} from './originPolicy.js'
import { RequestLimitError, streamGate } from './requestLimits.js'
const COMPLETION_KEYS = new Set(['executionTicket', 'requestHash', 'request', 'deadlineMs'])
@@ -61,6 +65,13 @@ function boundedErrorHandler(err: unknown, _req: Request, res: Response, _next:
export type ProxyRuntimeDeps = {
controlApiClient?: ControlApiClient
fetchFn?: typeof fetch
+ /**
+ * Test seam for the DNS half of the origin policy. Production always uses
+ * `defaultAddressLookup`; hermetic e2e injects a resolver so the frozen
+ * chatgpt.com origin check runs without live DNS. The URL freeze in
+ * `assertAllowedUpstreamUrl` is unaffected by this seam.
+ */
+ lookup?: OriginPolicyOptions['lookup']
}
export type ProxyServers = {
@@ -85,7 +96,7 @@ export function createProxyApps(config: CodexLlmProxyConfig, deps: ProxyRuntimeD
serviceToken: config.controlApiServiceToken,
})
const fetchFn = deps.fetchFn ?? fetch
- const lookup = defaultAddressLookup
+ const lookup = deps.lookup ?? defaultAddressLookup
const runtimeRateLimit = rateLimit({
windowMs: 60_000,
limit: 60,
diff --git a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
new file mode 100644
index 000000000..fe1747533
--- /dev/null
+++ b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
@@ -0,0 +1,394 @@
+/**
+ * Hermetic runtime-path e2e: authorize (mocked control-api redeem) → proxy
+ * runtime listener → REAL fixture ChatGPT upstream
+ * (tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs, spawned as
+ * a child process over TLS on loopback) → finalize receipt.
+ *
+ * This is the load-bearing transport evidence for
+ * scripts/e2e/e2e-codex-subscription-runtime.sh: the same fixture upstream the
+ * in-cluster manifest deploys serves the stream here, and the full proxy
+ * pipeline (platform JWT, execution ticket, request-hash freeze, origin
+ * policy, SSE mapping, finalize retry contract) runs unmocked. Only two seams
+ * are substituted, both injection points that production wires to live
+ * infrastructure:
+ * - ControlApiClient (redeem/finalize) — an in-memory grant table standing
+ * in for control-api's authorizer, keyed by the same recipe-shaped
+ * hostRef + connection-key identity used by
+ * `clerum.io/codex-connection-ref` (claim 1).
+ * - fetchFn/lookup — the frozen chatgpt.com origin is still asserted by the
+ * unmodified origin policy; the socket is then pointed at the loopback
+ * fixture instead of the public internet. No live ChatGPT OAuth is used.
+ */
+import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { generateKeyPairSync } from 'node:crypto'
+import jwt from 'jsonwebtoken'
+import request from 'supertest'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import {
+ hashCodexCompletionRequestV1,
+ parseCodexCompletionRequestV1,
+} from '@clerum/llm-provider-attempt-contract'
+import type { CodexLlmProxyConfig } from '../src/config.js'
+import {
+ ControlApiClientError,
+ type ControlApiClient,
+ type FinalizeAttemptSuccess,
+ type RedeemAttemptSuccess,
+} from '../src/controlApiClient.js'
+import { CODEX_CATALOG_ORIGIN, CODEX_COMPLETIONS_ORIGIN } from '../src/originPolicy.js'
+import { createProxyApps, type ProxyServers } from '../src/server.js'
+
+const FIXTURE_UPSTREAM = fileURLToPath(
+ new URL('../../tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs', import.meta.url)
+)
+const UPSTREAM_PORT = 18443 + (process.pid % 1000)
+const UPSTREAM_BASE = `https://127.0.0.1:${UPSTREAM_PORT}`
+
+// Grant table the mocked control-api authorizer redeems against. The key is
+// the same recipe-level connection identity persisted by the
+// `clerum.io/codex-connection-ref` annotation (claim 1): SDK / workflow
+// callers attest as `namespace/recipe`, and only an existing connected grant
+// offering the requested model may be redeemed.
+const RECIPE_HOST_REF = 'sandbox-recipes/e2e-codex-recipe'
+const CONNECTED_GRANTS: Record<string, { connectionKey: string; models: string[] }> = {
+ [RECIPE_HOST_REF]: { connectionKey: 'e2e-team-plus', models: ['gpt-5.3-codex'] },
+}
+
+const { privateKey, publicKey } = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+})
+
+function config(): CodexLlmProxyConfig {
+ return {
+ runtimePort: 0,
+ adminPort: 0,
+ probePort: 0,
+ maxBodyBytes: 1_048_576,
+ maxStreamDurationMs: 30_000,
+ maxDeadlineMs: 30_000,
+ jwtIssuer: 'control-api',
+ jwtPublicKey: publicKey,
+ executionEnabled: true,
+ controlApiBaseUrl: '',
+ controlApiServiceName: 'codex-llm-proxy',
+ controlApiServiceToken: '',
+ }
+}
+
+function sign(payload: Record<string, unknown>, audience: string): string {
+ return jwt.sign(payload, privateKey, {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience,
+ expiresIn: 60,
+ })
+}
+
+function platformToken(hostRef: string): string {
+ return sign(
+ {
+ sub: hostRef,
+ hostRefs: [hostRef],
+ workflowControlScopes: ['llm:codex:execute'],
+ scope: 'workflow:approval:request',
+ },
+ 'workflow-approvals'
+ )
+}
+
+function executionTicket(input: {
+ hostRef: string
+ model: string
+ requestHash: string
+ providerAttemptId: string
+}): string {
+ return sign(
+ {
+ jti: '22222222-2222-4222-8222-222222222222',
+ typ: 'codex-execution-ticket',
+ hostRef: input.hostRef,
+ model: input.model,
+ requestHash: input.requestHash,
+ providerAttemptId: input.providerAttemptId,
+ },
+ 'codex-llm-proxy'
+ )
+}
+
+function completionRequest(model: string): Record<string, unknown> {
+ return {
+ schemaVersion: 'codex-completion-request.v1',
+ requestId: 'req-hermetic-1',
+ idempotencyKey: 'idem-hermetic-1',
+ provider: 'codex-subscription',
+ model,
+ messages: [{ role: 'user', content: 'Say hello through Codex subscription' }],
+ }
+}
+
+/** SSE `data:` payloads written by the proxy runtime response. */
+function sseFrames(body: string): Array<Record<string, unknown>> {
+ return body
+ .split('\n\n')
+ .map(part => part.trim())
+ .filter(part => part.startsWith('data:'))
+ .map(part => JSON.parse(part.slice(5).trim()) as Record<string, unknown>)
+}
+
+type RedeemCall = Parameters<ControlApiClient['redeem']>[0]
+type FinalizeCall = Parameters<ControlApiClient['finalize']>[0]
+
+function makeControlApiMock(): {
+ client: ControlApiClient
+ redeems: RedeemCall[]
+ finalizes: FinalizeCall[]
+} {
+ const redeems: RedeemCall[] = []
+ const finalizes: FinalizeCall[] = []
+ const client = {
+ async redeem(input: RedeemCall): Promise<RedeemAttemptSuccess> {
+ redeems.push(input)
+ const grant = input.hostRef ? CONNECTED_GRANTS[input.hostRef] : undefined
+ // Fail closed exactly like control-api: an unassigned / unknown recipe
+ // grant never redeems, and never aliases deployment-default.
+ if (!grant) throw new ControlApiClientError('no_grant', 'no Codex grant is assigned')
+ if (!input.model || !grant.models.includes(input.model)) {
+ throw new ControlApiClientError('model_not_allowed', 'model is not offered on the grant')
+ }
+ return {
+ accessToken: 'test-access-hermetic',
+ chatgptAccountId: 'acct-e2e-hermetic',
+ transport: {
+ protocolVersion: 'codex-subscription-transport.v1',
+ completionsOrigin: CODEX_COMPLETIONS_ORIGIN,
+ catalogOrigin: CODEX_CATALOG_ORIGIN,
+ operation: 'completion_stream',
+ servedModel: input.model,
+ maxStreamDurationMs: 30_000,
+ },
+ expiryClass: 'short_lived',
+ attemptReceipt: 'b'.repeat(64),
+ }
+ },
+ async finalize(input: FinalizeCall): Promise<FinalizeAttemptSuccess> {
+ finalizes.push(input)
+ return {
+ providerAttemptId: input.receipt.providerAttemptId,
+ outcome: input.receipt.outcome,
+ duplicate: false,
+ }
+ },
+ } as unknown as ControlApiClient
+ return { client, redeems, finalizes }
+}
+
+/**
+ * Reroute the frozen chatgpt.com origin to the loopback fixture. The URL
+ * given to fetchFn has already passed the unmodified origin policy
+ * (assertAllowedUpstreamUrl + assertResolvedUpstream); only the socket
+ * destination changes, mirroring what the in-cluster NetworkPolicy/DNS pin
+ * would do for a test upstream.
+ */
+function rewriteFetch(url: string | URL | Request, init?: RequestInit): Promise<Response> {
+ const parsed = new URL(String(url))
+ expect(parsed.origin).toBe('https://chatgpt.com')
+ const target = new URL(parsed.pathname + parsed.search, UPSTREAM_BASE)
+ return fetch(target, init)
+}
+
+async function upstreamCounters(): Promise<Record<string, number>> {
+ const res = await fetch(`${UPSTREAM_BASE}/internal/counters`)
+ return (await res.json()) as Record<string, number>
+}
+
+let upstream: ChildProcess | undefined
+let workdir: string
+let servers: ProxyServers | undefined
+let previousTlsReject: string | undefined
+
+beforeAll(async () => {
+ // The fixture is TLS-only with a run-generated self-signed certificate
+ // (never committed). All traffic stays on 127.0.0.1, so disabling TLS
+ // verification for this isolated test process does not weaken any
+ // production path.
+ previousTlsReject = process.env.NODE_TLS_REJECT_UNAUTHORIZED
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
+ workdir = mkdtempSync(join(tmpdir(), 'codex-hermetic-'))
+ const certPath = join(workdir, 'tls.crt')
+ const keyPath = join(workdir, 'tls.key')
+ execFileSync(
+ 'openssl',
+ [
+ 'req',
+ '-x509',
+ '-newkey',
+ 'rsa:2048',
+ '-nodes',
+ '-days',
+ '1',
+ '-keyout',
+ keyPath,
+ '-out',
+ certPath,
+ '-subj',
+ '/CN=codex-test-upstream.local',
+ ],
+ { stdio: 'ignore' }
+ )
+ upstream = spawn(process.execPath, [FIXTURE_UPSTREAM], {
+ env: {
+ ...process.env,
+ CODEX_TEST_UPSTREAM_PORT: String(UPSTREAM_PORT),
+ CODEX_TEST_UPSTREAM_CERT_PATH: certPath,
+ CODEX_TEST_UPSTREAM_KEY_PATH: keyPath,
+ },
+ stdio: ['ignore', 'pipe', 'inherit'],
+ })
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('fixture upstream did not start')), 15_000)
+ upstream?.stdout?.on('data', (chunk: Buffer) => {
+ if (chunk.toString('utf8').includes('listening')) {
+ clearTimeout(timer)
+ resolve()
+ }
+ })
+ upstream?.on('exit', code => {
+ clearTimeout(timer)
+ reject(new Error(`fixture upstream exited early (code ${code})`))
+ })
+ })
+}, 30_000)
+
+afterAll(async () => {
+ await servers?.close()
+ upstream?.kill('SIGTERM')
+ rmSync(workdir, { recursive: true, force: true })
+ if (previousTlsReject === undefined) {
+ delete process.env.NODE_TLS_REJECT_UNAUTHORIZED
+ } else {
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = previousTlsReject
+ }
+})
+
+describe('hermetic authorize → proxy → fixture upstream → finalize', () => {
+ it('streams a completion through the fixture upstream and finalizes a success receipt', async () => {
+ const { client, redeems, finalizes } = makeControlApiMock()
+ servers = createProxyApps(config(), {
+ controlApiClient: client,
+ fetchFn: rewriteFetch,
+ lookup: async () => [{ address: '104.18.32.47', family: 4 }],
+ })
+ const before = await upstreamCounters()
+
+ const raw = completionRequest('gpt-5.3-codex')
+ const parsed = parseCodexCompletionRequestV1(raw)
+ if (!parsed.ok) throw new Error(parsed.message)
+ const requestHash = hashCodexCompletionRequestV1(parsed.value)
+ const providerAttemptId = 'att-hermetic-1'
+
+ const res = await request(servers.runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${platformToken(RECIPE_HOST_REF)}`)
+ .send({
+ executionTicket: executionTicket({
+ hostRef: RECIPE_HOST_REF,
+ model: 'gpt-5.3-codex',
+ requestHash,
+ providerAttemptId,
+ }),
+ requestHash,
+ request: raw,
+ })
+
+ expect(res.status).toBe(200)
+ expect(res.headers['content-type']).toContain('text/event-stream')
+ const frames = sseFrames(res.text)
+ expect(frames).toContainEqual({ type: 'text', text: 'hello' })
+ const done = frames.find(frame => frame.type === 'done')
+ expect(done).toBeDefined()
+ expect(done?.outcome).toBe('success')
+ expect(done?.usage).toEqual({ inputTokens: 3, outputTokens: 1 })
+
+ // One redemption against the recipe-shaped grant identity, no live OAuth.
+ expect(redeems).toHaveLength(1)
+ expect(redeems[0]).toMatchObject({
+ requestHash,
+ model: 'gpt-5.3-codex',
+ hostRef: RECIPE_HOST_REF,
+ operation: 'completion_stream',
+ })
+
+ // Finalize carries the physical receipt for the exact attempt and usage.
+ expect(finalizes).toHaveLength(1)
+ expect(finalizes[0]?.attemptReceipt).toBe('b'.repeat(64))
+ expect(finalizes[0]?.receipt).toEqual({
+ schemaVersion: 'codex-attempt-receipt.v1',
+ providerAttemptId,
+ requestHash,
+ outcome: 'success',
+ usage: { inputTokens: 3, outputTokens: 1 },
+ })
+
+ // The REAL fixture upstream served exactly one stream for this test.
+ const after = await upstreamCounters()
+ expect(after.streams).toBe((before.streams ?? 0) + 1)
+
+ // Secret hygiene: neither the upstream credential nor receipts leak into
+ // the client-visible stream.
+ expect(res.text).not.toMatch(/test-access-hermetic|attemptReceipt|refresh/i)
+
+ await servers.close()
+ servers = undefined
+ })
+
+ it('fails closed before touching the upstream when the recipe grant is unassigned', async () => {
+ const { client, redeems, finalizes } = makeControlApiMock()
+ servers = createProxyApps(config(), {
+ controlApiClient: client,
+ fetchFn: rewriteFetch,
+ lookup: async () => [{ address: '104.18.32.47', family: 4 }],
+ })
+ const before = await upstreamCounters()
+
+ const unassignedHostRef = 'sandbox-recipes/e2e-codex-recipe-unassigned'
+ const raw = completionRequest('gpt-5.3-codex')
+ const parsed = parseCodexCompletionRequestV1(raw)
+ if (!parsed.ok) throw new Error(parsed.message)
+ const requestHash = hashCodexCompletionRequestV1(parsed.value)
+
+ const res = await request(servers.runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${platformToken(unassignedHostRef)}`)
+ .send({
+ executionTicket: executionTicket({
+ hostRef: unassignedHostRef,
+ model: 'gpt-5.3-codex',
+ requestHash,
+ providerAttemptId: 'att-hermetic-2',
+ }),
+ requestHash,
+ request: raw,
+ })
+
+ // Redemption fails before the first stream write, so the denial is a
+ // plain 403 with the authorizer's stable code — never a partial stream.
+ expect(res.status).toBe(403)
+ // The SSE content-type header was already staged, so supertest surfaces
+ // the JSON denial in res.text rather than res.body.
+ expect(JSON.parse(res.text)).toEqual({ error: 'no_grant' })
+ expect(redeems).toHaveLength(1)
+ expect(finalizes).toHaveLength(0)
+
+ const after = await upstreamCounters()
+ expect(after.streams).toBe(before.streams ?? 0)
+
+ await servers.close()
+ servers = undefined
+ })
+})
diff --git a/codex-llm-proxy/test/server.security.test.ts b/codex-llm-proxy/test/server.security.test.ts
index 5c5162aba..40156c8d5 100644
--- a/codex-llm-proxy/test/server.security.test.ts
+++ b/codex-llm-proxy/test/server.security.test.ts
@@ -40,12 +40,14 @@ function sign(payload: Record<string, unknown>, audience: string): string {
})
}
-function platformToken(): string {
+function platformToken(overrides: Record<string, unknown> = {}): string {
return sign(
{
sub: 'default/research-host',
hostRefs: ['research-host'],
workflowControlScopes: ['llm:codex:execute'],
+ scope: 'workflow:approval:request',
+ ...overrides,
},
'workflow-approvals'
)
@@ -153,6 +155,7 @@ describe('codex-llm-proxy security surface', () => {
sub: 'default/other-host',
hostRefs: ['other-host'],
workflowControlScopes: ['llm:codex:execute'],
+ scope: 'workflow:approval:request',
},
'workflow-approvals'
)
@@ -168,6 +171,42 @@ describe('codex-llm-proxy security surface', () => {
expect(res.body.error).toBe('host_binding_mismatch')
})
+ it('rejects a refresh JWT that otherwise carries llm:codex:execute', async () => {
+ const { runtimeApp } = createProxyApps(config())
+ const res = await request(runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${platformToken({ scope: 'workflow:approval:refresh' })}`)
+ .send({
+ executionTicket: ticket(),
+ requestHash: 'a'.repeat(64),
+ request: {},
+ })
+ expect(res.status).toBe(401)
+ expect(res.body.error).toBe('Unauthorized')
+ })
+
+ it('rejects a platform JWT that omits the access-token scope', async () => {
+ const { runtimeApp } = createProxyApps(config())
+ const missingScope = sign(
+ {
+ sub: 'default/research-host',
+ hostRefs: ['research-host'],
+ workflowControlScopes: ['llm:codex:execute'],
+ },
+ 'workflow-approvals'
+ )
+ const res = await request(runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${missingScope}`)
+ .send({
+ executionTicket: ticket(),
+ requestHash: 'a'.repeat(64),
+ request: {},
+ })
+ expect(res.status).toBe(401)
+ expect(res.body.error).toBe('Unauthorized')
+ })
+
it('rejects a platform JWT whose hostRefs is a wildcard', async () => {
const { runtimeApp } = createProxyApps(config())
const wildcard = sign(
@@ -175,6 +214,7 @@ describe('codex-llm-proxy security surface', () => {
sub: 'default/research-host',
hostRefs: ['*'],
workflowControlScopes: ['llm:codex:execute'],
+ scope: 'workflow:approval:request',
},
'workflow-approvals'
)
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index ceccfd02a..a92642f23 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.508",
+ "version": "0.1.509",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.508",
+ "version": "0.1.509",
"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 6bc362f53..03dd33ed8 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.508",
+ "version": "0.1.509",
"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 af5f962b9..7265f5de6 100644
--- a/control-api/src/routes/admin/codexSubscription.ts
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -423,6 +423,7 @@ export function createAdminCodexSubscriptionRouter(
const connection = await refreshCodexSubscriptionConnection(
oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req))
)
+ if (await publishRuntimeAllowlistOrFail(res)) return
res.status(200).json(connection)
} catch (err) {
sendOAuthError(res, err)
@@ -454,6 +455,7 @@ export function createAdminCodexSubscriptionRouter(
return
}
if (synced.outcome !== 'ready') {
+ if (await publishRuntimeAllowlistOrFail(res)) return
res.status(503).json({
error: 'catalog_sync_failed',
outcome: synced.outcome,
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index 69d0c51d6..51853fa3e 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -3,6 +3,7 @@ import {
isCredentialSlotOwnedByProvider,
isLlmProviderId,
isRunnableLlmModelId,
+ providerDescriptor,
} from '@clerum/llm-providers'
import {
advisoryLockModelNames,
@@ -12,6 +13,11 @@ import {
import { asyncHandler } from '../../http/asyncHandler.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import { createPluginWorkloadSdkAdminRateLimit } from '../../middleware/pluginWorkloadSdkRateLimits.js'
+import { isCodexAssignmentAllowed } from '../../services/codexSubscriptionCatalog.js'
+import {
+ assertCodexConnectionKey,
+ isCodexUnassignedConnectionKey,
+} from '../../services/codexSubscriptionConnection.js'
import { listEnabledModelsWithStaleForProvider } from '../../services/llmAllowedModels.js'
import {
MAX_ALLOWLIST_ENTRY_LENGTH,
@@ -202,6 +208,11 @@ function parseModelPolicies(
return policies
}
+/** Whether a validated provider id resolves credentials through the OAuth broker. */
+function isBrokerBackedProvider(provider: string): boolean {
+ return isLlmProviderId(provider) && providerDescriptor(provider).authMode === 'oauth-broker'
+}
+
function credentialSlotBelongsToProvider(provider: string, credentialSlot: string): boolean {
// This shares the exact slot-ownership rule with the runtime broker. A
// target only carries the key identity; this route never reads the Secret or
@@ -238,6 +249,7 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
const provider = typeof raw.provider === 'string' ? raw.provider.trim() : ''
const model = typeof raw.model === 'string' ? raw.model.trim() : ''
const credentialSlot = typeof raw.credentialSlot === 'string' ? raw.credentialSlot.trim() : ''
+ const connectionRef = typeof raw.connectionRef === 'string' ? raw.connectionRef.trim() : ''
if (!targetRef || targetRef.length > MAX_ALLOWLIST_ENTRY_LENGTH || targetRef.includes('*')) {
res
.status(400)
@@ -254,16 +266,51 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
.json({ error: `promptTargets[${index}].model must be a non-wildcard model id` })
return null
}
- if (
- !credentialSlot ||
- credentialSlot.length > 253 ||
- !SECRET_KEY_RE.test(credentialSlot) ||
- !credentialSlotBelongsToProvider(provider, credentialSlot)
- ) {
- res.status(400).json({
- error: `promptTargets[${index}].credentialSlot must be a valid slot owned by provider "${provider}"`,
- })
- return null
+ const brokerBacked = providerDescriptor(provider).authMode === 'oauth-broker'
+ if (brokerBacked) {
+ // oauth-broker targets (Codex) carry no static Secret data key: the
+ // credential is brokered per attempt. An empty slot is the only correct
+ // value — a non-empty slot would pretend a ChatGPT refresh token lives
+ // in an API-key slot, which is exactly the shape this gate forbids.
+ if (credentialSlot) {
+ res.status(400).json({
+ error: `promptTargets[${index}].credentialSlot must be empty for oauth-broker provider "${provider}"`,
+ })
+ return null
+ }
+ // The target only CHOOSES an existing Codex grant. Reject the missing /
+ // unassigned / malformed key here; existence, connection status, and
+ // model offer are re-validated against the catalog inside the upsert
+ // transaction (fail closed on every unknown/revoked/not-offered case).
+ try {
+ if (!connectionRef || isCodexUnassignedConnectionKey(connectionRef)) {
+ throw new Error('missing_connection_ref')
+ }
+ assertCodexConnectionKey(connectionRef)
+ } catch {
+ res.status(400).json({
+ error: `promptTargets[${index}].connectionRef must name an existing Codex subscription connection`,
+ })
+ return null
+ }
+ } else {
+ if (connectionRef) {
+ res.status(400).json({
+ error: `promptTargets[${index}].connectionRef is only valid for oauth-broker providers`,
+ })
+ return null
+ }
+ if (
+ !credentialSlot ||
+ credentialSlot.length > 253 ||
+ !SECRET_KEY_RE.test(credentialSlot) ||
+ !credentialSlotBelongsToProvider(provider, credentialSlot)
+ ) {
+ res.status(400).json({
+ error: `promptTargets[${index}].credentialSlot must be a valid slot owned by provider "${provider}"`,
+ })
+ return null
+ }
}
const providerModel = `${provider}\u0000${model}`
if (targetRefs.has(targetRef) || providerModels.has(providerModel)) {
@@ -272,7 +319,13 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
}
targetRefs.add(targetRef)
providerModels.add(providerModel)
- targets.push({ targetRef, provider, model, credentialSlot })
+ targets.push({
+ targetRef,
+ provider,
+ model,
+ credentialSlot,
+ ...(brokerBacked ? { connectionRef } : {}),
+ })
}
return targets
}
@@ -485,8 +538,31 @@ export function createAdminPluginWorkloadSdkRouter(
await advisoryLockModelNames(db, allowedModels)
if (capabilityFamily === 'promptBridge') {
+ // Codex (oauth-broker) targets are validated against the chosen
+ // grant's per-connection catalog, not the flat `llm_allowed_models`
+ // union: only a model offered AND enabled (non-stale) on that
+ // exact connected grant may be authorized. Unknown, unassigned,
+ // revoked, and not-offered all fail closed with a stable error.
+ // No Pieza D toleration applies — a Codex grant that lost a model
+ // must be re-pointed explicitly, never silently kept.
+ for (const target of promptTargets) {
+ if (!isBrokerBackedProvider(target.provider)) continue
+ const allowed = await isCodexAssignmentAllowed(
+ db,
+ target.connectionRef ?? '',
+ target.model
+ )
+ if (!allowed) {
+ throw new GrantModelGateError({
+ error: 'codex_connection_not_allowed',
+ connectionRef: target.connectionRef ?? '',
+ model: target.model,
+ })
+ }
+ }
const modelsByProvider = new Map<string, string[]>()
for (const target of promptTargets) {
+ if (isBrokerBackedProvider(target.provider)) continue
modelsByProvider.set(target.provider, [
...(modelsByProvider.get(target.provider) ?? []),
target.model,
diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
index 72fb8bc56..67bdcda32 100644
--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
@@ -5,7 +5,7 @@ import type { K8sGateway } from '../../k8s.js'
import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'
import { rootLogger } from '../../observability/logger.js'
import {
- CODEX_UNASSIGNED_CONNECTION_KEY,
+ CODEX_CONNECTION_REF_ANNOTATION,
readHostCodexConnectionRef,
} from '../../services/codexSubscriptionConnection.js'
import {
@@ -47,7 +47,32 @@ export async function resolveHostAssignedConnectionKey(
hostRef: string
): Promise<string> {
if (hostRef.includes('/')) {
- return CODEX_UNASSIGNED_CONNECTION_KEY
+ // Workflow callers attest as `namespace/recipeName`. The grant identity is
+ // the `clerum.io/codex-connection-ref` annotation on that WorkflowRecipe
+ // (WRC stamps the parent's chosen key onto DB-run children). Missing or
+ // empty annotations resolve to the fail-closed `unassigned` sentinel.
+ const [recipeNamespace, recipeName, ...rest] = hostRef.split('/')
+ if (!recipeNamespace || !recipeName || rest.length > 0) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'host_binding_mismatch',
+ 'Recipe assignment could not be attested'
+ )
+ }
+ try {
+ const recipe = (await gateway.getResource(
+ 'workflowrecipes',
+ recipeName,
+ recipeNamespace
+ )) as { metadata?: { annotations?: Record<string, string> } }
+ return readHostCodexConnectionRef(
+ recipe?.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
+ )
+ } catch {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'host_binding_mismatch',
+ 'Recipe assignment could not be attested'
+ )
+ }
}
try {
const host = (await gateway.getResource('hosts', hostRef, config.hostsNamespace)) as {
diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.ts
index 78425fd31..2ae04b2e3 100644
--- a/control-api/src/services/codexSubscriptionConnection.ts
+++ b/control-api/src/services/codexSubscriptionConnection.ts
@@ -5,6 +5,15 @@ import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'
export const CODEX_SUBSCRIPTION_CONNECTION_KEY = 'deployment-default' as const
/** Fail-closed Host sentinel. Not a grant row; never maps to deployment-default. */
export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned' as const
+/**
+ * WorkflowRecipe metadata annotation naming the Codex grant (connection key)
+ * the recipe executes against. Recipes deliberately have no Host-style
+ * `spec.model.connectionRef` CRD field: grants are created in Secrets and a
+ * recipe only *chooses* an existing grant through this annotation. WRC
+ * (workflow-recipes `llmAllowedModelsSnapshot.ts`) and this service must agree
+ * on the same key.
+ */
+export const CODEX_CONNECTION_REF_ANNOTATION = 'clerum.io/codex-connection-ref' as const
const CONNECTION_KEY_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
diff --git a/control-api/src/services/llmAllowedModelsConfigMap.ts b/control-api/src/services/llmAllowedModelsConfigMap.ts
index 27e75cbe5..18e2a35bc 100644
--- a/control-api/src/services/llmAllowedModelsConfigMap.ts
+++ b/control-api/src/services/llmAllowedModelsConfigMap.ts
@@ -112,9 +112,10 @@ export interface AllowedModelsConfigMapMaterializer {
/**
* Push the current Postgres allowlist + per-grant Codex snapshot to the
- * runtime ConfigMap. Catalog sync, revoke, and a successful OAuth persist
- * must call this — mcp-host/HCC never read Postgres, and a cluster in
- * operation cannot wait for the next control-api boot.
+ * runtime ConfigMap. Catalog sync (including recorded non-ready outcomes),
+ * manual refresh, revoke, and a successful OAuth persist must call this —
+ * mcp-host/HCC never read Postgres, and a cluster in operation cannot wait
+ * for the next control-api boot.
*
* Missing writer is a no-op so unit tests without a K8s gateway stay local.
*/
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index dc823222a..8ef228a86 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -180,8 +180,19 @@ export interface PluginWorkloadSdkPromptTarget {
targetRef: string
provider: string
model: string
- /** Secret data-key identity only; never its value. */
+ /**
+ * Secret data-key identity only; never its value. Empty for oauth-broker
+ * providers (Codex): no static Secret key exists for a brokered grant.
+ */
credentialSlot: string
+ /**
+ * Codex subscription grant (connection key) this target executes against.
+ * Required for oauth-broker providers, absent for API-key providers. The
+ * grant is only *chosen* here — it must already exist and be connected; the
+ * runtime attestation authority stays the recipe-level
+ * `clerum.io/codex-connection-ref` annotation resolved by the authorizer.
+ */
+ connectionRef?: string
}
/**
@@ -367,7 +378,8 @@ function promptTargets(value: unknown): PluginWorkloadSdkPromptTarget[] {
typeof target.targetRef !== 'string' ||
typeof target.provider !== 'string' ||
typeof target.model !== 'string' ||
- typeof target.credentialSlot !== 'string'
+ typeof target.credentialSlot !== 'string' ||
+ (target.connectionRef !== undefined && typeof target.connectionRef !== 'string')
) {
return []
}
@@ -377,6 +389,9 @@ function promptTargets(value: unknown): PluginWorkloadSdkPromptTarget[] {
provider: target.provider,
model: target.model,
credentialSlot: target.credentialSlot,
+ ...(typeof target.connectionRef === 'string' && target.connectionRef
+ ? { connectionRef: target.connectionRef }
+ : {}),
},
]
})
@@ -1405,7 +1420,8 @@ export async function reservePluginWorkloadSdkProviderAttempt(input: {
!currentTarget ||
currentTarget.provider !== input.target.provider ||
currentTarget.model !== input.target.model ||
- currentTarget.credentialSlot !== input.target.credentialSlot
+ currentTarget.credentialSlot !== input.target.credentialSlot ||
+ (currentTarget.connectionRef ?? '') !== (input.target.connectionRef ?? '')
) {
return null
}
diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.ts
index 253c412da..90898cde4 100644
--- a/control-api/test/routes.admin.codexSubscription.test.ts
+++ b/control-api/test/routes.admin.codexSubscription.test.ts
@@ -371,6 +371,91 @@ describe('admin Codex subscription routes', () => {
assertNoLeak(res.body)
})
+ it('publishes the runtime ConfigMap after a manual refresh', async () => {
+ const materialize = vi.fn(async () => {})
+ oauth.refresh.mockResolvedValue({
+ connectionKey: 'codex-aaa',
+ status: 'connected',
+ credentialRevision: 4,
+ })
+ const res = await request(makeAuthedApp(makeGateway(materialize))).post(
+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/refresh'
+ )
+ expect(res.status).toBe(200)
+ expect(res.body.credentialRevision).toBe(4)
+ expect(materialize).toHaveBeenCalledTimes(1)
+ assertNoLeak(res.body)
+ })
+
+ it('returns 503 when refresh cannot publish the runtime ConfigMap', async () => {
+ const materialize = vi.fn(async () => {
+ throw new Error('apiserver down')
+ })
+ oauth.refresh.mockResolvedValue({
+ connectionKey: 'codex-aaa',
+ status: 'connected',
+ credentialRevision: 4,
+ })
+ const res = await request(makeAuthedApp(makeGateway(materialize))).post(
+ '/admin/llm/providers/codex-subscription/refresh'
+ )
+ expect(res.status).toBe(503)
+ expect(res.body.error).toBe('configmap_write_failed')
+ expect(materialize).toHaveBeenCalledTimes(1)
+ assertNoLeak(res.body)
+ })
+
+ it('publishes the runtime ConfigMap after a recorded non-ready catalog sync', async () => {
+ const materialize = vi.fn(async () => {})
+ catalog.loadSecrets.mockResolvedValue({ accessToken: 'access-secret' })
+ catalog.sync.mockResolvedValue({
+ outcome: 'auth-rejected',
+ added: 0,
+ refreshed: 0,
+ staled: 0,
+ connection: {
+ connectionKey: 'codex-aaa',
+ status: 'reauth_required',
+ catalogStatus: 'auth-rejected',
+ catalogRevision: 3,
+ },
+ })
+ const res = await request(makeAuthedApp(makeGateway(materialize))).post(
+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/catalog/sync'
+ )
+ expect(res.status).toBe(503)
+ expect(res.body.error).toBe('catalog_sync_failed')
+ expect(res.body.outcome).toBe('auth-rejected')
+ expect(materialize).toHaveBeenCalledTimes(1)
+ assertNoLeak(res.body)
+ })
+
+ it('returns 503 when a failed catalog sync cannot publish the runtime ConfigMap', async () => {
+ const materialize = vi.fn(async () => {
+ throw new Error('apiserver down')
+ })
+ catalog.loadSecrets.mockResolvedValue({ accessToken: 'access-secret' })
+ catalog.sync.mockResolvedValue({
+ outcome: 'unavailable',
+ added: 0,
+ refreshed: 0,
+ staled: 0,
+ connection: {
+ connectionKey: 'codex-aaa',
+ status: 'connected',
+ catalogStatus: 'unavailable',
+ catalogRevision: 2,
+ },
+ })
+ const res = await request(makeAuthedApp(makeGateway(materialize))).post(
+ '/admin/llm/providers/codex-subscription/catalog/sync'
+ )
+ expect(res.status).toBe(503)
+ expect(res.body.error).toBe('configmap_write_failed')
+ expect(materialize).toHaveBeenCalledTimes(1)
+ assertNoLeak(res.body)
+ })
+
it('publishes the runtime ConfigMap after revoke', async () => {
const materialize = vi.fn(async () => {})
oauth.revoke.mockResolvedValue({
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index a3bc0de8d..ddbc1f755 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -3,6 +3,7 @@ import express from 'express'
import request from 'supertest'
import { pool } from '../src/db.js'
import { createAdminPluginWorkloadSdkRouter } from '../src/routes/admin/pluginWorkloadSdk.js'
+import { isCodexAssignmentAllowed } from '../src/services/codexSubscriptionCatalog.js'
import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'
import { checkAndIncrement } from '../src/services/rateLimiterService.js'
@@ -44,6 +45,13 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
}
})
+// Codex targets are gated against the per-connection catalog, not the flat
+// llm_allowed_models union. The seam is mocked so tests pin the accept/reject
+// contract without a live codex_subscription_connections table.
+vi.mock('../src/services/codexSubscriptionCatalog.js', () => ({
+ isCodexAssignmentAllowed: vi.fn(),
+}))
+
const DEFAULT_ADMIN_SUB = '11111111-1111-4111-8111-111111111111'
function buildApp(sub: string | null = DEFAULT_ADMIN_SUB) {
@@ -97,6 +105,8 @@ beforeEach(() => {
// tests override to simulate a disallowed model.
vi.mocked(pool.query).mockReset()
vi.mocked(pool.query).mockResolvedValue({ rows: [{ model: 'glm-4.7' }], rowCount: 1 } as never)
+ vi.mocked(isCodexAssignmentAllowed).mockReset()
+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(false)
})
describe('routes/admin/pluginWorkloadSdk — grants', () => {
@@ -544,6 +554,141 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
})
+ // ── Claim 1b: Codex (oauth-broker) promptBridge targets ─────────────────────
+ describe('codex-subscription promptTargets', () => {
+ const codexGrantBody = {
+ ...validGrantBody,
+ provider: 'codex-subscription',
+ allowedModels: ['gpt-5.3-codex'],
+ promptTargets: [
+ {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ credentialSlot: '',
+ connectionRef: 'team-plus',
+ },
+ ],
+ defaultTargetRef: 'codex-primary',
+ }
+
+ it('accepts a Codex target bound to a permitted connection offering the model', async () => {
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-codex' } as never)
+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(true)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send(codexGrantBody)
+ expect(res.status).toBe(200)
+ expect(isCodexAssignmentAllowed).toHaveBeenCalledWith(
+ expect.anything(),
+ 'team-plus',
+ 'gpt-5.3-codex'
+ )
+ expect(sdkDb.upsertGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ provider: 'codex-subscription',
+ promptTargets: [
+ {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ credentialSlot: '',
+ connectionRef: 'team-plus',
+ },
+ ],
+ }),
+ '11111111-1111-4111-8111-111111111111',
+ expect.anything() // carrier transaction client (R1-H3 fase 2)
+ )
+ })
+
+ it('fails closed when the connection is unknown, revoked, or does not offer the model', async () => {
+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(false)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send(codexGrantBody)
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({
+ error: 'codex_connection_not_allowed',
+ connectionRef: 'team-plus',
+ model: 'gpt-5.3-codex',
+ })
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects a Codex target without a connectionRef', async () => {
+ const { connectionRef: _omitted, ...targetWithoutConnection } =
+ codexGrantBody.promptTargets[0]!
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({ ...codexGrantBody, promptTargets: [targetWithoutConnection] })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toContain('connectionRef')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects the unassigned sentinel as a Codex connection choice', async () => {
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...codexGrantBody,
+ promptTargets: [{ ...codexGrantBody.promptTargets[0]!, connectionRef: 'unassigned' }],
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toContain('connectionRef')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects a static credentialSlot on a Codex (oauth-broker) target', async () => {
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...codexGrantBody,
+ promptTargets: [
+ { ...codexGrantBody.promptTargets[0]!, credentialSlot: 'openai-api-key' },
+ ],
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toContain('credentialSlot must be empty')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects a connectionRef on an API-key (static-credentials) target', async () => {
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...validGrantBody,
+ promptTargets: [{ ...validGrantBody.promptTargets[0]!, connectionRef: 'team-plus' }],
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toContain('only valid for oauth-broker')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
+ it('keeps API-key promptTargets unchanged (no Codex gate, no connectionRef)', async () => {
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g1' } as never)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send(validGrantBody)
+ expect(res.status).toBe(200)
+ expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()
+ expect(sdkDb.upsertGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ promptTargets: [
+ {
+ targetRef: 'primary-zai',
+ provider: 'zai',
+ model: 'glm-4.7',
+ credentialSlot: 'zai-api-key',
+ },
+ ],
+ }),
+ '11111111-1111-4111-8111-111111111111',
+ expect.anything() // carrier transaction client (R1-H3 fase 2)
+ )
+ })
+ })
+
// ── Pieza D: no-worsening tolerance for grant `allowed_models` (G3) ─────────
describe('no-worsening tolerance', () => {
const buildAppWithEmit = (emit: (event: unknown) => void) => {
diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
index 08c52ebc8..e6c67b394 100644
--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
@@ -171,14 +171,55 @@ describe('resolveHostAssignedConnectionKey', () => {
)
})
- it('aliases a recipe caller to unassigned without a Host GET', async () => {
+ it('attests a recipe caller from the codex-connection-ref annotation', async () => {
const gateway = {
- getResource: vi.fn(),
+ getResource: vi.fn().mockResolvedValue({
+ metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },
+ }),
+ }
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')
+ ).resolves.toBe('team-plus')
+ expect(gateway.getResource).toHaveBeenCalledWith(
+ 'workflowrecipes',
+ 'codex-recipe',
+ 'sandbox-recipes'
+ )
+ })
+
+ it('treats a recipe without the grant annotation as unassigned', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({ metadata: { annotations: {} } }),
}
await expect(
resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe')
).resolves.toBe('unassigned')
- expect(gateway.getResource).not.toHaveBeenCalled()
+
+ gateway.getResource.mockResolvedValueOnce({
+ metadata: { annotations: { 'clerum.io/codex-connection-ref': ' ' } },
+ })
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/blank-annotation')
+ ).resolves.toBe('unassigned')
+
+ gateway.getResource.mockResolvedValueOnce({})
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/no-metadata')
+ ).resolves.toBe('unassigned')
+ })
+
+ it('fails closed when the recipe cannot be attested', async () => {
+ const gateway = {
+ getResource: vi.fn().mockRejectedValue(Object.assign(new Error('nf'), { code: 404 })),
+ }
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/ghost-recipe')
+ ).rejects.toMatchObject({ code: 'host_binding_mismatch' })
+
+ // Malformed multi-segment refs never reach the gateway.
+ await expect(resolveHostAssignedConnectionKey(gateway, 'ns/name/extra')).rejects.toMatchObject({
+ code: 'host_binding_mismatch',
+ })
})
it('fails closed when the Host cannot be attested', async () => {
diff --git a/control-ui/app/plugin-workload-sdk/Views.tsx b/control-ui/app/plugin-workload-sdk/Views.tsx
index cea47fa16..55f699ce2 100644
--- a/control-ui/app/plugin-workload-sdk/Views.tsx
+++ b/control-ui/app/plugin-workload-sdk/Views.tsx
@@ -127,7 +127,7 @@ export function GrantsView({
grant.capabilityFamily === 'promptBridge'
? (grant.promptTargets ?? []).map(
(target, index) =>
- `${index === 0 ? 'default' : `fallback ${index}`}: ${target.provider}/${target.model} (${target.credentialSlot})`
+ `${index === 0 ? 'default' : `fallback ${index}`}: ${target.provider}/${target.model} (${target.connectionRef ? `sub:${target.connectionRef}` : target.credentialSlot})`
)
: grant.allowedEventTypes
const quotaParts: string[] = []
diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsx
index b4fa8e028..a08beff35 100644
--- a/control-ui/app/plugin-workload-sdk/page.tsx
+++ b/control-ui/app/plugin-workload-sdk/page.tsx
@@ -30,10 +30,16 @@ import {
searchPluginWorkloadSdkInvocations,
upsertPluginWorkloadSdkGrant,
} from '@lib/api'
+import {
+ type CodexSubscriptionConnectionView,
+ listCodexConnectionModels,
+ listCodexSubscriptionConnections,
+} from '@lib/codexSubscription'
import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'
import {
LLM_PROVIDER_OPTIONS,
type LlmProvider,
+ OPENAI_SUBSCRIPTION_PROVIDER,
buildPromptBridgeTargetPolicy,
getModelOptions,
getPromptBridgeCredentialSlotOptions,
@@ -454,6 +460,14 @@ function GrantFormModal({
const [targetModel, setTargetModel] = useState('')
const [credentialSlot, setCredentialSlot] = useState('')
const [availableCredentialKeys, setAvailableCredentialKeys] = useState<string[]>([])
+ // Codex (oauth-broker) targets choose an EXISTING permitted subscription
+ // grant instead of a Secret data key. Only connected grants with a ready
+ // catalog are listed, and the model picker narrows to that grant's enabled
+ // non-stale models — the same "choose, don't create" lock Hosts follow.
+ const isCodexProvider = modelProvider === OPENAI_SUBSCRIPTION_PROVIDER
+ const [codexConnectionRef, setCodexConnectionRef] = useState('')
+ const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])
+ const [codexModels, setCodexModels] = useState<string[]>([])
const [allowedEventTypes, setAllowedEventTypes] = useState(
(grant?.allowedEventTypes ?? []).join(', ')
)
@@ -516,6 +530,45 @@ function GrantFormModal({
cancelled = true
}
}, [])
+ useEffect(() => {
+ if (!isCodexProvider) return
+ let cancelled = false
+ listCodexSubscriptionConnections()
+ .then(connections => {
+ if (cancelled) return
+ setCodexConnections(
+ connections.filter(
+ connection => connection.status === 'connected' && connection.catalogStatus === 'ready'
+ )
+ )
+ })
+ .catch(() => {
+ // Fail closed: without a readable connection list no Codex target can
+ // be added; the save endpoint stays the source of truth.
+ if (!cancelled) setCodexConnections([])
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [isCodexProvider])
+ useEffect(() => {
+ if (!isCodexProvider || !codexConnectionRef) {
+ setCodexModels([])
+ return
+ }
+ let cancelled = false
+ listCodexConnectionModels(codexConnectionRef)
+ .then(models => {
+ if (cancelled) return
+ setCodexModels(models.filter(row => row.enabled && !row.stale).map(row => row.model))
+ })
+ .catch(() => {
+ if (!cancelled) setCodexModels([])
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [isCodexProvider, codexConnectionRef])
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState('')
@@ -580,17 +633,21 @@ function GrantFormModal({
const callersList = parseList(allowedCallers)
const wildcardPresent =
promptTargets.some(target =>
- [target.targetRef, target.provider, target.model, target.credentialSlot].some(value =>
- value.includes('*')
- )
+ [
+ target.targetRef,
+ target.provider,
+ target.model,
+ target.credentialSlot,
+ target.connectionRef ?? '',
+ ].some(value => value.includes('*'))
) ||
hasWildcard(eventTypesList) ||
hasWildcard(parseList(allowedTargetRefs)) ||
hasWildcard(callersList)
const providerModelOptions = useMemo(
- () => getModelOptions(allowedCatalog, modelProvider),
- [allowedCatalog, modelProvider]
+ () => (isCodexProvider ? codexModels : getModelOptions(allowedCatalog, modelProvider)),
+ [allowedCatalog, codexModels, isCodexProvider, modelProvider]
)
const credentialSlotOptions = useMemo(
() => getPromptBridgeCredentialSlotOptions(modelProvider, availableCredentialKeys),
@@ -674,8 +731,11 @@ function GrantFormModal({
function addPromptTarget() {
const model = targetModel.trim()
const slot = credentialSlot.trim()
+ const connectionRef = codexConnectionRef.trim()
const ref = targetRef.trim() || `${modelProvider}-${model}-${promptTargets.length + 1}`
- if (!model || !slot || !ref) return
+ // Codex targets bind a permitted subscription grant and carry no static
+ // Secret slot; API-key targets keep requiring a provider-owned slot.
+ if (!model || !ref || (isCodexProvider ? !connectionRef : !slot)) return
if (
promptTargets.some(
target =>
@@ -687,7 +747,9 @@ function GrantFormModal({
}
setPromptTargets(current => [
...current,
- { targetRef: ref, provider: modelProvider, model, credentialSlot: slot },
+ isCodexProvider
+ ? { targetRef: ref, provider: modelProvider, model, credentialSlot: '', connectionRef }
+ : { targetRef: ref, provider: modelProvider, model, credentialSlot: slot },
])
setTargetRef('')
setTargetModel('')
@@ -807,6 +869,7 @@ function GrantFormModal({
setModelProvider(next)
setTargetModel('')
setCredentialSlot('')
+ setCodexConnectionRef('')
}}
>
{LLM_PROVIDER_OPTIONS.map(option => (
@@ -841,26 +904,54 @@ function GrantFormModal({
))}
</SelectInput>
</Field>
- <Field
- label="Credential slot"
- htmlFor="sdk-credential-slot"
- required
- description="Sanitized Secret data-key identity owned by this provider. Its value is never displayed or sent to the workload."
- >
- <SelectInput
- id="sdk-credential-slot"
- compact
- value={credentialSlot}
- onChange={e => setCredentialSlot(e.target.value)}
+ {isCodexProvider ? (
+ <Field
+ label="Codex subscription"
+ htmlFor="sdk-codex-connection"
+ required
+ description="Choose an existing connected ChatGPT subscription grant. Grants are created in Secrets & Connections; this policy only selects one, and only its enabled models can be added."
>
- <option value="">Select provider-owned slot…</option>
- {credentialSlotOptions.map(slot => (
- <option key={slot} value={slot}>
- {slot}
- </option>
- ))}
- </SelectInput>
- </Field>
+ <SelectInput
+ id="sdk-codex-connection"
+ compact
+ value={codexConnectionRef}
+ onChange={e => {
+ setCodexConnectionRef(e.target.value)
+ setTargetModel('')
+ }}
+ >
+ <option value="">Select connected subscription…</option>
+ {codexConnections.map(connection => (
+ <option key={connection.connectionKey} value={connection.connectionKey}>
+ {connection.displayName
+ ? `${connection.displayName} (${connection.connectionKey})`
+ : connection.connectionKey}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+ ) : (
+ <Field
+ label="Credential slot"
+ htmlFor="sdk-credential-slot"
+ required
+ description="Sanitized Secret data-key identity owned by this provider. Its value is never displayed or sent to the workload."
+ >
+ <SelectInput
+ id="sdk-credential-slot"
+ compact
+ value={credentialSlot}
+ onChange={e => setCredentialSlot(e.target.value)}
+ >
+ <option value="">Select provider-owned slot…</option>
+ {credentialSlotOptions.map(slot => (
+ <option key={slot} value={slot}>
+ {slot}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+ )}
<Field
label="Target reference"
htmlFor="sdk-target-ref"
@@ -880,7 +971,10 @@ function GrantFormModal({
type="button"
size="sm"
onClick={addPromptTarget}
- disabled={!targetModel.trim() || !credentialSlot.trim()}
+ disabled={
+ !targetModel.trim() ||
+ (isCodexProvider ? !codexConnectionRef.trim() : !credentialSlot.trim())
+ }
>
Add target
</Button>
@@ -893,7 +987,10 @@ function GrantFormModal({
<code>
{index === 0 ? 'default · ' : `fallback ${index} · `}
{target.targetRef}: {getProviderLabel(target.provider as LlmProvider)} /{' '}
- {target.model} / {target.credentialSlot}
+ {target.model} /{' '}
+ {target.connectionRef
+ ? `sub:${target.connectionRef}`
+ : target.credentialSlot}
</code>
<Button
type="button"
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 32694f529..2a3773de4 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -3630,7 +3630,12 @@ export type PluginWorkloadSdkPromptTarget = {
provider: string
model: string
// Identity of a provider-owned secret data key; never a secret value.
+ // Empty for oauth-broker (Codex) targets, which have no static Secret key.
credentialSlot: string
+ // Codex subscription connection key the target executes against. Only set
+ // for oauth-broker providers; the grant must already exist (choose, don't
+ // create) and offer the selected model.
+ connectionRef?: string
}
export type PluginWorkloadSdkQuotaLimits = {
diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.ts
index 1ee0c0525..d8bedc31a 100644
--- a/control-ui/lib/llm.ts
+++ b/control-ui/lib/llm.ts
@@ -19,6 +19,9 @@ export type PromptBridgeTargetPolicyInput = {
provider: string
model: string
credentialSlot: string
+ // Codex subscription connection key for oauth-broker targets. Optional and
+ // pass-through: the ordered policy serializer never invents or drops it.
+ connectionRef?: string
}
/**
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index e21405a89..7e0f771e7 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.468",
+ "version": "0.1.469",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.468",
+ "version": "0.1.469",
"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 b5e2928f6..bb33e2433 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.468",
+ "version": "0.1.469",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 13925ccfa..8f00c9185 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.289",
+ "version": "0.1.290",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.289",
+ "version": "0.1.290",
"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 45e4d0aef..1bc3898b0 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.289",
+ "version": "0.1.290",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/llm/__tests__/codexSubscription.test.ts b/mcp-host/src/llm/__tests__/codexSubscription.test.ts
index 72f14fdda..9b59a73d1 100644
--- a/mcp-host/src/llm/__tests__/codexSubscription.test.ts
+++ b/mcp-host/src/llm/__tests__/codexSubscription.test.ts
@@ -1,10 +1,12 @@
import { describe, expect, it, vi } from 'vitest'
import { LlmErrorCode } from '../../core/errors'
+import { CodexProxyError } from '../codexLlmProxyClient'
import {
CodexSubscriptionProvider,
isCodexNativeToolName,
selectCodexAdvertisedTools,
} from '../codexSubscription'
+import { classifyFailoverClass } from '../failover/classify'
import { CodexAuthorizeError } from '../providerAttemptAuthorizer'
import { makeProvider } from '../registry'
@@ -243,4 +245,21 @@ describe('CodexSubscriptionProvider', () => {
expect(classified.providerCode).toBe('insufficient_scope')
expect(classified.retryable).toBe(false)
})
+
+ it('maps transient proxy failures onto failover-eligible classes', () => {
+ const provider = new CodexSubscriptionProvider('gpt-5.3-codex', deps() as never)
+ const unavailable = provider.classifyError(
+ new CodexProxyError('provider_unavailable', 'upstream 5xx')
+ )
+ expect(unavailable.code).toBe(LlmErrorCode.ModelOverloaded)
+ expect(unavailable.retryable).toBe(true)
+ expect(classifyFailoverClass(unavailable.code, unavailable.retryable)).toBe(
+ 'provider_unavailable'
+ )
+
+ const limited = provider.classifyError(new CodexProxyError('rate_limited', 'upstream 429'))
+ expect(limited.code).toBe(LlmErrorCode.RateLimited)
+ expect(limited.retryable).toBe(true)
+ expect(classifyFailoverClass(limited.code, limited.retryable)).toBe('rate_limited')
+ })
})
diff --git a/mcp-host/src/llm/codexSubscription.ts b/mcp-host/src/llm/codexSubscription.ts
index d2382db60..40a22862d 100644
--- a/mcp-host/src/llm/codexSubscription.ts
+++ b/mcp-host/src/llm/codexSubscription.ts
@@ -142,6 +142,22 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {
providerCode: code,
}
}
+ if (code === 'rate_limited') {
+ return {
+ code: LlmErrorCode.RateLimited,
+ retryable: true,
+ message: err instanceof Error ? err.message : String(err),
+ providerCode: code,
+ }
+ }
+ if (code === 'provider_unavailable' || code === 'connection_unavailable') {
+ return {
+ code: LlmErrorCode.ModelOverloaded,
+ retryable: true,
+ message: err instanceof Error ? err.message : String(err),
+ providerCode: code,
+ }
+ }
if (code) {
return {
code: LlmErrorCode.ApiCallFailed,
diff --git a/mcp-host/src/pluginWorkloadSdk/domain/types.ts b/mcp-host/src/pluginWorkloadSdk/domain/types.ts
index 2a876c70e..c408519b5 100644
--- a/mcp-host/src/pluginWorkloadSdk/domain/types.ts
+++ b/mcp-host/src/pluginWorkloadSdk/domain/types.ts
@@ -40,7 +40,14 @@ export interface PromptBridgeTarget {
targetRef: string
provider: string
model: string
+ /** Empty for oauth-broker (Codex) targets: no static Secret data key exists. */
credentialSlot: string
+ /**
+ * Codex subscription grant (connection key) chosen by the operator for an
+ * oauth-broker target. Attestation authority stays with control-api via the
+ * recipe-level annotation; this field is carried for identity/audit only.
+ */
+ connectionRef?: string
}
export interface PromptBridgeResult {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index cd21c0e91..e63ecf73d 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -255,7 +255,9 @@ function isPromptBridgeTarget(value: unknown): value is PromptBridgeTarget {
typeof target.targetRef === 'string' &&
typeof target.provider === 'string' &&
typeof target.model === 'string' &&
- typeof target.credentialSlot === 'string'
+ typeof target.credentialSlot === 'string' &&
+ // Optional Codex subscription grant identity (oauth-broker targets only).
+ (target.connectionRef === undefined || typeof target.connectionRef === 'string')
)
}
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index 71f8dda5f..726a5b8c1 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -580,6 +580,9 @@ describe('LlmBridge authorized multi-provider fallback', () => {
provider: 'codex-subscription',
model: 'gpt-5.1',
credentialSlot: '',
+ // Claim 1b: the grant identity travels with the target for audit; it must
+ // not trigger any secret redemption or leak into the result payload.
+ connectionRef: 'team-plus',
}
const provider = new FakeProvider(async () => ({
...OK,
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index e80c986c6..07afbdcc3 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -250,7 +250,13 @@ export class LlmBridge {
}
private breakerKey(target: PromptBridgeTarget): string {
- return [target.targetRef, target.provider, target.model, target.credentialSlot].join('\u0000')
+ return [
+ target.targetRef,
+ target.provider,
+ target.model,
+ target.credentialSlot,
+ target.connectionRef ?? '',
+ ].join('\u0000')
}
private breakerFor(target: PromptBridgeTarget): CircuitBreaker {
diff --git a/scripts/e2e/e2e-codex-subscription-runtime.sh b/scripts/e2e/e2e-codex-subscription-runtime.sh
index c32a23705..59977084b 100755
--- a/scripts/e2e/e2e-codex-subscription-runtime.sh
+++ b/scripts/e2e/e2e-codex-subscription-runtime.sh
@@ -1,7 +1,33 @@
#!/usr/bin/env bash
-# RED acceptance harness for Codex subscription runtime integration.
-# GREEN is captured after Tasks 15–20. This script must fail on missing
-# scope/path, not on an ambiguous Kubernetes context.
+# Codex subscription runtime acceptance harness. Two load-bearing phases:
+#
+# Phase A — hermetic transport path (host-side, no cluster writes):
+# Runs codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts, which drives
+# authorize (mocked control-api redeem keyed by the recipe-level grant
+# identity) → the REAL proxy runtime listener → the REAL fixture ChatGPT
+# upstream (tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs,
+# spawned over TLS on loopback) → finalize, asserting the success receipt,
+# usage, and the fail-closed `no_grant` denial for an unassigned recipe.
+# No live ChatGPT OAuth is involved anywhere.
+#
+# Phase B — in-cluster projection path (branch-owned local profile only):
+# Seeds the published allowlist ConfigMap with a CONNECTED test grant
+# (multi-connection annotation) offering gpt-5.3-codex, binds the e2e Host
+# to that grant via spec.model.connectionRef (never `unassigned`, never an
+# invented `deployment-default`), stamps the WorkflowRecipe with the
+# `clerum.io/codex-connection-ref` grant annotation, and asserts HCC
+# projected `llm:codex:execute` plus the Codex proxy egress NetworkPolicy.
+# These assertions are load-bearing: with the grant removed or unassigned,
+# HCC fails closed and the scope is not emitted. The prior ConfigMap is
+# restored on exit.
+#
+# Remaining documented gap: the in-cluster authorize → proxy → upstream →
+# finalize hop is NOT driven here, because redemption requires live
+# control-api grant/credential rows (created only through the real OAuth
+# connect flow) and the proxy origin policy freezes https://chatgpt.com. That
+# transport hop is certified hermetically by Phase A against the same fixture
+# upstream this script deploys in-cluster. Do not weaken the origin policy or
+# invent live OAuth to close this gap.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
@@ -22,12 +48,15 @@ KUBECTL=(kubectl --context "$KUBECONTEXT")
HOST_NS="${HOST_NS:-mcp-host}"
RECIPE_NS="${RECIPE_NS:-sandbox-recipes}"
CONTROL_NS="${CONTROL_NS:-control-plane}"
+ALLOWLIST_CM="clerum-llm-allowed-models"
RUN_ID="$(date +%H%M%S)-$$"
HOST_NAME="e2e-codex-host-${RUN_ID}"
RECIPE_NAME="e2e-codex-recipe-${RUN_ID}"
UPSTREAM_NAME="e2e-codex-up-${RUN_ID}"
+GRANT_KEY="e2e-team-plus-${RUN_ID}"
WORKDIR="$(mktemp -d)"
CLEANED=0
+ALLOWLIST_BACKED_UP=0
cleanup() {
if [[ "$CLEANED" -eq 1 ]]; then
@@ -37,18 +66,41 @@ cleanup() {
"${KUBECTL[@]}" delete host "$HOST_NAME" -n "$HOST_NS" --ignore-not-found --wait=false >/dev/null 2>&1 || true
"${KUBECTL[@]}" delete workflowrecipe "$RECIPE_NAME" -n "$RECIPE_NS" --ignore-not-found --wait=false >/dev/null 2>&1 || true
"${KUBECTL[@]}" delete deploy,svc,cm,secret -n "$CONTROL_NS" -l "e2e.clerum.io/run=${RUN_ID}" --ignore-not-found --wait=false >/dev/null 2>&1 || true
+ # Restore the published allowlist ConfigMap exactly as found (or remove the
+ # seeded one when none existed) so the branch profile keeps its state.
+ if [[ "$ALLOWLIST_BACKED_UP" -eq 1 ]]; then
+ if [[ -s "${WORKDIR}/allowlist-backup.json" ]]; then
+ "${KUBECTL[@]}" -n "$HOST_NS" delete configmap "$ALLOWLIST_CM" --ignore-not-found >/dev/null 2>&1 || true
+ "${KUBECTL[@]}" -n "$HOST_NS" create -f "${WORKDIR}/allowlist-backup.json" >/dev/null 2>&1 || true
+ else
+ "${KUBECTL[@]}" -n "$HOST_NS" delete configmap "$ALLOWLIST_CM" --ignore-not-found >/dev/null 2>&1 || true
+ fi
+ fi
rm -rf "$WORKDIR"
}
trap cleanup EXIT
+WORKTREE_HEAD="$(git -C "$ROOT" rev-parse HEAD)"
+echo "codex_runtime: worktree=${ROOT} head=${WORKTREE_HEAD} context=${KUBECONTEXT}"
+
+# ─── Phase A: hermetic authorize → proxy → fixture upstream → finalize ──────
+if [[ ! -d "${ROOT}/codex-llm-proxy/node_modules" ]]; then
+ echo "codex_runtime: dependency_missing (run npm ci in codex-llm-proxy first)" >&2
+ exit 2
+fi
+echo "codex_runtime: phase A (hermetic proxy transport) starting"
+if ! (cd "${ROOT}/codex-llm-proxy" && npx vitest run test/runtimePath.hermetic.e2e.test.ts); then
+ echo "codex_runtime: transport_failed (hermetic authorize→proxy→upstream→finalize)" >&2
+ exit 1
+fi
+echo "codex_runtime: phase A passed"
+
+# ─── Phase B: in-cluster grant projection ────────────────────────────────────
if ! "${KUBECTL[@]}" get ns "$CONTROL_NS" >/dev/null 2>&1; then
echo "codex_runtime: workload_missing" >&2
exit 3
fi
-WORKTREE_HEAD="$(git -C "$ROOT" rev-parse HEAD)"
-echo "codex_runtime: worktree=${ROOT} head=${WORKTREE_HEAD} context=${KUBECONTEXT}"
-
openssl req -x509 -newkey rsa:2048 -nodes -days 1 \
-keyout "${WORKDIR}/tls.key" \
-out "${WORKDIR}/tls.crt" \
@@ -68,6 +120,40 @@ sed -e "s/\${UPSTREAM_NAME}/${UPSTREAM_NAME}/g" -e "s/\${RUN_ID}/${RUN_ID}/g" \
"${ROOT}/tests/e2e/fixtures/codex-subscription/test-upstream/manifest.yaml" \
| "${KUBECTL[@]}" apply -f - >/dev/null
+# Snapshot the current published allowlist so cleanup restores it verbatim.
+if "${KUBECTL[@]}" -n "$HOST_NS" get configmap "$ALLOWLIST_CM" >/dev/null 2>&1; then
+ "${KUBECTL[@]}" -n "$HOST_NS" get configmap "$ALLOWLIST_CM" -o json \
+ | python3 -c '
+import json, sys
+cm = json.load(sys.stdin)
+meta = cm.get("metadata", {})
+for key in ("resourceVersion", "uid", "creationTimestamp", "managedFields", "generation"):
+ meta.pop(key, None)
+print(json.dumps(cm))
+' > "${WORKDIR}/allowlist-backup.json"
+else
+ : > "${WORKDIR}/allowlist-backup.json"
+fi
+ALLOWLIST_BACKED_UP=1
+
+# Seed a CONNECTED test grant. The grant is CREATED here (published catalog),
+# and the Host/recipe below only CHOOSE it — the same lock production follows.
+"${KUBECTL[@]}" apply -f - >/dev/null <<YAML
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: ${ALLOWLIST_CM}
+ namespace: ${HOST_NS}
+ annotations:
+ clerum.io/codex-enabled: "true"
+ clerum.io/catalog-revision: "1"
+ clerum.io/connection-revision: "1"
+ clerum.io/codex-connection-status: connected
+ clerum.io/codex-connections: '{"${GRANT_KEY}":{"status":"connected","catalogRevision":1,"connectionRevision":1,"models":["gpt-5.3-codex"]}}'
+data:
+ codex-subscription: '[{"model":"gpt-5.3-codex"}]'
+YAML
+
"${KUBECTL[@]}" apply -f - >/dev/null <<YAML
apiVersion: clerum.io/v1alpha1
kind: Host
@@ -83,6 +169,7 @@ spec:
model:
provider: codex-subscription
name: gpt-5.3-codex
+ connectionRef: ${GRANT_KEY}
---
apiVersion: clerum.io/v1alpha1
kind: WorkflowRecipe
@@ -92,6 +179,8 @@ metadata:
labels:
e2e.clerum.io/suite: codex-subscription
e2e.clerum.io/run: "${RUN_ID}"
+ annotations:
+ clerum.io/codex-connection-ref: ${GRANT_KEY}
spec:
workloads: []
agent:
@@ -145,7 +234,7 @@ print(json.dumps({
echo "codex_runtime: redacted_claims=${claims}"
if ! python3 -c 'import json,sys; raise SystemExit(0 if json.loads(sys.argv[1]).get("has_codex_execute") else 1)' "$claims"; then
- echo "codex_runtime: scope_missing (HCC did not emit llm:codex:execute)" >&2
+ echo "codex_runtime: scope_missing (HCC did not emit llm:codex:execute for the connected grant)" >&2
exit 1
fi
@@ -155,4 +244,14 @@ if [[ "$proxy_np" != *codex* ]]; then
exit 1
fi
-echo "codex_runtime: integration assertions passed"
+# Claim 1 identity round-trip: the recipe-level grant annotation must survive
+# in the API server exactly as written, because control-api attests the grant
+# by reading it back from the recipe named in hostRef.
+recipe_grant="$("${KUBECTL[@]}" get workflowrecipe "$RECIPE_NAME" -n "$RECIPE_NS" \
+ -o jsonpath='{.metadata.annotations.clerum\.io/codex-connection-ref}')"
+if [[ "$recipe_grant" != "$GRANT_KEY" ]]; then
+ echo "codex_runtime: grant_annotation_missing (recipe grant identity did not round-trip)" >&2
+ exit 1
+fi
+
+echo "codex_runtime: integration assertions passed (grant=${GRANT_KEY})"
diff --git a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
index 8288d7e50..f33be5c74 100755
--- a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
+++ b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
@@ -114,11 +114,19 @@ const server = createServer({ cert, key }, async (request, response) => {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
})
+ // The proxy transport parser (codexTransport.consumeSse) dispatches on
+ // the `type` field INSIDE the data payload, exactly like the live
+ // ChatGPT backend. `event:` lines alone are ignored, so frames without
+ // an embedded type would leave the stream outcome `unknown`.
response.write(
- `event: response.output_text.delta\ndata: ${JSON.stringify({ delta: 'hello' })}\n\n`
+ `event: response.output_text.delta\ndata: ${JSON.stringify({
+ type: 'response.output_text.delta',
+ delta: 'hello',
+ })}\n\n`
)
response.write(
`event: response.completed\ndata: ${JSON.stringify({
+ type: 'response.completed',
id: streamId,
usage: { input_tokens: 3, output_tokens: 1 },
})}\n\n`
diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.json
index 6b7ba3961..b27a139fb 100644
--- a/tests/e2e/fixtures/package-lock.json
+++ b/tests/e2e/fixtures/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.67",
+ "version": "1.0.68",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.67",
+ "version": "1.0.68",
"dependencies": {
"@kubernetes/client-node": "^1.0.0"
},
diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.json
index 077439335..8b093d1d3 100644
--- a/tests/e2e/fixtures/package.json
+++ b/tests/e2e/fixtures/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.67",
+ "version": "1.0.68",
"description": "E2E test fixtures and utilities for Clerum testing",
"type": "module",
"main": "index.ts",
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 4ba56d3dd..1449732c9 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.309",
+ "version": "0.1.310",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.309",
+ "version": "0.1.310",
"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 a4d034678..1db94c0e9 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.309",
+ "version": "0.1.310",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index 907af81dd..57f82f50d 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -6758,6 +6758,7 @@ describe('WorkflowRecipeReconciler', () => {
runtimeScopeRecipeName: 'child-run',
claimedParent: true,
parentSpec: null,
+ connectionKey: 'unassigned',
})
})
@@ -6814,6 +6815,67 @@ describe('WorkflowRecipeReconciler', () => {
runtimeScopeRecipeName: 'parent-recipe',
claimedParent: true,
parentSpec,
+ connectionKey: 'unassigned',
+ })
+ })
+
+ it('binds the inherited parent Codex grant annotation to the reconcile context', async () => {
+ const parentSpec = {
+ agent: { provider: 'codex-subscription' as const, model: 'gpt-5.3-codex' },
+ steps: [{ id: 'research', instruction: 'parent target' }],
+ }
+ mockCustomApi.getNamespacedCustomObject.mockImplementation(({ name }: { name?: string }) =>
+ Promise.resolve({
+ metadata: {
+ uid: liveWorkflowRecipeUid(name),
+ resourceVersion: '1',
+ ...(name === 'parent-recipe'
+ ? { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } }
+ : {}),
+ },
+ spec: name === 'parent-recipe' ? parentSpec : { mcpServers: [] },
+ })
+ )
+ const setCodexReconcileContext = vi.fn()
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ setCodexReconcileContext: typeof setCodexReconcileContext
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ }
+ }
+ ).workflowReconciler = { setCodexReconcileContext, ensureMcpHostRuntimeCredentials }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: {
+ 'clerum.io/parent-recipe': 'parent-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
+ },
+ spec: {
+ agent: { provider: 'openai', model: 'gpt-5.4-mini' },
+ steps: [{ id: 'research', instruction: 'child body must not win' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(setCodexReconcileContext).toHaveBeenCalledWith({
+ recipeName: 'child-run',
+ runtimeScopeRecipeName: 'parent-recipe',
+ claimedParent: true,
+ parentSpec,
+ connectionKey: 'team-plus',
})
})
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index fe50fd71c..e294ec93f 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -42,6 +42,7 @@ import {
import { HttpMcpHostClient } from '../workflow/httpMcpHostClient'
import { JwtTokenFactory } from '../workflow/jwtTokenFactory'
import { K8sSecretReaderImpl } from '../workflow/k8sSecretReaderImpl'
+import { readRecipeCodexConnectionRef } from '../workflow/llmAllowedModelsSnapshot'
import { ModelConfigHandler } from '../workflow/modelConfigHandler'
import { buildCoordinatorGfsNetworkPolicy } from '../workflow/networkPolicyFactory'
import type { EagerSdkBootstrapProof } from '../workflow/pluginWorkloadSdkProvisioner'
@@ -1014,11 +1015,11 @@ export class WorkflowRecipeReconciler {
return Boolean(parentLabel || ownerRef)
}
- private async loadCodexParentSpec(
+ private async loadCodexParent(
recipe: WorkflowRecipeCRD,
runtimeScopeRecipeName: string
- ): Promise<WorkflowRecipeSpec | null> {
- if (runtimeScopeRecipeName === recipe.metadata.name) return null
+ ): Promise<{ spec: WorkflowRecipeSpec | null; annotations?: Record<string, string> }> {
+ if (runtimeScopeRecipeName === recipe.metadata.name) return { spec: null }
try {
const live = (await this.customApi.getNamespacedCustomObject({
group: CRD_GROUP,
@@ -1026,10 +1027,10 @@ export class WorkflowRecipeReconciler {
namespace: recipe.metadata.namespace,
plural: WORKFLOWRECIPE_PLURAL,
name: runtimeScopeRecipeName,
- })) as { spec?: WorkflowRecipeSpec }
- return live.spec ?? null
+ })) as { metadata?: { annotations?: Record<string, string> }; spec?: WorkflowRecipeSpec }
+ return { spec: live.spec ?? null, annotations: live.metadata?.annotations }
} catch {
- return null
+ return { spec: null }
}
}
@@ -1039,11 +1040,21 @@ export class WorkflowRecipeReconciler {
): Promise<void> {
const setter = this.workflowReconciler?.setCodexReconcileContext
if (typeof setter !== 'function') return
+ const parent = await this.loadCodexParent(recipe, runtimeScopeRecipeName)
+ // The Codex grant (connection key) follows the same authority rule as the
+ // Codex spec: the runtime-scope parent's annotation when inherited, the
+ // recipe's own annotation when standalone. Missing/unreadable annotations
+ // resolve to the fail-closed `unassigned` sentinel inside the reader.
+ const grantAnnotations =
+ runtimeScopeRecipeName !== recipe.metadata.name
+ ? parent.annotations
+ : recipe.metadata.annotations
setter.call(this.workflowReconciler, {
recipeName: recipe.metadata.name,
runtimeScopeRecipeName,
claimedParent: this.claimedCodexParent(recipe),
- parentSpec: await this.loadCodexParentSpec(recipe, runtimeScopeRecipeName),
+ parentSpec: parent.spec,
+ connectionKey: readRecipeCodexConnectionRef(grantAnnotations),
})
}
diff --git a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts
index 4a48888e4..ec491d994 100644
--- a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts
+++ b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts
@@ -197,6 +197,42 @@ describe('createDbRunChildRecipe', () => {
expect(childSpec?.computed).toEqual([{ name: 'db_mode', expression: "'readonly'" }])
})
+ it('copies the parent Codex grant annotation onto the DB-run child recipe', async () => {
+ const parent = makeParent()
+ ;(parent.metadata as Record<string, unknown>).annotations = {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ }
+ const customApi = {
+ getNamespacedCustomObject: vi.fn().mockResolvedValue(parent),
+ createNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: { name: 'demo-parent-00000000' },
+ }),
+ } as unknown as k8s.CustomObjectsApi
+
+ await createDbRunChildRecipe(customApi, makeRun())
+
+ expect(
+ (customApi.createNamespacedCustomObject as unknown as ReturnType<typeof vi.fn>).mock
+ .calls[0]?.[0]?.body?.metadata?.annotations?.['clerum.io/codex-connection-ref']
+ ).toBe('team-plus')
+ })
+
+ it('does not invent a Codex grant annotation when the parent has none', async () => {
+ const customApi = {
+ getNamespacedCustomObject: vi.fn().mockResolvedValue(makeParent()),
+ createNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: { name: 'demo-parent-00000000' },
+ }),
+ } as unknown as k8s.CustomObjectsApi
+
+ await createDbRunChildRecipe(customApi, makeRun())
+
+ expect(
+ (customApi.createNamespacedCustomObject as unknown as ReturnType<typeof vi.fn>).mock
+ .calls[0]?.[0]?.body?.metadata?.annotations?.['clerum.io/codex-connection-ref']
+ ).toBeUndefined()
+ })
+
it('retains the exact parent GFS intent on a DB-run child recipe', async () => {
const gfs: WorkflowRecipeGfsIntentSpec = {
publishTargets: [{ drive: 'main', target: 'published-results' }],
diff --git a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts
index 619c89bba..6b3d1eabb 100644
--- a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts
+++ b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts
@@ -10,6 +10,7 @@ import {
buildChildRecipe,
buildDbRunChildName,
} from './childRecipeFactory.js'
+import { CODEX_CONNECTION_REF_ANNOTATION } from './llmAllowedModelsSnapshot.js'
import { WORKFLOW_TEAM_ID_LABEL } from './schedulingHandler.js'
export const RUN_ID_LABEL = 'clerum.io/workflow-run-id'
@@ -169,6 +170,16 @@ export async function createDbRunChildRecipe(
[RUN_INTERMEDIATE_PARAMS_ANNOTATION]: JSON.stringify(run.intermediate_parameters),
}
: {}),
+ // The Codex grant identity is inherited by copy: the trusted controller
+ // stamps the parent's chosen connection key on the child so control-api
+ // can attest the grant by reading the child recipe named in hostRef.
+ // A parent without the annotation stays fail-closed (`unassigned`).
+ ...(response.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]?.trim()
+ ? {
+ [CODEX_CONNECTION_REF_ANNOTATION]:
+ response.metadata.annotations[CODEX_CONNECTION_REF_ANNOTATION].trim(),
+ }
+ : {}),
},
})
// Match the JSON representation persisted by Kubernetes: buildChildRecipe
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
index f3c7c3c03..18ab162e3 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
-import { parseAllowedModelsSnapshot } from './llmAllowedModelsSnapshot'
+import {
+ CODEX_CONNECTION_REF_ANNOTATION,
+ parseAllowedModelsSnapshot,
+ readRecipeCodexConnectionRef,
+} from './llmAllowedModelsSnapshot'
function multiGrantConfigMap() {
return {
@@ -67,3 +71,23 @@ describe('WRC parseAllowedModelsSnapshot per assigned connection', () => {
)
})
})
+
+describe('readRecipeCodexConnectionRef', () => {
+ it('reads the explicit annotation and trims whitespace', () => {
+ expect(
+ readRecipeCodexConnectionRef({ [CODEX_CONNECTION_REF_ANNOTATION]: ' personal-pro ' })
+ ).toBe('personal-pro')
+ })
+
+ it('resolves missing/empty annotations to the fail-closed unassigned sentinel', () => {
+ expect(readRecipeCodexConnectionRef(undefined)).toBe('unassigned')
+ expect(readRecipeCodexConnectionRef({})).toBe('unassigned')
+ expect(readRecipeCodexConnectionRef({ [CODEX_CONNECTION_REF_ANNOTATION]: ' ' })).toBe(
+ 'unassigned'
+ )
+ })
+
+ it('never aliases the reserved deployment-default grant for a missing annotation', () => {
+ expect(readRecipeCodexConnectionRef({})).not.toBe('deployment-default')
+ })
+})
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
index dad4fb2cc..7fc773ade 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
@@ -8,8 +8,31 @@ export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'
export const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'
export const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'
export const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
+/**
+ * WorkflowRecipe metadata annotation naming the Codex grant (connection key)
+ * the recipe executes against. Recipes have no Host `spec.model.connectionRef`
+ * field by design: grants are created in Secrets and a recipe only *chooses*
+ * an existing grant through this annotation. HCC (Hosts), WRC (recipes), the
+ * control-api authorizer, and mcp-host must agree on the same key.
+ */
+export const CODEX_CONNECTION_REF_ANNOTATION = 'clerum.io/codex-connection-ref'
+/** Fail-closed sentinel. Not a grant row; never aliases deployment-default. */
+export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned'
export const ALLOWLIST_CONFIGMAP_NAMESPACE = process.env.CLERUM_MODEL_CONFIG_NAMESPACE ?? 'mcp-host'
+/**
+ * Recipe annotation reader. Empty/missing is `unassigned`, never the reserved
+ * grant: only an explicit annotation may spend a ChatGPT subscription.
+ */
+export function readRecipeCodexConnectionRef(
+ annotations: Record<string, string> | undefined
+): string {
+ const raw = annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
+ const trimmed = typeof raw === 'string' ? raw.trim() : ''
+ if (!trimmed) return CODEX_UNASSIGNED_CONNECTION_KEY
+ return trimmed
+}
+
export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot {
return { flagEnabled: false, snapshotError: error }
}
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index a8f1e222d..5cf89791e 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -59,6 +59,7 @@ import { JwtTokenFactory } from './jwtTokenFactory'
import {
ALLOWED_MODELS_CONFIGMAP_NAME,
ALLOWLIST_CONFIGMAP_NAMESPACE,
+ CODEX_UNASSIGNED_CONNECTION_KEY,
parseAllowedModelsSnapshot,
snapshotFromConfigMapError,
} from './llmAllowedModelsSnapshot'
@@ -356,6 +357,13 @@ export type CodexReconcileContext = {
runtimeScopeRecipeName: string
claimedParent: boolean
parentSpec: WorkflowRecipeSpec | null
+ /**
+ * Grant (connection key) the recipe is bound to via the
+ * `clerum.io/codex-connection-ref` annotation on the authoritative recipe
+ * (the runtime-scope parent when inherited). Missing/empty binds the
+ * fail-closed `unassigned` sentinel, never the reserved grant.
+ */
+ connectionKey?: string
}
function orderedScopesEqual<T extends string>(actual: T[], expected: T[]): boolean {
@@ -878,6 +886,13 @@ export class WorkflowReconciler {
private readonly log = createLogger('wrc', 'reconciler')
private readonly pluginWorkloadSdkProvisioner: PluginWorkloadSdkProvisioner
private codexSnapshot: CodexCatalogSnapshot = { flagEnabled: false }
+ /**
+ * Raw allowlist ConfigMap from the last refresh, kept so each recipe's
+ * projection can re-parse it with that recipe's assigned grant key (HCC
+ * keeps the same shape for Hosts). Undefined while the read is failing —
+ * `codexSnapshot` then carries the fail-closed snapshot error.
+ */
+ private lastCodexConfigMap: k8s.V1ConfigMap | undefined
private codexContext: CodexReconcileContext | null = null
constructor(private readonly deps: WorkflowReconcilerDeps) {
@@ -943,7 +958,22 @@ export class WorkflowReconciler {
ownSpec: spec,
parentSpec: context.parentSpec,
})
- return projectRecipeCodexExecution(resolved.spec, this.codexSnapshot, resolved.provenance)
+ return projectRecipeCodexExecution(
+ resolved.spec,
+ this.codexSnapshotFor(context.connectionKey ?? CODEX_UNASSIGNED_CONNECTION_KEY),
+ resolved.provenance
+ )
+ }
+
+ /**
+ * Per-recipe snapshot: re-parse the last allowlist ConfigMap with the
+ * recipe's assigned grant key. A multi-grant map fail-closes for a missing
+ * key (including the `unassigned` sentinel); a legacy flat ConfigMap keeps
+ * the flat catalog. Read failures keep the fail-closed error snapshot.
+ */
+ private codexSnapshotFor(connectionKey: string): CodexCatalogSnapshot {
+ if (!this.lastCodexConfigMap) return this.codexSnapshot
+ return parseAllowedModelsSnapshot(this.lastCodexConfigMap, connectionKey)
}
private resolveEffectiveControlScopes(
@@ -968,8 +998,10 @@ export class WorkflowReconciler {
name: ALLOWED_MODELS_CONFIGMAP_NAME,
namespace: ALLOWLIST_CONFIGMAP_NAMESPACE,
})
+ this.lastCodexConfigMap = cm
this.codexSnapshot = parseAllowedModelsSnapshot(cm)
} catch (err) {
+ this.lastCodexConfigMap = undefined
if (isCodexSnapshotTimeout(err)) {
this.codexSnapshot = snapshotFromConfigMapError('timeout')
this.log.warn('Codex allowlist ConfigMap read timed out; failing closed', {