Skip to content

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

TypeScript

fix: close reserved Codex SDK attempts through authorize-link

Alfredo Lopez1a8b0dd0bb19
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index aeaf96298..398056d97 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.526",
+ "version": "0.1.527",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.526",
+ "version": "0.1.527",
"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 872bcf041..83bdec9b4 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.526",
+ "version": "0.1.527",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index 356106f62..d2c282feb 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -22,6 +22,7 @@ import {
import {
applyLlmProviderAttemptConnectionIdSchema,
applyLlmProviderAttemptSchema,
+ applyLlmProviderAttemptSdkLinkOnDeleteSetNullSchema,
applyLlmProviderAttemptSdkLinkSchema,
applyLlmProviderAttemptTicketSchema,
} from './services/llmProviderAttemptStore.js'
@@ -6009,6 +6010,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0107_llm_provider_attempts_sdk_link',
apply: applyLlmProviderAttemptSdkLinkSchema,
},
+ {
+ version: '0108_llm_provider_attempts_sdk_link_on_delete_set_null',
+ apply: applyLlmProviderAttemptSdkLinkOnDeleteSetNullSchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
index 1ee6f18b8..a9ac51e8d 100644
--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
@@ -1,6 +1,5 @@
import { type NextFunction, type Request, type Response, Router } from 'express'
import { rateLimit } from 'express-rate-limit'
-import { PROVIDER_AUTH_MODE, isLlmProviderId } from '@clerum/llm-providers'
import { config } from '../../config.js'
import { pool } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
@@ -193,9 +192,7 @@ function parsePromptBridgeFinalizationBody(
reason.length > 128 ||
!targetRef ||
!provider ||
- !model ||
- (!(isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker') &&
- !credentialSlot)
+ !model
) {
res.status(400).json({
error:
@@ -219,9 +216,7 @@ function parsePromptBridgeFinalizationBody(
const outputTokens = Number.isInteger(rawUsage.outputTokens)
? Number(rawUsage.outputTokens)
: -1
- const oauthBroker = isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker'
if (
- (!oauthBroker && !llmSecretName) ||
!callerRef ||
typeof rawUsage.fallbackUsed !== 'boolean' ||
attemptCount < 1 ||
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 5228ef56c..d78223358 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -23,7 +23,12 @@ import {
insertLlmProviderAttempt,
} from './llmProviderAttemptStore.js'
import { issueRegisteredCodexExecutionTicket } from './llmProviderAttemptTicket.js'
-import { getPluginWorkloadSdkProviderAttempt } from './pluginWorkloadSdkDb.js'
+import {
+ getPluginWorkloadSdkProviderAttemptForUpdate,
+ lockPluginWorkloadSdkRecipe,
+ pluginWorkloadSdkSpendOutcomeExists,
+ promoteReservedOauthBrokerProviderAttempt,
+} from './pluginWorkloadSdkDb.js'
const log = rootLogger.child({ module: 'llm-provider-attempt-authorizer' })
const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'
@@ -43,6 +48,7 @@ const AUTHORIZE_BODY_KEYS = new Set([
'recipeName',
'userId',
'pluginWorkloadSdkProviderAttemptId',
+ 'targetRef',
])
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
@@ -363,6 +369,17 @@ export async function authorizeLlmProviderAttempt(
typeof body.pluginWorkloadSdkProviderAttemptId === 'string'
? body.pluginWorkloadSdkProviderAttemptId.trim()
: ''
+ const presentedTargetRef = typeof body.targetRef === 'string' ? body.targetRef.trim() : ''
+ let reservedSdkAttemptToPromote: {
+ id: string
+ invocationId: string
+ recipeNamespace: string
+ recipeName: string
+ attemptGeneration: number
+ attemptIndex: number
+ model: string
+ targetRef: string
+ } | null = null
if (pluginWorkloadSdkProviderAttemptId) {
if (!UUID_RE.test(pluginWorkloadSdkProviderAttemptId)) {
throw new LlmProviderAttemptAuthorizeError(
@@ -370,18 +387,38 @@ export async function authorizeLlmProviderAttempt(
'pluginWorkloadSdkProviderAttemptId must be a UUID'
)
}
- const sdkAttempt = await getPluginWorkloadSdkProviderAttempt(
+ if (caller.callerKind === 'host') {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'host Codex chat cannot bind a Plugin Workload SDK provider attempt'
+ )
+ }
+ if (!caller.recipeNamespace || !caller.recipeName) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
+ )
+ }
+ await lockPluginWorkloadSdkRecipe(db, caller.recipeNamespace, caller.recipeName)
+ const sdkAttempt = await getPluginWorkloadSdkProviderAttemptForUpdate(
pluginWorkloadSdkProviderAttemptId,
db
)
+ const spendExists = sdkAttempt
+ ? await pluginWorkloadSdkSpendOutcomeExists(sdkAttempt.id, db)
+ : false
if (
!sdkAttempt ||
+ spendExists ||
sdkAttempt.invocationId !== invocationId ||
sdkAttempt.attemptGeneration !== attemptGeneration ||
sdkAttempt.attemptIndex !== providerAttemptIndex ||
sdkAttempt.recipeNamespace !== caller.recipeNamespace ||
sdkAttempt.recipeName !== caller.recipeName ||
sdkAttempt.provider !== PROVIDER ||
+ sdkAttempt.model !== request.model ||
+ !sdkAttempt.targetRef.trim() ||
+ (presentedTargetRef !== '' && presentedTargetRef !== sdkAttempt.targetRef) ||
!['reserved', 'in_progress'].includes(sdkAttempt.status)
) {
throw new LlmProviderAttemptAuthorizeError(
@@ -389,6 +426,18 @@ export async function authorizeLlmProviderAttempt(
'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
)
}
+ if (sdkAttempt.status === 'reserved') {
+ reservedSdkAttemptToPromote = {
+ id: sdkAttempt.id,
+ invocationId: sdkAttempt.invocationId,
+ recipeNamespace: sdkAttempt.recipeNamespace,
+ recipeName: sdkAttempt.recipeName,
+ attemptGeneration: sdkAttempt.attemptGeneration,
+ attemptIndex: sdkAttempt.attemptIndex,
+ model: sdkAttempt.model,
+ targetRef: sdkAttempt.targetRef,
+ }
+ }
}
try {
@@ -409,6 +458,27 @@ export async function authorizeLlmProviderAttempt(
connectionId: connection.id,
...(pluginWorkloadSdkProviderAttemptId ? { pluginWorkloadSdkProviderAttemptId } : {}),
})
+ if (reservedSdkAttemptToPromote) {
+ const promoted = await promoteReservedOauthBrokerProviderAttempt(
+ reservedSdkAttemptToPromote,
+ db
+ )
+ if (!promoted) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'pluginWorkloadSdkProviderAttemptId is no longer reserved for Codex authorize'
+ )
+ }
+ log.info(
+ {
+ event: 'sdk_oauth_attempt_promoted',
+ pluginWorkloadSdkProviderAttemptId: reservedSdkAttemptToPromote.id,
+ providerAttemptId: attempt.id,
+ credentialJtiPresent: false,
+ },
+ 'promoted reserved SDK oauth attempt after Codex authorize-link'
+ )
+ }
const issued = await resolvedDeps.issueTicket(db, {
sub: claims.sub,
hostRef: caller.hostRef,
diff --git a/control-api/src/services/llmProviderAttemptStore.ts b/control-api/src/services/llmProviderAttemptStore.ts
index 2318a4a9f..1e1c2d494 100644
--- a/control-api/src/services/llmProviderAttemptStore.ts
+++ b/control-api/src/services/llmProviderAttemptStore.ts
@@ -105,6 +105,38 @@ export async function applyLlmProviderAttemptSdkLinkSchema(db: DbClient): Promis
`)
}
+export async function applyLlmProviderAttemptSdkLinkOnDeleteSetNullSchema(
+ db: DbClient
+): Promise<void> {
+ await db.query(`
+ DO $$
+ DECLARE
+ constraint_name text;
+ BEGIN
+ SELECT c.conname INTO constraint_name
+ FROM pg_constraint c
+ JOIN pg_class t ON t.oid = c.conrelid
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY (c.conkey)
+ WHERE t.relname = 'llm_provider_attempts'
+ AND c.contype = 'f'
+ AND a.attname = 'plugin_workload_sdk_provider_attempt_id'
+ LIMIT 1;
+ IF constraint_name IS NOT NULL THEN
+ EXECUTE format(
+ 'ALTER TABLE llm_provider_attempts DROP CONSTRAINT %I',
+ constraint_name
+ );
+ END IF;
+ END $$;
+
+ ALTER TABLE llm_provider_attempts
+ ADD CONSTRAINT llm_provider_attempts_plugin_workload_sdk_provider_attempt_id_fkey
+ FOREIGN KEY (plugin_workload_sdk_provider_attempt_id)
+ REFERENCES plugin_workload_sdk_provider_attempts(id)
+ ON DELETE SET NULL;
+ `)
+}
+
export async function applyLlmProviderAttemptTicketSchema(db: DbClient): Promise<void> {
await db.query(`
CREATE TABLE IF NOT EXISTS llm_provider_attempt_tickets (
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index 50140229f..738e78bf0 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -1493,6 +1493,84 @@ export async function getPluginWorkloadSdkProviderAttempt(
return row ? mapProviderAttemptRow(row) : null
}
+export async function lockPluginWorkloadSdkRecipe(
+ db: DbClient,
+ recipeNamespace: string,
+ recipeName: string
+): Promise<void> {
+ const recipeLock = `plugin_workload_sdk:${recipeNamespace}/${recipeName}`
+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])
+}
+
+export async function getPluginWorkloadSdkProviderAttemptForUpdate(
+ id: string,
+ db: DbClient
+): Promise<PluginWorkloadSdkProviderAttempt | null> {
+ const result = await db.query(
+ `SELECT * FROM plugin_workload_sdk_provider_attempts WHERE id = $1 FOR UPDATE`,
+ [id]
+ )
+ const row = result.rows[0] as Record<string, unknown> | undefined
+ return row ? mapProviderAttemptRow(row) : null
+}
+
+export async function pluginWorkloadSdkSpendOutcomeExists(
+ providerAttemptId: string,
+ db: DbClient
+): Promise<boolean> {
+ const result = await db.query(
+ `SELECT 1 FROM plugin_workload_sdk_spend_outcomes WHERE provider_attempt_id = $1`,
+ [providerAttemptId]
+ )
+ return result.rows.length > 0
+}
+
+/**
+ * JTI-free reserved → in_progress for Codex authorize-link. Does not write
+ * credential_jti. The secret-ticket path still promotes through
+ * registerPluginWorkloadSdkCredentialTicketJti.
+ */
+export async function promoteReservedOauthBrokerProviderAttempt(
+ input: {
+ id: string
+ invocationId: string
+ recipeNamespace: string
+ recipeName: string
+ attemptGeneration: number
+ attemptIndex: number
+ model: string
+ targetRef: string
+ },
+ db: DbClient
+): Promise<boolean> {
+ const result = await db.query(
+ `UPDATE plugin_workload_sdk_provider_attempts
+ SET status = 'in_progress'
+ WHERE id = $1
+ AND invocation_id = $2
+ AND recipe_namespace = $3
+ AND recipe_name = $4
+ AND attempt_generation = $5
+ AND attempt_index = $6
+ AND provider = 'codex-subscription'
+ AND model = $7
+ AND target_ref = $8
+ AND status = 'reserved'
+ AND credential_jti IS NULL`,
+ [
+ input.id,
+ input.invocationId,
+ input.recipeNamespace,
+ input.recipeName,
+ input.attemptGeneration,
+ input.attemptIndex,
+ input.model,
+ input.targetRef,
+ ]
+ )
+ return (result.rowCount ?? 0) === 1
+}
+
export async function markPluginWorkloadSdkProviderAttemptStatus(input: {
id: string
invocationId: string
@@ -2177,6 +2255,20 @@ export async function prunePluginWorkloadSdkExpiredIdempotency(): Promise<number
AND inv.status <> 'in_progress'`,
[IDEMPOTENCY_TTL_HOURS]
)
+ // Unlink the durable Codex ledger before deleting SDK attempt rows.
+ // 0108 also SET NULLs the FK on delete; this UPDATE keeps prune from
+ // depending on that constraint name and never CASCADE-deletes spend.
+ await db.query(
+ `UPDATE llm_provider_attempts a
+ SET plugin_workload_sdk_provider_attempt_id = NULL
+ FROM plugin_workload_sdk_provider_attempts attempts
+ JOIN plugin_workload_sdk_invocations inv
+ ON attempts.invocation_id = inv.id
+ WHERE a.plugin_workload_sdk_provider_attempt_id = attempts.id
+ AND inv.created_at < now() - interval '1 hour' * $1
+ AND inv.status <> 'in_progress'`,
+ [IDEMPOTENCY_TTL_HOURS]
+ )
await db.query(
`DELETE FROM plugin_workload_sdk_provider_attempts attempts
USING plugin_workload_sdk_invocations inv
diff --git a/control-api/test/db.llmProviderAttemptMigration.test.ts b/control-api/test/db.llmProviderAttemptMigration.test.ts
index 5578e273e..b0c8b1571 100644
--- a/control-api/test/db.llmProviderAttemptMigration.test.ts
+++ b/control-api/test/db.llmProviderAttemptMigration.test.ts
@@ -46,12 +46,19 @@ describe('00a2/00a3 LLM provider-attempt ledger', () => {
it('registers the unique SDK-attempt link after the latest Codex OAuth owner migration', () => {
expect(dbSource).toContain("version: '0106_oauth_grants_owner_generalization'")
expect(dbSource).toContain("version: '0107_llm_provider_attempts_sdk_link'")
+ expect(dbSource).toContain("version: '0108_llm_provider_attempts_sdk_link_on_delete_set_null'")
expect(dbSource).toContain('apply: applyLlmProviderAttemptSdkLinkSchema')
+ expect(dbSource).toContain('apply: applyLlmProviderAttemptSdkLinkOnDeleteSetNullSchema')
expect(dbSource.indexOf("version: '0106_oauth_grants_owner_generalization'")).toBeLessThan(
dbSource.indexOf("version: '0107_llm_provider_attempts_sdk_link'")
)
+ expect(dbSource.indexOf("version: '0107_llm_provider_attempts_sdk_link'")).toBeLessThan(
+ dbSource.indexOf("version: '0108_llm_provider_attempts_sdk_link_on_delete_set_null'")
+ )
expect(storeSource).toContain('plugin_workload_sdk_provider_attempt_id UUID')
expect(storeSource).toContain('REFERENCES plugin_workload_sdk_provider_attempts(id)')
+ expect(storeSource).toContain('ON DELETE SET NULL')
+ expect(storeSource).not.toMatch(/ON DELETE CASCADE/i)
expect(storeSource).toContain(
'CREATE UNIQUE INDEX IF NOT EXISTS llm_provider_attempts_sdk_attempt_uidx'
)
diff --git a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
index 99c133ed3..a61f1911c 100644
--- a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
+++ b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
@@ -21,13 +21,16 @@ describe('0101 oauth_grants owner generalization migration', () => {
const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
const versions = CONTROL_API_MIGRATIONS.map(m => m.version)
expect(versions).toContain('0106_oauth_grants_owner_generalization')
- expect(versions.at(-1)).toBe('0107_llm_provider_attempts_sdk_link')
+ expect(versions.at(-1)).toBe('0108_llm_provider_attempts_sdk_link_on_delete_set_null')
expect(versions.indexOf('0100_seed_minimax_allowed_model')).toBeLessThan(
versions.indexOf('0106_oauth_grants_owner_generalization')
)
expect(versions.indexOf('0106_oauth_grants_owner_generalization')).toBeLessThan(
versions.indexOf('0107_llm_provider_attempts_sdk_link')
)
+ expect(versions.indexOf('0107_llm_provider_attempts_sdk_link')).toBeLessThan(
+ versions.indexOf('0108_llm_provider_attempts_sdk_link_on_delete_set_null')
+ )
expect(versions).toContain('0099_gfs_upload_finalizing_recovery')
expect(versions).toContain('0100_seed_minimax_allowed_model')
})
diff --git a/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
index 65b622424..f3d834491 100644
--- a/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
+++ b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
@@ -12,6 +12,7 @@ import {
recordCodexCatalogOutcome,
} from '../src/services/codexSubscriptionConnection.js'
import {
+ LlmProviderAttemptAuthorizeError,
type LlmProviderAttemptAuthorizerDeps,
authorizeLlmProviderAttempt,
computeCodexPolicyHash,
@@ -23,6 +24,7 @@ import {
loadLlmProviderAttemptBySdkAttemptId,
} from '../src/services/llmProviderAttemptStore.js'
import { issueRegisteredCodexExecutionTicket } from '../src/services/llmProviderAttemptTicket.js'
+import { prunePluginWorkloadSdkExpiredIdempotency } from '../src/services/pluginWorkloadSdkDb.js'
import { finalizePromptBridgeInTransaction } from '../src/services/pluginWorkloadSdkFinalization.js'
import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
import './realPostgres.requirement.ts'
@@ -304,6 +306,13 @@ describeRealPostgres('Plugin Workload SDK Codex dual ledger on real PostgreSQL',
expect(linked?.id).toBe(authorized.providerAttemptId)
expect(linked?.pluginWorkloadSdkProviderAttemptId).toBe(sdkAttemptId)
expect(linked?.invocationId).toBe(invocationId)
+ const promoted = await pool.query<{ status: string; credential_jti: string | null }>(
+ `SELECT status, credential_jti
+ FROM plugin_workload_sdk_provider_attempts
+ WHERE id = $1`,
+ [sdkAttemptId]
+ )
+ expect(promoted.rows[0]).toEqual({ status: 'in_progress', credential_jti: null })
expect(JSON.stringify(authorized)).not.toContain('refresh-sdk-dual')
})
@@ -340,14 +349,69 @@ describeRealPostgres('Plugin Workload SDK Codex dual ledger on real PostgreSQL',
expect(stored.rows[0]?.plugin_workload_sdk_provider_attempt_id).toBeNull()
})
+ it('rejects Codex complete while the reserved SDK attempt has not been authorized', async () => {
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'reserved' })
+ await expect(
+ finalizePromptBridgeInTransaction(
+ {
+ invocationId,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRef: `${NS}/${RECIPE}`,
+ attemptGeneration: 1,
+ providerAttemptId: sdkAttemptId,
+ providerAttemptIndex: 1,
+ status: 'complete',
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: MODEL,
+ credentialSlot: '',
+ },
+ reason: 'provider_completed',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ pool
+ )
+ ).rejects.toMatchObject({
+ name: 'PromptBridgeFinalizationError',
+ code: 'conflict',
+ httpStatus: 409,
+ })
+ })
+
it('finalizes complete plus linked Codex success as exact using Codex usage', async () => {
- const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'in_progress' })
- const codex = await insertLlmProviderAttempt(
- pool,
- attemptInput({
+ const current = await getSafeCodexSubscriptionConnection(pool)
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'reserved' })
+ const authorized = await authorizeLlmProviderAttempt(
+ recipeClaims(),
+ {
+ request: {
+ ...REQUEST,
+ requestId: `req-exact-${invocationId}`,
+ idempotencyKey: `idem-exact-${invocationId}`,
+ },
invocationId,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ policyRevision: current!.catalogRevision,
+ policyHash: computeCodexPolicyHash({
+ model: MODEL,
+ catalogRevision: current!.catalogRevision,
+ credentialRevision: current!.credentialRevision,
+ connectionKey: current!.connectionKey,
+ }),
pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
- })
+ targetRef: 'codex-primary',
+ },
+ testDeps()
)
await pool.query(
`UPDATE llm_provider_attempts
@@ -357,7 +421,7 @@ describeRealPostgres('Plugin Workload SDK Codex dual ledger on real PostgreSQL',
usage_output_tokens = 7,
finalized_at = now()
WHERE id = $1`,
- [codex.id]
+ [authorized.providerAttemptId]
)
const result = await finalizePromptBridgeInTransaction(
@@ -539,4 +603,118 @@ describeRealPostgres('Plugin Workload SDK Codex dual ledger on real PostgreSQL',
)
).resolves.toMatchObject({ idempotent: true, outcome: 'unknown', usageAccepted: false })
})
+
+ it('refuses authorize-link after finalize failed already wrote spend', async () => {
+ const current = await getSafeCodexSubscriptionConnection(pool)
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'reserved' })
+ await finalizePromptBridgeInTransaction(
+ {
+ invocationId,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRef: `${NS}/${RECIPE}`,
+ attemptGeneration: 1,
+ providerAttemptId: sdkAttemptId,
+ providerAttemptIndex: 1,
+ status: 'failed',
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: MODEL,
+ credentialSlot: '',
+ },
+ reason: 'codex_execution_binding_missing',
+ },
+ pool
+ )
+ await expect(
+ authorizeLlmProviderAttempt(
+ recipeClaims(),
+ {
+ request: {
+ ...REQUEST,
+ requestId: `req-race-${invocationId}`,
+ idempotencyKey: `idem-race-${invocationId}`,
+ },
+ invocationId,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ policyRevision: current!.catalogRevision,
+ policyHash: computeCodexPolicyHash({
+ model: MODEL,
+ catalogRevision: current!.catalogRevision,
+ credentialRevision: current!.credentialRevision,
+ connectionKey: current!.connectionKey,
+ }),
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ targetRef: 'codex-primary',
+ },
+ testDeps()
+ )
+ ).rejects.toBeInstanceOf(LlmProviderAttemptAuthorizeError)
+ expect(await loadLlmProviderAttemptBySdkAttemptId(pool, sdkAttemptId)).toBeNull()
+ })
+
+ it('prunes a linked terminal SDK attempt without deleting the Codex ledger row', async () => {
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'reserved' })
+ const current = await getSafeCodexSubscriptionConnection(pool)
+ const authorized = await authorizeLlmProviderAttempt(
+ recipeClaims(),
+ {
+ request: {
+ ...REQUEST,
+ requestId: `req-prune-${invocationId}`,
+ idempotencyKey: `idem-prune-${invocationId}`,
+ },
+ invocationId,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ policyRevision: current!.catalogRevision,
+ policyHash: computeCodexPolicyHash({
+ model: MODEL,
+ catalogRevision: current!.catalogRevision,
+ credentialRevision: current!.credentialRevision,
+ connectionKey: current!.connectionKey,
+ }),
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ targetRef: 'codex-primary',
+ },
+ testDeps()
+ )
+ await pool.query(
+ `UPDATE plugin_workload_sdk_invocations
+ SET status = 'complete', created_at = now() - interval '25 hours'
+ WHERE id = $1`,
+ [invocationId]
+ )
+ const deleteRule = await pool.query<{ delete_rule: string }>(
+ `SELECT rc.delete_rule
+ FROM information_schema.referential_constraints rc
+ JOIN information_schema.key_column_usage kcu
+ ON rc.constraint_name = kcu.constraint_name
+ WHERE kcu.table_name = 'llm_provider_attempts'
+ AND kcu.column_name = 'plugin_workload_sdk_provider_attempt_id'`
+ )
+ expect(deleteRule.rows[0]?.delete_rule).toBe('SET NULL')
+ const pruned = await prunePluginWorkloadSdkExpiredIdempotency()
+ expect(pruned).toBeGreaterThan(0)
+ const leftoverSdk = await pool.query(
+ `SELECT id FROM plugin_workload_sdk_provider_attempts WHERE id = $1`,
+ [sdkAttemptId]
+ )
+ expect(leftoverSdk.rows).toHaveLength(0)
+ const ledger = await pool.query<{
+ id: string
+ plugin_workload_sdk_provider_attempt_id: string | null
+ }>(
+ `SELECT id, plugin_workload_sdk_provider_attempt_id
+ FROM llm_provider_attempts
+ WHERE id = $1`,
+ [authorized.providerAttemptId]
+ )
+ expect(ledger.rows[0]).toEqual({
+ id: authorized.providerAttemptId,
+ plugin_workload_sdk_provider_attempt_id: null,
+ })
+ })
})
diff --git a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
index 02c02804c..550f82568 100644
--- a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
+++ b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
@@ -855,6 +855,47 @@ describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/finalize', () => {
expect(res.body).toMatchObject({ error: 'idempotency_conflict', retryable: false })
})
+ it('accepts empty Codex credential fields and defers auth-mode rules to the service', async () => {
+ vi.mocked(finalizer.finalizePromptBridge).mockResolvedValue({
+ invocationId: 'inv-1',
+ providerAttemptId: finalizationBody.providerAttemptId,
+ status: 'complete',
+ outcome: 'exact',
+ idempotent: false,
+ usageAccepted: false,
+ })
+ const res = await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/invocations/inv-1/finalize')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send({
+ ...finalizationBody,
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ },
+ usage: {
+ llmSecretName: '',
+ callerRef: 'api',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ })
+ expect(res.status).toBe(201)
+ expect(finalizer.finalizePromptBridge).toHaveBeenCalledWith(
+ expect.objectContaining({
+ target: expect.objectContaining({
+ provider: 'codex-subscription',
+ credentialSlot: '',
+ }),
+ usage: expect.objectContaining({ llmSecretName: '' }),
+ })
+ )
+ })
+
it('accepts a failed no-execution finalization without usage claims', async () => {
vi.mocked(finalizer.finalizePromptBridge).mockResolvedValue({
invocationId: 'inv-1',
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index a9d42c7c0..5e9010e06 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -8,7 +8,10 @@ import {
} from '../src/services/llmProviderAttemptAuthorizer.js'
import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
-const getPluginWorkloadSdkProviderAttempt = vi.hoisted(() => vi.fn())
+const lockPluginWorkloadSdkRecipe = vi.hoisted(() => vi.fn())
+const getPluginWorkloadSdkProviderAttemptForUpdate = vi.hoisted(() => vi.fn())
+const pluginWorkloadSdkSpendOutcomeExists = vi.hoisted(() => vi.fn())
+const promoteReservedOauthBrokerProviderAttempt = vi.hoisted(() => vi.fn())
vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
const actual = await vi.importActual<typeof import('../src/services/pluginWorkloadSdkDb.js')>(
@@ -16,10 +19,35 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
)
return {
...actual,
- getPluginWorkloadSdkProviderAttempt,
+ lockPluginWorkloadSdkRecipe,
+ getPluginWorkloadSdkProviderAttemptForUpdate,
+ pluginWorkloadSdkSpendOutcomeExists,
+ promoteReservedOauthBrokerProviderAttempt,
}
})
+function reservedSdkAttempt(overrides: Record<string, unknown> = {}) {
+ return {
+ id: '44444444-4444-4444-8444-444444444444',
+ invocationId: 'invocation-1',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ attemptGeneration: 1,
+ attemptIndex: 1,
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ status: 'reserved',
+ credentialJti: null,
+ startedAt: new Date().toISOString(),
+ leaseExpiresAt: null,
+ completedAt: null,
+ usageRequestId: null,
+ ...overrides,
+ }
+}
+
const REQUEST = {
schemaVersion: 'codex-completion-request.v1' as const,
requestId: 'req-001',
@@ -116,7 +144,10 @@ describe('authorizeLlmProviderAttempt', () => {
beforeEach(() => {
current = deps()
- getPluginWorkloadSdkProviderAttempt.mockReset()
+ lockPluginWorkloadSdkRecipe.mockReset().mockResolvedValue(undefined)
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockReset()
+ pluginWorkloadSdkSpendOutcomeExists.mockReset().mockResolvedValue(false)
+ promoteReservedOauthBrokerProviderAttempt.mockReset().mockResolvedValue(true)
})
it('authorizes a bound attempt and returns a ticket without persisting messages', async () => {
@@ -194,34 +225,24 @@ describe('authorizeLlmProviderAttempt', () => {
it('binds a reserved Plugin Workload SDK attempt onto the Codex ledger row', async () => {
const sdkAttemptId = '44444444-4444-4444-8444-444444444444'
- getPluginWorkloadSdkProviderAttempt.mockResolvedValue({
- id: sdkAttemptId,
- invocationId: 'invocation-1',
- recipeNamespace: 'sandbox-recipes',
- recipeName: 'prompt-notify',
- attemptGeneration: 1,
- attemptIndex: 1,
- targetRef: 'codex-primary',
- provider: 'codex-subscription',
- model: 'gpt-5.1',
- credentialSlot: '',
- status: 'reserved',
- credentialJti: null,
- startedAt: new Date().toISOString(),
- leaseExpiresAt: null,
- completedAt: null,
- usageRequestId: null,
- })
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(
+ reservedSdkAttempt({ id: sdkAttemptId })
+ )
await authorizeLlmProviderAttempt(
claims({
recipeNamespace: 'sandbox-recipes',
recipeName: 'prompt-notify',
hostRefs: ['sandbox-recipes/prompt-notify'],
}),
- body({ pluginWorkloadSdkProviderAttemptId: sdkAttemptId }),
+ body({ pluginWorkloadSdkProviderAttemptId: sdkAttemptId, targetRef: 'codex-primary' }),
current
)
- expect(getPluginWorkloadSdkProviderAttempt).toHaveBeenCalledWith(
+ expect(lockPluginWorkloadSdkRecipe).toHaveBeenCalledWith(
+ expect.anything(),
+ 'sandbox-recipes',
+ 'prompt-notify'
+ )
+ expect(getPluginWorkloadSdkProviderAttemptForUpdate).toHaveBeenCalledWith(
sdkAttemptId,
expect.anything()
)
@@ -233,10 +254,21 @@ describe('authorizeLlmProviderAttempt', () => {
hostRef: 'sandbox-recipes/prompt-notify',
})
)
+ expect(promoteReservedOauthBrokerProviderAttempt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: sdkAttemptId,
+ model: 'gpt-5.1',
+ targetRef: 'codex-primary',
+ }),
+ expect.anything()
+ )
+ expect(promoteReservedOauthBrokerProviderAttempt.mock.invocationCallOrder[0]).toBeGreaterThan(
+ current.insertAttempt.mock.invocationCallOrder[0]!
+ )
})
it('rejects a Plugin Workload SDK attempt that does not match the reserved receipt', async () => {
- getPluginWorkloadSdkProviderAttempt.mockResolvedValue(null)
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(null)
await expect(
authorizeLlmProviderAttempt(
claims({
@@ -249,6 +281,73 @@ describe('authorizeLlmProviderAttempt', () => {
)
).rejects.toMatchObject({ code: 'no_grant' })
expect(current.insertAttempt).not.toHaveBeenCalled()
+ expect(promoteReservedOauthBrokerProviderAttempt).not.toHaveBeenCalled()
+ })
+
+ it('rejects a reserved SDK attempt whose model does not match the Codex request', async () => {
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(
+ reservedSdkAttempt({ model: 'gpt-5.4-mini' })
+ )
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body({ pluginWorkloadSdkProviderAttemptId: reservedSdkAttempt().id }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'no_grant' })
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ })
+
+ it('rejects a reserved SDK attempt whose targetRef does not match the authorize body', async () => {
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(reservedSdkAttempt())
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body({
+ pluginWorkloadSdkProviderAttemptId: reservedSdkAttempt().id,
+ targetRef: 'other-target',
+ }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'no_grant' })
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ })
+
+ it('rejects a host caller that presents a Plugin Workload SDK attempt id', async () => {
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims(),
+ body({ pluginWorkloadSdkProviderAttemptId: reservedSdkAttempt().id }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'no_grant' })
+ expect(getPluginWorkloadSdkProviderAttemptForUpdate).not.toHaveBeenCalled()
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ })
+
+ it('rejects linking after a spend outcome already exists', async () => {
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(reservedSdkAttempt())
+ pluginWorkloadSdkSpendOutcomeExists.mockResolvedValue(true)
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body({ pluginWorkloadSdkProviderAttemptId: reservedSdkAttempt().id }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'no_grant' })
+ expect(current.insertAttempt).not.toHaveBeenCalled()
})
it('rejects a stale requestHash', async () => {
diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
index 90c9787ec..a9ad1a214 100644
--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
@@ -806,6 +806,83 @@ describe('reissuePromptBridgeCredentialTicket', () => {
expect(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).not.toHaveBeenCalled()
})
+ it('returns a reservation-only Codex ticket and leaves the physical row reserved', async () => {
+ const policy = grant({
+ promptTargets: [
+ {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ },
+ ],
+ defaultTargetRef: 'codex-primary',
+ })
+ const policyHash = sdkDb.hashPromptTargetPolicy(policy)
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(policy)
+ vi.mocked(sdkDb.getInvocationById).mockResolvedValue(
+ invocation({
+ promptAuthorization: {
+ policyRevision: 1,
+ policyHash,
+ authorizedTargetRefs: ['codex-primary'],
+ },
+ })
+ )
+ vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockResolvedValue({
+ invocationId: 'inv-1',
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ attemptGeneration: 1,
+ method: 'promptBridge',
+ targetRefs: ['codex-primary'],
+ policyRevision: 1,
+ policyHash,
+ status: 'in_progress',
+ startedAt: '2026-06-09T00:00:00.000Z',
+ leaseExpiresAt: '2026-06-09T00:01:00.000Z',
+ completedAt: null,
+ })
+ vi.mocked(sdkDb.reservePluginWorkloadSdkProviderAttempt).mockResolvedValue({
+ id: '44444444-4444-4444-8444-444444444444',
+ invocationId: 'inv-1',
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ attemptGeneration: 1,
+ attemptIndex: 1,
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ status: 'reserved',
+ credentialJti: null,
+ startedAt: '2026-06-09T00:00:00.000Z',
+ leaseExpiresAt: '2026-06-09T00:01:00.000Z',
+ completedAt: null,
+ usageRequestId: null,
+ })
+
+ const result = await reissuePromptBridgeCredentialTicket({
+ claims: claims(),
+ invocationId: 'inv-1',
+ targetRef: 'codex-primary',
+ attemptGeneration: 1,
+ })
+
+ expect(result).toMatchObject({
+ ok: true,
+ value: {
+ invocationId: 'inv-1',
+ targetRef: 'codex-primary',
+ credentialTicket: '',
+ reservationOnly: true,
+ providerAttemptId: '44444444-4444-4444-8444-444444444444',
+ },
+ })
+ expect(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).not.toHaveBeenCalled()
+ expect(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).not.toHaveBeenCalled()
+ })
+
it('fails closed when policy changes or the invocation is terminal', async () => {
const policy = twoTargetGrant()
authorizedSuffix.policyHash = sdkDb.hashPromptTargetPolicy(policy)
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
index 0722cc96d..44f427fc8 100644
--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
@@ -752,4 +752,65 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
httpStatus: 403,
})
})
+
+ it('rejects Codex complete while the physical attempt is still reserved', async () => {
+ await expect(
+ finalizePromptBridgeInTransaction(
+ {
+ ...inputBase,
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ },
+ status: 'complete',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ dbWithRows(
+ [],
+ [],
+ {
+ id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ },
+ {
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ method: 'promptBridge',
+ status: 'in_progress',
+ },
+ {
+ id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credential_slot: '',
+ status: 'reserved',
+ }
+ ) as never
+ )
+ ).rejects.toMatchObject({
+ code: 'conflict',
+ httpStatus: 409,
+ })
+ })
})
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 47b9639eb..4649d7587 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.305",
+ "version": "0.1.306",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.305",
+ "version": "0.1.306",
"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 7b6e6ca12..aad4c677e 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.305",
+ "version": "0.1.306",
"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/codexSubscription.ts b/mcp-host/src/llm/codexSubscription.ts
index 704a57f60..d1b2cbc4b 100644
--- a/mcp-host/src/llm/codexSubscription.ts
+++ b/mcp-host/src/llm/codexSubscription.ts
@@ -23,6 +23,7 @@ export type CodexAttemptContext = {
attemptGeneration?: number
providerAttemptIndex?: number
pluginWorkloadSdkProviderAttemptId?: string
+ targetRef?: string
policyRevision: number
policyHash: string
hostRef?: string
@@ -263,6 +264,7 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {
...(context.pluginWorkloadSdkProviderAttemptId
? { pluginWorkloadSdkProviderAttemptId: context.pluginWorkloadSdkProviderAttemptId }
: {}),
+ ...(context.targetRef ? { targetRef: context.targetRef } : {}),
})
if (!('accessToken' in authorized)) {
// Bound: authorize returns ticket material only.
diff --git a/mcp-host/src/llm/providerAttemptAuthorizer.ts b/mcp-host/src/llm/providerAttemptAuthorizer.ts
index 0320957a0..a47b8c6ee 100644
--- a/mcp-host/src/llm/providerAttemptAuthorizer.ts
+++ b/mcp-host/src/llm/providerAttemptAuthorizer.ts
@@ -26,6 +26,7 @@ export type AuthorizeAttemptBody = {
userId?: string
budgetReservationId?: string
pluginWorkloadSdkProviderAttemptId?: string
+ targetRef?: string
}
export type ProviderAttemptAuthorizerOptions = {
diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
index bf90b157b..c0c451004 100644
--- a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
@@ -33,6 +33,9 @@ describe('readVerifiedSdkOnlyCodexBinding', () => {
).toBeNull()
expect(readVerifiedSdkOnlyCodexBinding(binding, 'gpt-5.4-mini')).toBeNull()
expect(readVerifiedSdkOnlyCodexBinding(undefined, model)).toBeNull()
+ expect(readVerifiedSdkOnlyCodexBinding({ ...binding, extra: 'drop-me' }, model)).toEqual(
+ binding
+ )
})
})
@@ -306,4 +309,41 @@ describe('Plugin Workload SDK bootstrap identity', () => {
expect(readSdkOnlyCodexBinding()).toEqual(binding)
replaceSdkOnlyCodexBinding(null)
})
+
+ it('echoes a sanitized five-field Codex binding instead of extra request keys', async () => {
+ const binding = {
+ connectionKey: 'team-plus',
+ catalogRevision: 4,
+ credentialRevision: 1,
+ model: 'gpt-5.6-luna',
+ bindingHash: computeCodexPolicyHash({
+ model: 'gpt-5.6-luna',
+ catalogRevision: 4,
+ credentialRevision: 1,
+ connectionKey: 'team-plus',
+ }),
+ }
+ const verify = vi.fn().mockResolvedValue({
+ ready: true,
+ contractVersion: 3,
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ policyReady: true,
+ policyState: 'active',
+ codexBindingReady: true,
+ })
+ const result = await configurePluginWorkloadSdkBootstrapIdentity(
+ {
+ capabilityFamily: 'promptBridge',
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ contractVersion: 3,
+ codexBinding: { ...binding, leaked: 'drop-me' },
+ },
+ { capabilityFamily: 'promptBridge', verify }
+ )
+ expect(result.codexBinding).toEqual(binding)
+ expect(result.codexBinding).not.toHaveProperty('leaked')
+ replaceSdkOnlyCodexBinding(null)
+ })
})
diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
index 1f5574a66..e90691836 100644
--- a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
@@ -137,7 +137,7 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(
policyState: proof.policyState,
policyReason: 'codex_execution_binding_missing',
message: 'Control API rejected the SDK-only Codex execution binding',
- ...(req.codexBinding ? { codexBinding: req.codexBinding } : {}),
+ ...(verifiedBinding ? { codexBinding: verifiedBinding } : {}),
}
}
deps.onConfigured?.({ provider: req.provider, defaultModel: model })
@@ -165,8 +165,8 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(
...(proof?.clientNotificationsPolicyReason !== undefined
? { clientNotificationsPolicyReason: proof.clientNotificationsPolicyReason }
: {}),
- ...(req.provider === 'codex-subscription' && req.codexBinding
- ? { codexBinding: req.codexBinding }
+ ...(req.provider === 'codex-subscription' && verifiedBinding
+ ? { codexBinding: verifiedBinding }
: {}),
}
}
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index d878fdbd5..d37fd60ec 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -161,6 +161,7 @@ function captureSdkOnlyCodexAttemptContext(
attemptGeneration: request.attemptGeneration,
providerAttemptIndex: ticket.providerAttemptIndex,
pluginWorkloadSdkProviderAttemptId: ticket.providerAttemptId,
+ targetRef: target.targetRef,
policyRevision: binding.catalogRevision,
policyHash: binding.bindingHash,
...(request.hostRef ? { hostRef: request.hostRef } : {}),
diff --git a/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
index c30042a3b..f849ae577 100644
--- a/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
+++ b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
@@ -77,11 +77,24 @@ export function verifySdkOnlyCodexBindingHash(
* This must run for every bootstrap request that carries a binding object;
* the request provider/version must not decide whether the hash is verified.
*/
+export function sanitizePluginWorkloadSdkCodexBindingProof(
+ binding: PluginWorkloadSdkCodexBindingProof
+): PluginWorkloadSdkCodexBindingProof {
+ return {
+ connectionKey: binding.connectionKey,
+ catalogRevision: binding.catalogRevision,
+ credentialRevision: binding.credentialRevision,
+ model: binding.model,
+ bindingHash: binding.bindingHash,
+ }
+}
+
export function readVerifiedSdkOnlyCodexBinding(
value: unknown,
model: string
): PluginWorkloadSdkCodexBindingProof | null {
if (!isPluginWorkloadSdkCodexBindingProof(value)) return null
if (value.model !== model) return null
- return verifySdkOnlyCodexBindingHash(value) ? value : null
+ if (!verifySdkOnlyCodexBindingHash(value)) return null
+ return sanitizePluginWorkloadSdkCodexBindingProof(value)
}
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 0836e6883..e1a752db9 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.320",
+ "version": "0.1.321",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.320",
+ "version": "0.1.321",
"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 aa001334c..dec1cd091 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.320",
+ "version": "0.1.321",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.ts
index 9061c9352..4e9474b84 100644
--- a/workflow-recipes/src/workflow/modelConfigHandler.ts
+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts
@@ -21,6 +21,10 @@ import {
isRunnableLlmModelId,
} from '@clerum/llm-providers'
import { createLogger } from '../observability/logger'
+import {
+ isPluginWorkloadSdkCodexBindingProof,
+ sanitizePluginWorkloadSdkCodexBindingProof,
+} from './sdkOnlyCodexBinding'
// ─── Types ──────────────────────────────────────────────────────────────
@@ -309,10 +313,8 @@ export class ModelConfigHandler {
model,
contractVersion: expectedContractVersion,
capabilityFamily,
- ...(result.body.codexBinding &&
- typeof result.body.codexBinding === 'object' &&
- !Array.isArray(result.body.codexBinding)
- ? { codexBinding: result.body.codexBinding }
+ ...(isPluginWorkloadSdkCodexBindingProof(result.body.codexBinding)
+ ? { codexBinding: sanitizePluginWorkloadSdkCodexBindingProof(result.body.codexBinding) }
: {}),
...(typeof result.body.policyReady === 'boolean'
? { policyReady: result.body.policyReady }
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index 7cc94d23d..f14f732ad 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -33,8 +33,7 @@ import {
import type { WorkflowRuntimePlan } from './runtimePlan'
import {
type PluginWorkloadSdkCodexBindingProof,
- isPluginWorkloadSdkCodexBindingProof,
- verifySdkOnlyCodexBindingHash,
+ readVerifiedSdkOnlyCodexBinding,
} from './sdkOnlyCodexBinding'
import { buildPluginWorkloadSdkTokenSecret } from './secretFactory'
import type { WorkflowConfig } from './types'
@@ -106,6 +105,13 @@ export type PluginWorkloadSdkProvisionerDeps = {
ensureMcpHostHeadlessService: (recipeName: string) => Promise<void>
createIfNotExists: (createFn: () => Promise<unknown>, label: string) => Promise<boolean>
safeDelete: (deleteFn: () => Promise<unknown>) => Promise<void>
+ resolveCodexBinding?: (input: {
+ provider: string
+ model: string
+ recipeName: string
+ recipeUid: string
+ runtimeScopeRecipeName: string
+ }) => PluginWorkloadSdkCodexBindingProof | null
}
/**
@@ -337,8 +343,19 @@ export class PluginWorkloadSdkProvisioner {
}
if (promptBridge && !mcpHostAgent) return 'failed'
+ const resolvedCodexBinding =
+ opts.codexBinding ??
+ (mcpHostAgent
+ ? (this.deps.resolveCodexBinding?.({
+ provider: mcpHostAgent.provider,
+ model: mcpHostAgent.model,
+ recipeName,
+ recipeUid,
+ runtimeScopeRecipeName,
+ }) ?? null)
+ : null)
const capabilityFamily = promptBridge ? 'promptBridge' : 'clientNotifications'
- const configureKey = `${readiness.uid}:${capabilityFamily}:${mcpHostAgent?.provider ?? 'none'}:${mcpHostAgent?.model ?? 'none'}:${opts.codexBinding?.bindingHash ?? 'none'}`
+ const configureKey = `${readiness.uid}:${capabilityFamily}:${mcpHostAgent?.provider ?? 'none'}:${mcpHostAgent?.model ?? 'none'}:${resolvedCodexBinding?.bindingHash ?? 'none'}`
try {
const wrcConfigureToken = await this.deps.tokenFactory.signWrcConfigureToken(
recipeName,
@@ -353,7 +370,7 @@ export class PluginWorkloadSdkProvisioner {
mcpHostEndpoint,
wrcConfigureToken,
'promptBridge',
- opts.codexBinding ?? null
+ resolvedCodexBinding
)
: await modelConfigHandler.configurePluginWorkloadSdkBootstrap(
undefined,
@@ -661,7 +678,5 @@ function parseEagerSdkBootstrapProof(
}
function parseCodexBindingProof(value: unknown): PluginWorkloadSdkCodexBindingProof | undefined {
- if (!isPluginWorkloadSdkCodexBindingProof(value)) return undefined
- if (!verifySdkOnlyCodexBindingHash(value)) return undefined
- return value
+ return readVerifiedSdkOnlyCodexBinding(value) ?? undefined
}
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
index 591874113..d0c182229 100644
--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
@@ -3,6 +3,7 @@ import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
import {
deriveSdkOnlyCodexBinding,
isPluginWorkloadSdkCodexBindingProof,
+ readVerifiedSdkOnlyCodexBinding,
verifySdkOnlyCodexBindingHash,
} from './sdkOnlyCodexBinding'
@@ -57,4 +58,22 @@ describe('deriveSdkOnlyCodexBinding', () => {
})
).toBeNull()
})
+
+ it('rebuilds a five-field proof and drops extra keys', () => {
+ const proof = {
+ connectionKey: 'team-plus',
+ catalogRevision: 3,
+ credentialRevision: 1,
+ model: 'gpt-5.6-luna',
+ bindingHash: HASH,
+ extra: true,
+ }
+ expect(readVerifiedSdkOnlyCodexBinding(proof)).toEqual({
+ connectionKey: 'team-plus',
+ catalogRevision: 3,
+ credentialRevision: 1,
+ model: 'gpt-5.6-luna',
+ bindingHash: HASH,
+ })
+ })
})
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
index 882ccb8b2..5e84f998e 100644
--- a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
@@ -50,6 +50,28 @@ export function verifySdkOnlyCodexBindingHash(
)
}
+export function sanitizePluginWorkloadSdkCodexBindingProof(
+ binding: PluginWorkloadSdkCodexBindingProof
+): PluginWorkloadSdkCodexBindingProof {
+ return {
+ connectionKey: binding.connectionKey,
+ catalogRevision: binding.catalogRevision,
+ credentialRevision: binding.credentialRevision,
+ model: binding.model,
+ bindingHash: binding.bindingHash,
+ }
+}
+
+export function readVerifiedSdkOnlyCodexBinding(
+ value: unknown,
+ model?: string
+): PluginWorkloadSdkCodexBindingProof | null {
+ if (!isPluginWorkloadSdkCodexBindingProof(value)) return null
+ if (model !== undefined && value.model !== model) return null
+ if (!verifySdkOnlyCodexBindingHash(value)) return null
+ return sanitizePluginWorkloadSdkCodexBindingProof(value)
+}
+
/**
* Derive the sanitized v3 Codex execution proof from one WRC snapshot.
* Returns null when the grant is unassigned, the catalog is not executable,
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 19132ecff..1bfb7d314 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -926,6 +926,15 @@ export class WorkflowReconciler {
ensureMcpHostHeadlessService: recipeName => this.ensureMcpHostHeadlessService(recipeName),
createIfNotExists: (createFn, label) => this.createIfNotExists(createFn, label),
safeDelete: deleteFn => this.safeDelete(deleteFn),
+ resolveCodexBinding: ({ provider, model, recipeName, recipeUid, runtimeScopeRecipeName }) => {
+ const context = this.resolveCodexContext(recipeUid, recipeName, runtimeScopeRecipeName)
+ return deriveSdkOnlyCodexBinding({
+ provider,
+ model,
+ connectionKey: context.connectionKey,
+ configMap: this.lastCodexConfigMap,
+ })
+ },
})
}
diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts
index 3966e4ae7..d52bf034e 100644
--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts
+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts
@@ -221,7 +221,7 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {
contractVersion: 3,
policyReady: true,
policyState: 'active',
- codexBinding: binding,
+ codexBinding: { ...binding, leaked: 'drop-me' },
},
})),
}
@@ -243,6 +243,7 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {
model: 'gpt-5.1',
codexBinding: binding,
})
+ expect(result.body.codexBinding).not.toHaveProperty('leaked')
expect(mcpHost.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(
'http://mcp-host:8090',
'wrc-token',