Skip to content

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

TypeScript

fix(codex): close CodeQL alerts and remaining grant-path review gaps

Alfredo Lopezb73999f70225
diff --git a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
index fe1747533..3fcdc4e64 100644
--- a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
+++ b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
@@ -20,7 +20,8 @@
* 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 { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { request as httpsRequest } from 'node:https'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -193,32 +194,81 @@ function makeControlApiMock(): {
* 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.
+ * would do for a test upstream. TLS is verified against the run-generated
+ * CA (SAN IP:127.0.0.1); certificate validation is never disabled.
*/
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)
+ return trustedLoopbackFetch(target, init)
}
async function upstreamCounters(): Promise<Record<string, number>> {
- const res = await fetch(`${UPSTREAM_BASE}/internal/counters`)
+ const res = await trustedLoopbackFetch(`${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
+let fixtureCa: Buffer | undefined
+
+function trustedLoopbackFetch(url: string | URL, init?: RequestInit): Promise<Response> {
+ if (!fixtureCa) {
+ return Promise.reject(new Error('fixture CA is not ready'))
+ }
+ const target = new URL(String(url))
+ const headers: Record<string, string> = {}
+ if (init?.headers) {
+ new Headers(init.headers).forEach((value, key) => {
+ headers[key] = value
+ })
+ }
+ return new Promise((resolve, reject) => {
+ const req = httpsRequest(
+ {
+ hostname: target.hostname,
+ port: target.port,
+ path: `${target.pathname}${target.search}`,
+ method: init?.method ?? 'GET',
+ headers,
+ ca: fixtureCa,
+ rejectUnauthorized: true,
+ },
+ res => {
+ const chunks: Buffer[] = []
+ res.on('data', chunk => chunks.push(chunk as Buffer))
+ res.on('end', () => {
+ const headerBag = new Headers()
+ for (const [key, value] of Object.entries(res.headers)) {
+ if (typeof value === 'string') headerBag.set(key, value)
+ else if (Array.isArray(value)) headerBag.set(key, value.join(', '))
+ }
+ resolve(
+ new Response(Buffer.concat(chunks), {
+ status: res.statusCode ?? 500,
+ headers: headerBag,
+ })
+ )
+ })
+ }
+ )
+ req.on('error', reject)
+ const body = init?.body
+ if (body == null) {
+ req.end()
+ return
+ }
+ if (typeof body === 'string' || body instanceof Uint8Array || Buffer.isBuffer(body)) {
+ req.end(body)
+ return
+ }
+ reject(new Error('unsupported request body in hermetic fixture fetch'))
+ })
+}
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')
@@ -237,10 +287,13 @@ beforeAll(async () => {
'-out',
certPath,
'-subj',
- '/CN=codex-test-upstream.local',
+ '/CN=127.0.0.1',
+ '-addext',
+ 'subjectAltName=IP:127.0.0.1',
],
{ stdio: 'ignore' }
)
+ fixtureCa = readFileSync(certPath)
upstream = spawn(process.execPath, [FIXTURE_UPSTREAM], {
env: {
...process.env,
@@ -269,11 +322,6 @@ 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', () => {
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index a92642f23..fa2a61081 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.509",
+ "version": "0.1.510",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.509",
+ "version": "0.1.510",
"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 03dd33ed8..2dcc55800 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.509",
+ "version": "0.1.510",
"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 7265f5de6..8c52f74fe 100644
--- a/control-api/src/routes/admin/codexSubscription.ts
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -30,6 +30,7 @@ import {
import {
type CodexOAuthDeps,
CodexSubscriptionOAuthError,
+ ensureFreshCodexAccessToken,
getCodexSubscriptionConnection,
pollCodexDevice,
refreshCodexSubscriptionConnection,
@@ -438,6 +439,9 @@ export function createAdminCodexSubscriptionRouter(
}
const db = dbClient()
const connectionKey = keyFromReq(req)
+ await ensureFreshCodexAccessToken(
+ oauthDeps(req, resolveBrowserRedirectUri(req), connectionKey)
+ )
const secrets = await loadCodexSubscriptionSecrets(
db,
deriveOAuthEncryptionKey(config.oauthEncryptionKey),
diff --git a/control-api/src/routes/admin/index.ts b/control-api/src/routes/admin/index.ts
index d9ce14cc4..445e10caa 100644
--- a/control-api/src/routes/admin/index.ts
+++ b/control-api/src/routes/admin/index.ts
@@ -44,7 +44,7 @@ export function createAdminRouter(gateway: K8sGateway): Router {
router.use(createAdminContextRouter())
router.use(createAdminAgentsRouter())
router.use(createAdminPersonalizationRouter(gateway))
- router.use(createAdminPluginWorkloadSdkRouter())
+ router.use(createAdminPluginWorkloadSdkRouter({ gateway }))
router.use(createAdminUsageRouter())
router.use(createAdminLlmPricesRouter())
router.use(createAdminLlmModelsRouter(gateway))
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index 51853fa3e..c57c74db8 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -11,10 +11,13 @@ import {
withTransaction,
} from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
+import type { K8sGateway } from '../../k8s.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import { createPluginWorkloadSdkAdminRateLimit } from '../../middleware/pluginWorkloadSdkRateLimits.js'
+import { rootLogger } from '../../observability/logger.js'
import { isCodexAssignmentAllowed } from '../../services/codexSubscriptionCatalog.js'
import {
+ CODEX_CONNECTION_REF_ANNOTATION,
assertCodexConnectionKey,
isCodexUnassignedConnectionKey,
} from '../../services/codexSubscriptionConnection.js'
@@ -327,6 +330,15 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
...(brokerBacked ? { connectionRef } : {}),
})
}
+ const brokerKeys = new Set(
+ targets
+ .filter(target => isBrokerBackedProvider(target.provider))
+ .map(target => target.connectionRef ?? '')
+ )
+ if (brokerKeys.size > 1) {
+ res.status(400).json({ error: 'codex_connection_ref_conflict' })
+ return null
+ }
return targets
}
@@ -350,8 +362,16 @@ export interface AdminPluginWorkloadSdkRouterDeps {
* guarantee is testable through the seam; defaults to the shared emitter.
*/
emitIncoherenceTolerated?: EmitHostSpecIncoherenceTolerated
+ /**
+ * Stamps `clerum.io/codex-connection-ref` on the WorkflowRecipe after a
+ * Codex promptBridge upsert. Authorize attests that annotation, not the
+ * Postgres grant row, so a successful choose must persist it.
+ */
+ gateway?: Pick<K8sGateway, 'patchResourceAnnotations'>
}
+const log = rootLogger.child({ module: 'admin-plugin-workload-sdk' })
+
export function createAdminPluginWorkloadSdkRouter(
deps: AdminPluginWorkloadSdkRouterDeps = {}
): Router {
@@ -739,6 +759,26 @@ export function createAdminPluginWorkloadSdkRouter(
// Grant PERSISTED: NOW emit any Pieza D tolerations (never before the upsert
// lands, so a failed upsert leaves no audit record — mini-spec 01).
for (const event of pendingGrantTolerations) emitIncoherenceTolerated(event)
+ const brokerConnectionRef = promptTargets.find(target =>
+ isBrokerBackedProvider(target.provider)
+ )?.connectionRef
+ if (capabilityFamily === 'promptBridge' && brokerConnectionRef && deps.gateway) {
+ try {
+ await deps.gateway.patchResourceAnnotations(
+ 'workflowrecipes',
+ recipeName,
+ { [CODEX_CONNECTION_REF_ANNOTATION]: brokerConnectionRef },
+ recipeNamespace
+ )
+ } catch (err) {
+ log.error(
+ { err, recipeNamespace, recipeName },
+ 'failed to stamp Codex connection annotation on WorkflowRecipe'
+ )
+ res.status(503).json({ error: 'recipe_annotation_stamp_failed' })
+ return
+ }
+ }
// Fase 6: attach any soft-quarantine warnings additively (older clients
// ignore the field). Absent when there is nothing to warn about.
res
diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
index 67bdcda32..d8989d246 100644
--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
@@ -12,6 +12,7 @@ import {
LlmProviderAttemptAuthorizeError,
authorizeLlmProviderAttempt,
} from '../../services/llmProviderAttemptAuthorizer.js'
+import { listGrants } from '../../services/pluginWorkloadSdkDb.js'
import { llmProviderAttemptAuthorizeRateLimits } from '../workflows/shared/rateLimit.js'
const log = rootLogger.child({ module: 'mcp-host-llm-provider-attempts' })
@@ -44,7 +45,10 @@ function sendAuthorizeError(res: Response, err: unknown): void {
export async function resolveHostAssignedConnectionKey(
gateway: Pick<K8sGateway, 'getResource'>,
- hostRef: string
+ hostRef: string,
+ opts?: {
+ listSdkCodexConnectionRefs?: (namespace: string, recipeName: string) => Promise<string[]>
+ }
): Promise<string> {
if (hostRef.includes('/')) {
// Workflow callers attest as `namespace/recipeName`. The grant identity is
@@ -64,10 +68,27 @@ export async function resolveHostAssignedConnectionKey(
recipeName,
recipeNamespace
)) as { metadata?: { annotations?: Record<string, string> } }
- return readHostCodexConnectionRef(
+ const annotated = readHostCodexConnectionRef(
recipe?.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
)
- } catch {
+ if (opts?.listSdkCodexConnectionRefs) {
+ const grantRefs = [
+ ...new Set(
+ (await opts.listSdkCodexConnectionRefs(recipeNamespace, recipeName))
+ .map(ref => ref.trim())
+ .filter(Boolean)
+ ),
+ ]
+ if (grantRefs.length > 1 || (grantRefs.length === 1 && grantRefs[0] !== annotated)) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'host_binding_mismatch',
+ 'SDK grant connectionRef does not match the recipe annotation'
+ )
+ }
+ }
+ return annotated
+ } catch (err) {
+ if (err instanceof LlmProviderAttemptAuthorizeError) throw err
throw new LlmProviderAttemptAuthorizeError(
'host_binding_mismatch',
'Recipe assignment could not be attested'
@@ -101,7 +122,17 @@ export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Rout
}
try {
const result = await authorizeLlmProviderAttempt(claims, req.body, {
- resolveConnectionKey: hostRef => resolveHostAssignedConnectionKey(gateway, hostRef),
+ resolveConnectionKey: hostRef =>
+ resolveHostAssignedConnectionKey(gateway, hostRef, {
+ listSdkCodexConnectionRefs: async (namespace, recipeName) => {
+ const grants = await listGrants({ recipeNamespace: namespace, recipeName })
+ return grants.flatMap(grant =>
+ grant.promptTargets
+ .map(target => target.connectionRef)
+ .filter((ref): ref is string => typeof ref === 'string' && ref.length > 0)
+ )
+ },
+ }),
})
res.status(200).json(result)
} catch (err) {
diff --git a/control-api/src/services/llmProviderAttemptRedemption.ts b/control-api/src/services/llmProviderAttemptRedemption.ts
index 1aa457d7d..c23b8fa21 100644
--- a/control-api/src/services/llmProviderAttemptRedemption.ts
+++ b/control-api/src/services/llmProviderAttemptRedemption.ts
@@ -5,7 +5,6 @@ import { deriveOAuthEncryptionKey } from '../oauth/encryption.js'
import { rootLogger } from '../observability/logger.js'
import { chatgptAccountIdFromJwt } from './chatgptAccountId.js'
import {
- getSafeCodexSubscriptionConnection,
getSafeCodexSubscriptionConnectionById,
loadCodexSubscriptionSecrets,
} from './codexSubscriptionConnection.js'
@@ -194,9 +193,13 @@ export async function redeemLlmProviderAttempt(
)
}
- const connection = attempt.connectionId
- ? await getSafeCodexSubscriptionConnectionById(tx, attempt.connectionId)
- : await getSafeCodexSubscriptionConnection(tx)
+ if (!attempt.connectionId) {
+ throw new LlmProviderAttemptRedeemError(
+ 'connection_unavailable',
+ 'Codex attempt is missing a connection binding'
+ )
+ }
+ const connection = await getSafeCodexSubscriptionConnectionById(tx, attempt.connectionId)
if (
!connection ||
connection.status !== 'connected' ||
diff --git a/control-api/src/services/llmProviderAttemptTicket.ts b/control-api/src/services/llmProviderAttemptTicket.ts
index 884161525..cce22e6e1 100644
--- a/control-api/src/services/llmProviderAttemptTicket.ts
+++ b/control-api/src/services/llmProviderAttemptTicket.ts
@@ -85,7 +85,8 @@ export function verifyCodexExecutionTicket(ticket: string): CodexExecutionTicket
typeof claims.model !== 'string' ||
typeof claims.requestHash !== 'string' ||
typeof claims.policyHash !== 'string' ||
- typeof claims.budgetReservationId !== 'string'
+ typeof claims.budgetReservationId !== 'string' ||
+ typeof claims.exp !== 'number'
) {
return null
}
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index 8ef228a86..50140229f 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -188,9 +188,10 @@ export interface PluginWorkloadSdkPromptTarget {
/**
* 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.
+ * grant is only *chosen* here — it must already exist and be connected.
+ * Control-api stamps the matching `clerum.io/codex-connection-ref`
+ * annotation; authorize attests that annotation and fail-closes if this
+ * field disagrees.
*/
connectionRef?: string
}
diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.ts
index 90898cde4..aab62a0d2 100644
--- a/control-api/test/routes.admin.codexSubscription.test.ts
+++ b/control-api/test/routes.admin.codexSubscription.test.ts
@@ -11,6 +11,7 @@ const oauth = vi.hoisted(() => ({
pollDevice: vi.fn(),
refresh: vi.fn(),
revoke: vi.fn(),
+ ensureFresh: vi.fn(),
}))
const catalog = vi.hoisted(() => ({
@@ -29,6 +30,7 @@ vi.mock('../src/services/codexSubscriptionOAuth.js', async () => {
pollCodexDevice: oauth.pollDevice,
refreshCodexSubscriptionConnection: oauth.refresh,
revokeCodexSubscription: oauth.revoke,
+ ensureFreshCodexAccessToken: oauth.ensureFresh,
}
})
@@ -143,6 +145,7 @@ describe('admin Codex subscription routes', () => {
catalog.sync.mockReset()
catalog.listOffered.mockReset()
catalog.listOffered.mockResolvedValue(['gpt-5.1'])
+ oauth.ensureFresh.mockResolvedValue(undefined)
vi.mocked(pool.query).mockReset()
})
@@ -346,10 +349,26 @@ describe('admin Codex subscription routes', () => {
)
expect(res.status).toBe(200)
expect(res.body.added).toBe(8)
+ expect(oauth.ensureFresh).toHaveBeenCalledTimes(1)
expect(materialize).toHaveBeenCalledTimes(1)
assertNoLeak(res.body)
})
+ it('does not publish the runtime ConfigMap when catalog sync cannot refresh the access token', async () => {
+ const materialize = vi.fn(async () => {})
+ oauth.ensureFresh.mockRejectedValueOnce(
+ new CodexSubscriptionOAuthError('reauth_required', 'refresh token rejected')
+ )
+ const res = await request(makeAuthedApp(makeGateway(materialize))).post(
+ '/admin/llm/providers/codex-subscription/connections/codex-aaa/catalog/sync'
+ )
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('reauth_required')
+ expect(catalog.sync).not.toHaveBeenCalled()
+ expect(materialize).not.toHaveBeenCalled()
+ assertNoLeak(res.body)
+ })
+
it('returns 503 when catalog sync cannot publish the runtime ConfigMap', async () => {
const materialize = vi.fn(async () => {
throw new Error('apiserver down')
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index ddbc1f755..0a184c7dc 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -54,6 +54,8 @@ vi.mock('../src/services/codexSubscriptionCatalog.js', () => ({
const DEFAULT_ADMIN_SUB = '11111111-1111-4111-8111-111111111111'
+const patchResourceAnnotations = vi.fn().mockResolvedValue({})
+
function buildApp(sub: string | null = DEFAULT_ADMIN_SUB) {
const app = express()
app.use(express.json())
@@ -61,7 +63,7 @@ function buildApp(sub: string | null = DEFAULT_ADMIN_SUB) {
;(req as unknown as { adminAuth: { sub?: string } }).adminAuth = sub === null ? {} : { sub }
next()
})
- app.use(createAdminPluginWorkloadSdkRouter())
+ app.use(createAdminPluginWorkloadSdkRouter({ gateway: { patchResourceAnnotations } }))
return app
}
@@ -107,6 +109,8 @@ beforeEach(() => {
vi.mocked(pool.query).mockResolvedValue({ rows: [{ model: 'glm-4.7' }], rowCount: 1 } as never)
vi.mocked(isCodexAssignmentAllowed).mockReset()
vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(false)
+ patchResourceAnnotations.mockReset()
+ patchResourceAnnotations.mockResolvedValue({})
})
describe('routes/admin/pluginWorkloadSdk — grants', () => {
@@ -600,6 +604,45 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
'11111111-1111-4111-8111-111111111111',
expect.anything() // carrier transaction client (R1-H3 fase 2)
)
+ expect(patchResourceAnnotations).toHaveBeenCalledWith(
+ 'workflowrecipes',
+ 'sdk-recipe',
+ { 'clerum.io/codex-connection-ref': 'team-plus' },
+ 'sandbox-recipes'
+ )
+ })
+
+ it('returns 503 when the recipe annotation cannot be stamped after a Codex upsert', async () => {
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-codex' } as never)
+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(true)
+ patchResourceAnnotations.mockRejectedValueOnce(new Error('apiserver down'))
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send(codexGrantBody)
+ expect(res.status).toBe(503)
+ expect(res.body.error).toBe('recipe_annotation_stamp_failed')
+ })
+
+ it('rejects two Codex targets that name different grants', async () => {
+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(true)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...codexGrantBody,
+ promptTargets: [
+ codexGrantBody.promptTargets[0],
+ {
+ targetRef: 'codex-fallback',
+ provider: 'codex-subscription',
+ model: 'gpt-5.4',
+ credentialSlot: '',
+ connectionRef: 'team-other',
+ },
+ ],
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('codex_connection_ref_conflict')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
})
it('fails closed when the connection is unknown, revoked, or does not offer the model', async () => {
diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
index e6c67b394..b350be05f 100644
--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
@@ -230,4 +230,41 @@ describe('resolveHostAssignedConnectionKey', () => {
code: 'host_binding_mismatch',
})
})
+
+ it('fails closed when the SDK grant connectionRef disagrees with the recipe annotation', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({
+ metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },
+ }),
+ }
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {
+ listSdkCodexConnectionRefs: async () => ['team-other'],
+ })
+ ).rejects.toMatchObject({ code: 'host_binding_mismatch' })
+ })
+
+ it('fails closed when the recipe annotation is unassigned but the SDK grant chose a key', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({ metadata: { annotations: {} } }),
+ }
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {
+ listSdkCodexConnectionRefs: async () => ['team-plus'],
+ })
+ ).rejects.toMatchObject({ code: 'host_binding_mismatch' })
+ })
+
+ it('accepts a recipe whose SDK grant matches the stamped annotation', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({
+ metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },
+ }),
+ }
+ await expect(
+ resolveHostAssignedConnectionKey(gateway, 'sandbox-recipes/codex-recipe', {
+ listSdkCodexConnectionRefs: async () => ['team-plus'],
+ })
+ ).resolves.toBe('team-plus')
+ })
})
diff --git a/control-api/test/services.llmProviderAttemptRedemption.test.ts b/control-api/test/services.llmProviderAttemptRedemption.test.ts
index dbe698e68..4005544d6 100644
--- a/control-api/test/services.llmProviderAttemptRedemption.test.ts
+++ b/control-api/test/services.llmProviderAttemptRedemption.test.ts
@@ -32,6 +32,26 @@ const CLAIMS = {
connectionRevision: 3,
}
+const CONNECTION_ID = '11111111-1111-1111-1111-111111111111'
+const SAFE_CONNECTION = {
+ id: CONNECTION_ID,
+ connectionKey: 'team-plus',
+ displayName: 'Team Plus',
+ createdBy: null,
+ status: 'connected' as const,
+ credentialRevision: 3,
+ catalogRevision: 4,
+ accountFingerprint: 'fp',
+ catalogStatus: 'ready' as const,
+ catalogSyncedAt: new Date(),
+ lastRefreshAt: null,
+ lastAuthAt: new Date(),
+ refreshLockHeld: false,
+ revokedAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+}
+
describe('redeemLlmProviderAttempt', () => {
beforeEach(() => {
config.codexSubscriptionEnabled = true
@@ -59,30 +79,16 @@ describe('redeemLlmProviderAttempt', () => {
policyHash: CLAIMS.policyHash,
budgetReservationId: CLAIMS.budgetReservationId,
connectionRevision: CLAIMS.connectionRevision,
- connectionId: null,
+ connectionId: CONNECTION_ID,
status: 'authorized',
outcome: null,
createdAt: new Date(),
})
vi.spyOn(store, 'markLlmProviderAttemptTicketRedeemed').mockResolvedValue(true)
- vi.spyOn(connection, 'getSafeCodexSubscriptionConnection').mockResolvedValue({
- id: '11111111-1111-1111-1111-111111111111',
- connectionKey: 'deployment-default',
- displayName: 'Default deployment',
- createdBy: null,
- status: 'connected',
- credentialRevision: 3,
- catalogRevision: 4,
- accountFingerprint: 'fp',
- catalogStatus: 'ready',
- catalogSyncedAt: new Date(),
- lastRefreshAt: null,
- lastAuthAt: new Date(),
- refreshLockHeld: false,
- revokedAt: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- })
+ vi.spyOn(connection, 'getSafeCodexSubscriptionConnectionById').mockResolvedValue(
+ SAFE_CONNECTION
+ )
+ vi.spyOn(connection, 'getSafeCodexSubscriptionConnection').mockResolvedValue(SAFE_CONNECTION)
})
it('returns only the usable access token and frozen transport metadata', async () => {
@@ -144,23 +150,11 @@ describe('redeemLlmProviderAttempt', () => {
})
it('refuses to redeem a pre-revoke ticket after the grant is revoked', async () => {
- vi.mocked(connection.getSafeCodexSubscriptionConnection).mockResolvedValueOnce({
- id: '11111111-1111-1111-1111-111111111111',
- connectionKey: 'team-plus',
- displayName: 'Team Plus',
- createdBy: null,
+ vi.mocked(connection.getSafeCodexSubscriptionConnectionById).mockResolvedValueOnce({
+ ...SAFE_CONNECTION,
status: 'revoked',
credentialRevision: 4,
- catalogRevision: 4,
- accountFingerprint: null,
- catalogStatus: 'ready',
- catalogSyncedAt: new Date(),
- lastRefreshAt: null,
- lastAuthAt: new Date(),
- refreshLockHeld: false,
revokedAt: new Date(),
- createdAt: new Date(),
- updatedAt: new Date(),
})
await expect(
redeemLlmProviderAttempt(
@@ -179,6 +173,46 @@ describe('redeemLlmProviderAttempt', () => {
).rejects.toMatchObject({ code: 'connection_unavailable' })
})
+ it('refuses to fall back to the reserved grant when the attempt has no connectionId', async () => {
+ vi.mocked(store.loadLlmProviderAttempt).mockResolvedValueOnce({
+ id: CLAIMS.providerAttemptId,
+ callerKind: 'host',
+ hostRef: CLAIMS.hostRef,
+ recipeNamespace: null,
+ recipeName: null,
+ invocationId: CLAIMS.invocationId,
+ attemptGeneration: CLAIMS.attemptGeneration,
+ providerAttemptIndex: 1,
+ provider: 'codex-subscription',
+ model: CLAIMS.model,
+ requestHash: CLAIMS.requestHash,
+ policyRevision: CLAIMS.policyRevision,
+ policyHash: CLAIMS.policyHash,
+ budgetReservationId: CLAIMS.budgetReservationId,
+ connectionRevision: CLAIMS.connectionRevision,
+ connectionId: null,
+ status: 'authorized',
+ outcome: null,
+ createdAt: new Date(),
+ })
+ await expect(
+ 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 without a connection binding')
+ },
+ encryptionKey: Buffer.alloc(32),
+ }
+ )
+ ).rejects.toMatchObject({ code: 'connection_unavailable' })
+ expect(connection.getSafeCodexSubscriptionConnection).not.toHaveBeenCalled()
+ })
+
it('is disabled when the flag is off', async () => {
await expect(
redeemLlmProviderAttempt(
diff --git a/control-api/test/services.llmProviderAttemptTicket.test.ts b/control-api/test/services.llmProviderAttemptTicket.test.ts
index 2f95b6a34..6efa314f0 100644
--- a/control-api/test/services.llmProviderAttemptTicket.test.ts
+++ b/control-api/test/services.llmProviderAttemptTicket.test.ts
@@ -114,4 +114,24 @@ describe('Codex execution ticket', () => {
)
expect(hash).not.toContain('prompt')
})
+
+ it('rejects a ticket that is missing a numeric exp claim', async () => {
+ const token = jwt.sign(
+ {
+ ...binding,
+ jti: randomUUID(),
+ typ: 'codex-execution-ticket',
+ provider: 'codex-subscription',
+ },
+ config.adminJwtPrivateKey,
+ {
+ algorithm: 'RS256',
+ issuer: config.adminJwtIssuer,
+ audience: CODEX_EXECUTION_TICKET_AUDIENCE,
+ }
+ )
+ expect(typeof jwt.decode(token)).toBe('object')
+ expect((jwt.decode(token) as jwt.JwtPayload).exp).toBeUndefined()
+ expect(verifyCodexExecutionTicket(token)).toBeNull()
+ })
})
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsx
index b361f9022..1680d5e8c 100644
--- a/control-ui/app/hosts/[name]/page.tsx
+++ b/control-ui/app/hosts/[name]/page.tsx
@@ -31,6 +31,7 @@ import type { ContextResource, ContextSpec, HostSecretResource } from '../../../
import {
CODEX_UNASSIGNED_CONNECTION_KEY,
type CodexSubscriptionConnectionView,
+ isAssignableCodexGrant,
listCodexConnectionModels,
listCodexSubscriptionConnections,
} from '../../../lib/codexSubscription'
@@ -681,7 +682,7 @@ export default function HostDetailsPage() {
if (secretRefDraft.trim() && !options.some(secret => secret.value === secretRefDraft.trim())) {
options.unshift(toOption(secretRefDraft.trim(), currentSecretKeys))
}
- for (const row of codexConnections.filter(item => item.status !== 'revoked')) {
+ for (const row of codexConnections.filter(isAssignableCodexGrant)) {
options.push({
group: 'ChatGPT subscriptions',
value: credentialSelectValue('', row.connectionKey),
@@ -694,7 +695,7 @@ export default function HostDetailsPage() {
connectionRefDraft &&
connectionRefDraft !== CODEX_UNASSIGNED_CONNECTION_KEY &&
!codexConnections.some(
- row => row.connectionKey === connectionRefDraft && row.status !== 'revoked'
+ row => row.connectionKey === connectionRefDraft && isAssignableCodexGrant(row)
)
) {
options.push({
@@ -804,52 +805,6 @@ export default function HostDetailsPage() {
}
}
- async function saveSecretRef(nextSecretRef: string): Promise<void> {
- const normalizedSecretRef = nextSecretRef.trim()
- if (!normalizedSecretRef) throw new Error('Select an LLM Secret.')
-
- setBusy(true)
- setError('')
- try {
- const currentHost = await getHost(routeName)
- const nextSpec = {
- ...currentHost.spec,
- secretRef: normalizedSecretRef,
- }
- const formResourceVersion = formResourceVersionRef.current
- await apiSend('PUT', `/api/v1/admin/hosts/${encodeURIComponent(routeName)}`, {
- ...(formResourceVersion ? { metadata: { resourceVersion: formResourceVersion } } : {}),
- spec: nextSpec,
- })
- setSecretRefDraft(normalizedSecretRef)
- await loadData('none')
- showToast('LLM Secret link updated.', { tone: 'success' })
- } catch (e) {
- const status = (e as { status?: number } | null)?.status
- const code = (e as { code?: string } | null)?.code
- const message =
- status === 409 && code === 'conflict'
- ? 'This agent changed since you opened the form. Reload to see the latest, then re-apply your change.'
- : e instanceof Error
- ? e.message
- : 'Failed to change the linked LLM Secret'
- setError(message)
- throw new Error(message)
- } finally {
- setBusy(false)
- }
- }
-
- async function handleSecretRefChange(nextSecretRef: string): Promise<void> {
- if (nextSecretRef === secretRefDraft) return
- try {
- await saveSecretRef(nextSecretRef)
- } catch {
- // saveSecretRef surfaces the server error in the page banner. Keep the
- // controlled select on the previously saved value when the write fails.
- }
- }
-
function handleCredentialChange(value: string) {
const parsed = parseCredentialSelect(value)
if (parsed.kind === 'empty') {
@@ -1158,7 +1113,7 @@ export default function HostDetailsPage() {
onSaveDisplayName={nextDisplayName => saveHost(nextDisplayName)}
onSaveLifecycle={nextStateless => {
setStatelessDraft(nextStateless)
- return saveHost(hostDisplayDraft, nextStateless)
+ return saveHost(hostDisplaySaved, nextStateless)
}}
createdAt={hostCreatedAt}
/>
@@ -1196,13 +1151,7 @@ export default function HostDetailsPage() {
id="model-secret"
value={credentialSelectValue(secretRefDraft, connectionRefDraft)}
ariaLabel={credentialFieldLabel}
- onChange={value => {
- if (!editingModel && parseCredentialSelect(value).kind === 'secret') {
- void handleSecretRefChange(value)
- return
- }
- handleCredentialChange(value)
- }}
+ onChange={handleCredentialChange}
options={llmSecretOptions}
placeholder={
isCodexAssignment
@@ -1215,7 +1164,7 @@ export default function HostDetailsPage() {
? 'No LLM Secret available'
: 'Select an LLM Secret...'
}
- disabled={busy}
+ disabled={busy || !editingModel}
/>
<button
type="button"
diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsx
index a08beff35..43f18516e 100644
--- a/control-ui/app/plugin-workload-sdk/page.tsx
+++ b/control-ui/app/plugin-workload-sdk/page.tsx
@@ -1,7 +1,6 @@
'use client'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { useRouter } from 'next/navigation'
import { useConfirmDialog } from '@components/ConfirmDialog'
import { DashboardLayout } from '@components/DashboardLayout'
import { SectionSearchInput } from '@components/SectionSearchInput'
@@ -32,6 +31,7 @@ import {
} from '@lib/api'
import {
type CodexSubscriptionConnectionView,
+ isAssignableCodexGrant,
listCodexConnectionModels,
listCodexSubscriptionConnections,
} from '@lib/codexSubscription'
@@ -125,7 +125,6 @@ async function fetchUsersByRefs(userRefs: string[]): Promise<AdminUser[]> {
}
export default function PluginWorkloadSdkPage() {
- const router = useRouter()
const { confirm, confirmDialog } = useConfirmDialog()
const { showToast } = useToast()
const [view, setView] = useState<SdkView>('grants')
@@ -536,11 +535,7 @@ function GrantFormModal({
listCodexSubscriptionConnections()
.then(connections => {
if (cancelled) return
- setCodexConnections(
- connections.filter(
- connection => connection.status === 'connected' && connection.catalogStatus === 'ready'
- )
- )
+ setCodexConnections(connections.filter(isAssignableCodexGrant))
})
.catch(() => {
// Fail closed: without a readable connection list no Codex target can
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsx
index b5abe173d..c068e014c 100644
--- a/control-ui/components/HostWizard/index.tsx
+++ b/control-ui/components/HostWizard/index.tsx
@@ -21,6 +21,7 @@ import { cn } from '@/lib/cn'
import {
CODEX_UNASSIGNED_CONNECTION_KEY,
type CodexSubscriptionConnectionView,
+ isAssignableCodexGrant,
listCodexConnectionModels,
listCodexSubscriptionConnections,
} from '@/lib/codexSubscription'
@@ -328,15 +329,13 @@ export function HostWizard({
})
.filter(option => option !== null)
.sort((left, right) => left.value.localeCompare(right.value)),
- ...codexConnections
- .filter(row => row.status !== 'revoked')
- .map(row => ({
- group: 'ChatGPT subscriptions',
- value: credentialSelectValue('', row.connectionKey),
- label: row.displayName || row.connectionKey,
- meta: 'ChatGPT subscription',
- providers: [{ id: 'codex-subscription', label: 'ChatGPT' }],
- })),
+ ...codexConnections.filter(isAssignableCodexGrant).map(row => ({
+ group: 'ChatGPT subscriptions',
+ value: credentialSelectValue('', row.connectionKey),
+ label: row.displayName || row.connectionKey,
+ meta: 'ChatGPT subscription',
+ providers: [{ id: 'codex-subscription', label: 'ChatGPT' }],
+ })),
],
[codexConnections, existingSecrets]
)
diff --git a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx
index f0373f5ec..2a8f4d169 100644
--- a/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.conflict.test.tsx
@@ -559,18 +559,24 @@ describe('HostDetailsPage current model and credential flow', () => {
})
it('changes the linked LLM Secret from the inline credentials dropdown', async () => {
+ setupApiMocks(formLoadHost, refetchedHost, [
+ { name: 'openai-secret', keys: ['openai-api-key'] },
+ { name: 'openai-secret-b', keys: ['openai-api-key'] },
+ ])
const view = render(<HostDetailsPage />)
navigateToTab(view, 'model')
await screen.findByText('Current model')
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
fireEvent.click(screen.getByRole('button', { name: 'LLM Secret' }))
- fireEvent.click(screen.getByRole('option', { name: /anthropic-secret/ }))
+ fireEvent.click(screen.getByRole('option', { name: /openai-secret-b/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save model configuration' }))
await waitFor(() =>
expect(api.apiSend).toHaveBeenCalledWith('PUT', '/api/v1/admin/hosts/foo', expect.any(Object))
)
const payload = findHostPutPayload() as { spec: Record<string, unknown> }
- expect(payload.spec.secretRef).toBe('anthropic-secret')
+ expect(payload.spec.secretRef).toBe('openai-secret-b')
expect(payload.spec.model).toEqual(baseSpec.model)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
index 097eaf35d..b78050fa9 100644
--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
@@ -191,12 +191,14 @@ describe('HostDetailsPage identity integration', () => {
const picker = await screen.findByRole('button', { name: 'LLM Secret' })
expect(picker).toHaveTextContent('openai-secret')
+ expect(picker).toBeDisabled()
expect(picker.querySelectorAll('img')).toHaveLength(2)
expect(picker.querySelector('img')).toHaveAttribute('src', '/provider-icons/openai.svg')
expect(picker.querySelectorAll('img')[1]).toHaveAttribute('src', '/provider-icons/claude.svg')
expect(screen.queryByRole('combobox')).toBeNull()
- fireEvent.click(picker)
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
+ fireEvent.click(screen.getByRole('button', { name: 'LLM Secret' }))
const zaiOption = screen.getByRole('option', { name: /zai-secret/ })
expect(zaiOption).toHaveTextContent('Providers: Z.AI')
diff --git a/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts b/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
index 7af7096a0..bbe12e86e 100644
--- a/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
+++ b/control-ui/lib/__tests__/codexSubscription.sanitize.test.ts
@@ -1,7 +1,13 @@
import { describe, expect, it } from 'vitest'
-import { sanitizeCodexConnection } from '../codexSubscription'
+import {
+ type CodexSubscriptionConnectionView,
+ isAssignableCodexGrant,
+ sanitizeCodexConnection,
+} from '../codexSubscription'
-function connected(overrides: Record<string, unknown> = {}) {
+function connected(
+ overrides: Partial<CodexSubscriptionConnectionView> = {}
+): CodexSubscriptionConnectionView {
return {
connectionKey: 'codex-aaa',
status: 'connected',
@@ -34,3 +40,12 @@ describe('sanitizeCodexConnection', () => {
)
})
})
+
+describe('isAssignableCodexGrant', () => {
+ it('accepts only a connected grant whose catalog is ready', () => {
+ expect(isAssignableCodexGrant(connected())).toBe(true)
+ expect(isAssignableCodexGrant(connected({ status: 'connecting' }))).toBe(false)
+ expect(isAssignableCodexGrant(connected({ catalogStatus: 'never_synced' }))).toBe(false)
+ expect(isAssignableCodexGrant(connected({ status: 'revoked' }))).toBe(false)
+ })
+})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 2a3773de4..8b8ae6689 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -91,7 +91,7 @@ async function parseJsonResponse(res: Response): Promise<unknown> {
}
export function formatApiError(res: Response, text: string): Error {
- let detail = text
+ let detail: string
let parsedBody: Record<string, unknown> | null = null
try {
const parsed = JSON.parse(text) as { error?: unknown; message?: unknown }
@@ -1367,7 +1367,7 @@ export async function sfsUpload(
handler?.()
throw new Error('401 Unauthorized - session expired, please sign in again')
}
- let detail = text
+ let detail: string
try {
const parsed = JSON.parse(text) as { error?: { message?: string; code?: string } }
detail = parsed.error?.message || parsed.error?.code || text
diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.ts
index 74d1587ee..2dc31fdc8 100644
--- a/control-ui/lib/codexSubscription.ts
+++ b/control-ui/lib/codexSubscription.ts
@@ -25,6 +25,12 @@ export type CodexAssignableHost = {
export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned'
+export function isAssignableCodexGrant(
+ row: Pick<CodexSubscriptionConnectionView, 'status' | 'catalogStatus'>
+): boolean {
+ return row.status === 'connected' && row.catalogStatus === 'ready'
+}
+
export type CodexSubscriptionConnectionView = {
id?: string
connectionKey: string
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 7e0f771e7..a48c0df04 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.469",
+ "version": "0.1.470",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.469",
+ "version": "0.1.470",
"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 bb33e2433..e985fa60c 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.469",
+ "version": "0.1.470",
"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 8f00c9185..667c8656a 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.290",
+ "version": "0.1.291",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.290",
+ "version": "0.1.291",
"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 1bc3898b0..b2b3f621c 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.290",
+ "version": "0.1.291",
"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 459f3749d..2ecb98952 100644
--- a/mcp-host/src/config/configStore.test.ts
+++ b/mcp-host/src/config/configStore.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { register } from 'prom-client'
import { ALL_PROVIDERS, descriptorFor } from '../llm/registryCore'
import {
diff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.ts
index 8a0b8be1f..46c52daab 100644
--- a/mcp-host/src/core/types.ts
+++ b/mcp-host/src/core/types.ts
@@ -129,6 +129,12 @@ export interface CompletionResponse {
/** True only when the provider response carried authoritative token counters. */
usage_reported?: boolean
finish_reason: FinishReason
+ /**
+ * Physical ledger identity when the provider authorized a spend (Codex).
+ * Absent for static-credential providers that use a separate ticket issuer.
+ */
+ providerAttemptId?: string
+ providerAttemptIndex?: number
}
export interface ToolCompletionRequest {
diff --git a/mcp-host/src/llm/__tests__/codexSubscription.test.ts b/mcp-host/src/llm/__tests__/codexSubscription.test.ts
index 9b59a73d1..8d7147c36 100644
--- a/mcp-host/src/llm/__tests__/codexSubscription.test.ts
+++ b/mcp-host/src/llm/__tests__/codexSubscription.test.ts
@@ -163,6 +163,8 @@ describe('CodexSubscriptionProvider', () => {
const result = await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])
expect(result.usage_reported).toBe(false)
expect(result.usage).toEqual({ input_tokens: 0, output_tokens: 0, total_tokens: 0 })
+ expect(result.providerAttemptId).toBe('attempt-1')
+ expect(result.providerAttemptIndex).toBe(1)
})
it('omits MCP tools and caps natives at the Codex maxTools limit', () => {
diff --git a/mcp-host/src/llm/__tests__/registry.test.ts b/mcp-host/src/llm/__tests__/registry.test.ts
index 33eabb7bc..fbeb869ae 100644
--- a/mcp-host/src/llm/__tests__/registry.test.ts
+++ b/mcp-host/src/llm/__tests__/registry.test.ts
@@ -134,8 +134,8 @@ describe('createLLMProvider — fail-safe (§5.7)', () => {
)
const logged = spy.mock.calls.map(args => args.map(String).join(' ')).join('\n')
spy.mockRestore()
- expect(logged).toContain('[LLM] Unknown provider:')
- expect(logged).toContain('mystery')
+ expect(logged).toContain('[LLM] Unknown provider')
+ expect(logged).not.toContain('mystery')
expect(logged).not.toContain('%s')
expect(logged).not.toMatch(/mystery\n/)
})
diff --git a/mcp-host/src/llm/codexSubscription.ts b/mcp-host/src/llm/codexSubscription.ts
index 40a22862d..da152b20a 100644
--- a/mcp-host/src/llm/codexSubscription.ts
+++ b/mcp-host/src/llm/codexSubscription.ts
@@ -184,6 +184,8 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {
result.outcome === 'canceled' || result.outcome === 'unknown'
? FinishReason.Unknown
: FinishReason.Stop,
+ providerAttemptId: result.providerAttemptId,
+ providerAttemptIndex: result.providerAttemptIndex,
}
}
@@ -244,12 +246,13 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {
) {
throw new CodexAuthorizeError('no_grant', 'Codex catalog policy binding is missing')
}
+ const providerAttemptIndex = context.providerAttemptIndex ?? this.nextProviderAttemptIndex++
const authorized = await this.deps.authorizer.authorize({
request,
requestHash,
invocationId: context.invocationId ?? request.requestId,
attemptGeneration: context.attemptGeneration ?? 1,
- providerAttemptIndex: context.providerAttemptIndex ?? this.nextProviderAttemptIndex++,
+ providerAttemptIndex,
policyRevision: context.policyRevision,
policyHash: context.policyHash,
hostRef: context.hostRef,
@@ -260,12 +263,17 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {
if (!('accessToken' in authorized)) {
// Bound: authorize returns ticket material only.
}
- return this.deps.proxy.stream({
+ const streamed = await this.deps.proxy.stream({
executionTicket: authorized.executionTicket,
requestHash: authorized.requestHash,
request,
signal: options?.signal,
})
+ return {
+ ...streamed,
+ providerAttemptId: authorized.providerAttemptId,
+ providerAttemptIndex,
+ }
}
private buildRequest(
diff --git a/mcp-host/src/llm/index.ts b/mcp-host/src/llm/index.ts
index a8b597648..972eda63a 100644
--- a/mcp-host/src/llm/index.ts
+++ b/mcp-host/src/llm/index.ts
@@ -21,11 +21,6 @@ export type { ClassifiedError, SingleTurnProvider } from './types'
const DEFAULT_CODEX_AUTHORIZE_GATEWAY =
'http://nginx-workflow-approval-gateway.control-plane.svc.cluster.local:8092'
-function sanitizeLogValue(value: unknown): string {
- const raw = typeof value === 'string' ? value : String(value ?? '')
- return JSON.stringify(raw.replace(/[\r\n\u2028\u2029]/g, ''))
-}
-
function createCodexRuntimeDeps() {
const gateway = (config.mcpHostGatewayUrl ?? '').trim() || DEFAULT_CODEX_AUTHORIZE_GATEWAY
return {
@@ -68,7 +63,7 @@ export function createLLMProvider(
const modelName = modelConfig?.name
if (!isLlmProvider(provider)) {
- console.error('[LLM] Unknown provider: ' + sanitizeLogValue(provider))
+ console.error('[LLM] Unknown provider')
return null
}
@@ -79,13 +74,7 @@ export function createLLMProvider(
const credentials = keys[provider] ?? {}
for (const slot of descriptorFor(provider).credentialSlots) {
if (slot.required && !credentials[slot.dataKey]) {
- console.error(
- '[LLM] ' +
- sanitizeLogValue(provider) +
- ' credential ' +
- sanitizeLogValue(slot.dataKey) +
- ' not found in secrets'
- )
+ console.error('[LLM] required credential missing from secrets')
return null
}
}
@@ -104,12 +93,7 @@ export function createLLMProvider(
provider === 'codex-subscription' ? { codex: createCodexRuntimeDeps() } : undefined
)
} catch (err) {
- console.error(
- '[LLM] failed to construct ' +
- sanitizeLogValue(provider) +
- ': ' +
- sanitizeLogValue(err instanceof Error ? err.message : 'error')
- )
+ console.error('[LLM] failed to construct provider')
return null
}
}
diff --git a/mcp-host/src/logger.ts b/mcp-host/src/logger.ts
index 37c0f8e00..ad93bceb8 100644
--- a/mcp-host/src/logger.ts
+++ b/mcp-host/src/logger.ts
@@ -18,25 +18,37 @@ const COMPONENT_RE = /^\[([^\]]+)\]\s*/
const SENSITIVE_KEY_RE =
/password|secret|token|authorization|cookie|api[_-]?key|dsn|private|refresh|credential|account[_-]?id/i
const UNSAFE_OBJECT_KEY = /^(?:__proto__|constructor|prototype)$/
+const SAFE_OBJECT_KEY = /^[A-Za-z0-9._-]{1,64}$/
const originalLog = console.log.bind(console)
const originalError = console.error.bind(console)
const originalWarn = console.warn.bind(console)
-function redactReplacer(key: string, value: unknown): unknown {
- if (value === process.env) return '[Redacted]'
- if (UNSAFE_OBJECT_KEY.test(key)) return undefined
- if (key && SENSITIVE_KEY_RE.test(key)) return '[Redacted]'
- return value
+function isSafeObjectKey(key: string): boolean {
+ return SAFE_OBJECT_KEY.test(key) && !UNSAFE_OBJECT_KEY.test(key)
}
-export function redactUnknown(value: unknown, key?: string): unknown {
+function cloneRedacted(value: unknown, key?: string): unknown {
if (value === process.env) return '[Redacted]'
if (key && SENSITIVE_KEY_RE.test(key)) return '[Redacted]'
if (value === undefined) return undefined
if (typeof value !== 'object' || value === null) return value
+ if (Array.isArray(value)) return value.map(item => cloneRedacted(item))
+ const out: Record<string, unknown> = Object.create(null)
+ for (const nextKey of Object.keys(value as object)) {
+ if (!isSafeObjectKey(nextKey)) continue
+ if (SENSITIVE_KEY_RE.test(nextKey)) {
+ out[nextKey] = '[Redacted]'
+ continue
+ }
+ out[nextKey] = cloneRedacted((value as Record<string, unknown>)[nextKey], nextKey)
+ }
+ return out
+}
+
+export function redactUnknown(value: unknown, key?: string): unknown {
try {
- return JSON.parse(JSON.stringify(value, redactReplacer)) as unknown
+ return cloneRedacted(value, key)
} catch {
return '[Unserializable]'
}
@@ -58,14 +70,17 @@ function emit(level: string, args: unknown[]): void {
const match = raw.match(COMPONENT_RE)
if (match) {
- component = match[1]
- msg = raw.slice(match[0].length)
+ const parsed = match[1] ?? ''
+ if (SAFE_OBJECT_KEY.test(parsed)) {
+ component = parsed
+ msg = raw.slice(match[0].length)
+ }
}
const entry: Record<string, string> = {
timestamp: new Date().toISOString(),
level,
- msg: msg.trim(),
+ msg: msg.replace(/[\r\n\u2028\u2029]/g, ' ').trim(),
}
if (component) {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
index d723542b7..e551017df 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
@@ -483,4 +483,26 @@ describe('PromptBridgeHandler', () => {
)
expect(report).not.toHaveBeenCalled()
})
+
+ it('does not return an SDK-only completion without a physical attempt receipt', async () => {
+ const finalize = vi.fn<FinalizePromptBridge>()
+ const complete = vi.fn().mockResolvedValue({
+ model: primary.model,
+ servedTarget: primary,
+ fallbackUsed: false,
+ attemptCount: 1,
+ llmSecretName: '',
+ providerAttemptAcknowledgement: 'owned_by_finalizer',
+ content: 'ok',
+ usage: { inputTokens: 1, outputTokens: 1 },
+ finishReason: 'complete',
+ })
+ const { handler } = makeDeps({ complete, finalize })
+
+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ message: 'provider attempt receipt is missing from the SDK-only completion',
+ })
+ expect(finalize).not.toHaveBeenCalled()
+ })
})
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index 726a5b8c1..4e41286e2 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -588,6 +588,8 @@ describe('LlmBridge authorized multi-provider fallback', () => {
...OK,
usage_reported: false,
usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
+ providerAttemptId: 'attempt-codex',
+ providerAttemptIndex: 1,
}))
const { bridge, credentialCalls, resolver } = makeBridge({ 'gpt-5.1': provider })
const issuer = { issue: vi.fn() }
@@ -603,5 +605,40 @@ describe('LlmBridge authorized multi-provider fallback', () => {
expect(resolver.resolve).not.toHaveBeenCalled()
expect(credentialCalls).toEqual([])
expect(JSON.stringify(result)).not.toMatch(/ticket|authorization|refreshToken|accessToken/i)
+ expect(result.providerAttemptId).toBe('attempt-codex')
+ expect(result.providerAttemptIndex).toBe(1)
+ })
+
+ it('does not execute a Codex target while its circuit is open', async () => {
+ const codex: PromptBridgeTarget = {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ connectionRef: 'team-plus',
+ }
+ const provider = new FakeProvider(async () => ({
+ ...OK,
+ usage_reported: false,
+ usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
+ providerAttemptId: 'attempt-codex',
+ providerAttemptIndex: 1,
+ }))
+ const openBreaker = new CircuitBreaker({ minSamples: 1, failureRateThreshold: 0 })
+ openBreaker.record(false)
+ const { bridge, providerCalls } = makeBridge(
+ { 'gpt-5.1': provider },
+ undefined,
+ () => openBreaker
+ )
+
+ await expect(
+ bridge.complete({
+ ...request,
+ targets: [{ target: codex }],
+ })
+ ).rejects.toMatchObject({ code: 'provider_unavailable' })
+ expect(providerCalls).toEqual([])
+ expect(provider.completeSingleTurn).not.toHaveBeenCalled()
})
})
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index 07afbdcc3..2f00b11d7 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -303,6 +303,21 @@ export class LlmBridge {
isLlmProvider(authorized.target.provider) &&
descriptorFor(authorized.target.provider).authMode === 'oauth-broker'
) {
+ if (!breaker.allow()) {
+ lastProviderError = new ClassifiedProviderError(
+ { code: LlmErrorCode.ApiCallFailed, retryable: true },
+ new PluginWorkloadError(
+ 'provider_unavailable',
+ 'LLM provider circuit is open',
+ true,
+ 'provider_unavailable'
+ )
+ )
+ if (index === request.targets.length - 1) {
+ throw lastProviderError.toPluginWorkloadError()
+ }
+ continue
+ }
try {
const completion = await this.attempt(
{ target: authorized.target, keys: {}, llmSecretName: '' },
@@ -562,7 +577,12 @@ export class LlmBridge {
credential: BrokeredCredential,
request: LlmBridgeRequest,
breaker: CircuitBreaker
- ): Promise<Pick<LlmBridgeResult, 'model' | 'content' | 'usage' | 'finishReason'>> {
+ ): Promise<
+ Pick<
+ LlmBridgeResult,
+ 'model' | 'content' | 'usage' | 'finishReason' | 'providerAttemptId' | 'providerAttemptIndex'
+ >
+ > {
if (request.timeoutMs <= 0) {
throw new PluginWorkloadError(
'provider_unavailable',
@@ -636,6 +656,14 @@ export class LlmBridge {
content: response.content,
usage: { inputTokens, outputTokens },
finishReason: mapFinishReason(response.finish_reason),
+ ...(typeof response.providerAttemptId === 'string' && response.providerAttemptId
+ ? { providerAttemptId: response.providerAttemptId }
+ : {}),
+ ...(typeof response.providerAttemptIndex === 'number' &&
+ Number.isInteger(response.providerAttemptIndex) &&
+ response.providerAttemptIndex >= 1
+ ? { providerAttemptIndex: response.providerAttemptIndex }
+ : {}),
}
} catch (error) {
if (error instanceof PluginWorkloadError) throw error
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 1449732c9..0edfc0f0c 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.310",
+ "version": "0.1.311",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.310",
+ "version": "0.1.311",
"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 1db94c0e9..42d320a88 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.310",
+ "version": "0.1.311",
"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 57f82f50d..cccd6fdc5 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -272,12 +272,14 @@ describe('WorkflowRecipeReconciler', () => {
},
})
const workflowReconcile = vi.fn()
+ const setCodexReconcileContext = vi.fn()
;(
reconciler as unknown as {
config: { pluginWorkloadSdkEnabled: boolean }
workflowReconciler: {
reconcile: typeof workflowReconcile
reconcilePluginWorkloadSdkOnly: typeof reconcilePluginWorkloadSdkOnly
+ setCodexReconcileContext: typeof setCodexReconcileContext
}
}
).config.pluginWorkloadSdkEnabled = true
@@ -286,9 +288,14 @@ describe('WorkflowRecipeReconciler', () => {
workflowReconciler: {
reconcile: typeof workflowReconcile
reconcilePluginWorkloadSdkOnly: typeof reconcilePluginWorkloadSdkOnly
+ setCodexReconcileContext: typeof setCodexReconcileContext
}
}
- ).workflowReconciler = { reconcile: workflowReconcile, reconcilePluginWorkloadSdkOnly }
+ ).workflowReconciler = {
+ reconcile: workflowReconcile,
+ reconcilePluginWorkloadSdkOnly,
+ setCodexReconcileContext,
+ }
const recipe = makeRecipe({
spec: {
@@ -301,11 +308,18 @@ describe('WorkflowRecipeReconciler', () => {
const result = await reconciler.reconcile(recipe)
expect(result.phase).toBe('active')
+ expect(setCodexReconcileContext).toHaveBeenCalledWith(
+ expect.objectContaining({
+ recipeName: 'test-recipe',
+ runtimeScopeRecipeName: 'test-recipe',
+ })
+ )
expect(reconcilePluginWorkloadSdkOnly).toHaveBeenCalledWith(
'test-recipe',
'uid-123',
'sandbox-recipes',
- recipe.spec
+ recipe.spec,
+ 'test-recipe'
)
expect(workflowReconcile).not.toHaveBeenCalled()
})
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index e294ec93f..9ac8bd92b 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -2707,11 +2707,14 @@ export class WorkflowRecipeReconciler {
message: 'Plugin Workload SDK subsystem not initialized — missing clerum-wrc-signing-key',
}
}
+ const runtimeScopeRecipeName = await this.workflowRuntimeScopeRecipeName(recipe)
+ await this.bindCodexReconcileContext(recipe, runtimeScopeRecipeName)
return this.workflowReconciler.reconcilePluginWorkloadSdkOnly(
recipe.metadata.name,
recipe.metadata.uid ?? '',
recipe.metadata.namespace,
- recipe.spec
+ recipe.spec,
+ runtimeScopeRecipeName
)
}
diff --git a/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
index bf2796489..caa045c6b 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
@@ -356,6 +356,10 @@ describe('WorkflowReconciler Codex scope provenance', () => {
expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
expect(issuedScopes()).not.toContain('llm:codex:execute')
expect(proxyPolicyBodies(networkingApi)).toEqual([])
+ expect(networkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
+ name: CODEX_PROXY_POLICY,
+ namespace: sandboxNamespace,
+ })
})
it('does not mint Codex scope or egress when the allowlist ConfigMap times out', async () => {
@@ -369,5 +373,9 @@ describe('WorkflowReconciler Codex scope provenance', () => {
expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
expect(issuedScopes()).not.toContain('llm:codex:execute')
expect(proxyPolicyBodies(networkingApi)).toEqual([])
+ expect(networkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
+ name: CODEX_PROXY_POLICY,
+ namespace: sandboxNamespace,
+ })
})
})
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 5cf89791e..fc8bb9394 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -2821,6 +2821,12 @@ export class WorkflowReconciler {
// deploys the mcp-host (and its NetworkPolicy lanes) before any run is
// triggered. The artifact-reader/snippet-runner stay run-only.
const mcpHostLaneLive = !awaitsTriggeredRun || eagerSdkMcpHost
+ const includeMcpHost = runtime.network.includeMcpHost && mcpHostLaneLive
+ const codexProjection = this.projectCodex(
+ spec,
+ recipeName,
+ this.codexContext?.runtimeScopeRecipeName ?? recipeName
+ )
const npConfig: NetworkPolicyConfig = {
recipeName,
sandboxNamespace: this.deps.config.sandboxNamespace,
@@ -2830,12 +2836,8 @@ export class WorkflowReconciler {
mcpHostPort: 8080,
artifactReaderPort: 8080,
snippetRunnerPort: 8095,
- includeMcpHost: runtime.network.includeMcpHost && mcpHostLaneLive,
- includeCodexProxyEgress:
- this.projectCodex(spec, recipeName, this.codexContext?.runtimeScopeRecipeName ?? recipeName)
- .requiresCodexProxyEgress &&
- runtime.network.includeMcpHost &&
- mcpHostLaneLive,
+ includeMcpHost,
+ includeCodexProxyEgress: codexProjection.requiresCodexProxyEgress && includeMcpHost,
// A stepless eager SDK host has no coordinator pod. Keep the mcp-host
// control/egress lanes, but do not manufacture coordinator policies
// whose selectors can never match a real workload.
@@ -2942,7 +2944,12 @@ export class WorkflowReconciler {
}
const policyNames = new Set(policies.map(policy => policy.metadata?.name))
const codexProxyPolicyName = `${recipeName}-mcp-host-to-codex-proxy`
- if (!policyNames.has(codexProxyPolicyName)) {
+ const codexProjection = this.projectCodex(
+ spec,
+ recipeName,
+ this.codexContext?.runtimeScopeRecipeName ?? recipeName
+ )
+ if (!policyNames.has(codexProxyPolicyName) && codexProjection.eligibility !== 'uncertain') {
await this.safeDelete(() =>
this.deps.networkingApi.deleteNamespacedNetworkPolicy({
name: codexProxyPolicyName,