Skip to content

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

TypeScript

fix(control-api): persist Grok SDK grants and reject mixed brokers

Jose Gabriel Ramirez Encinas7a6d7591f2e3
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index ea680ad61..655d61be9 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.560",
+ "version": "0.1.561",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.560",
+ "version": "0.1.561",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 58f7c58a3..c295d8b72 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.560",
+ "version": "0.1.561",
"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/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.ts
index 3079b07d6..5a1de39f6 100644
--- a/control-api/src/routes/admin/hostSpecValidation.ts
+++ b/control-api/src/routes/admin/hostSpecValidation.ts
@@ -13,6 +13,12 @@ import {
isCodexUnassignedConnectionKey,
readHostCodexConnectionRef,
} from '../../services/codexSubscriptionConnection.js'
+import { isGrokAssignmentAllowed } from '../../services/grokSubscriptionCatalog.js'
+import {
+ GROK_UNASSIGNED_CONNECTION_KEY,
+ isGrokUnassignedConnectionKey,
+ readHostGrokConnectionRef,
+} from '../../services/grokSubscriptionConnection.js'
import {
getModelAllowlistState as getModelAllowlistStateDefault,
isModelAllowed as isModelAllowedDefault,
@@ -62,6 +68,16 @@ function isCodexSubscriptionEnabled(): boolean {
return process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED === 'true'
}
+function isGrokSubscriptionEnabled(): boolean {
+ return process.env.CONTROL_API_GROK_SUBSCRIPTION_ENABLED === 'true'
+}
+
+function oauthBrokerFlagEnabled(provider: string): boolean {
+ if (provider === 'codex-subscription') return isCodexSubscriptionEnabled()
+ if (provider === 'grok-subscription') return isGrokSubscriptionEnabled()
+ return true
+}
+
type HostLlmTarget = {
provider: string
field: string
@@ -103,16 +119,23 @@ function validateCodexBrokerAdmission(
spec: Record<string, unknown>
): { errors: Array<{ field: string; message: string }> } | null {
const targets = collectHostLlmTargets(spec)
- const enabled = isCodexSubscriptionEnabled()
for (const target of targets) {
- if (target.provider !== 'codex-subscription') continue
- if (!enabled) {
+ if (
+ !isLlmProviderId(target.provider) ||
+ PROVIDER_AUTH_MODE[target.provider] !== 'oauth-broker'
+ ) {
+ continue
+ }
+ if (!oauthBrokerFlagEnabled(target.provider)) {
+ const flag =
+ target.provider === 'grok-subscription'
+ ? 'CONTROL_API_GROK_SUBSCRIPTION_ENABLED'
+ : 'CONTROL_API_CODEX_SUBSCRIPTION_ENABLED'
return {
errors: [
{
field: target.field,
- message:
- 'provider "codex-subscription" is disabled (set CONTROL_API_CODEX_SUBSCRIPTION_ENABLED=true)',
+ message: `provider "${target.provider}" is disabled (set ${flag}=true)`,
},
],
}
@@ -204,7 +227,9 @@ export function createHostValidationDeps(db: DbClient): HostSpecValidationDeps {
isModelAllowed: (provider, model, connectionRef) =>
provider === 'codex-subscription'
? isCodexAssignmentAllowed(db, readHostCodexConnectionRef(connectionRef), model)
- : isModelAllowedDefault(provider, model, db),
+ : provider === 'grok-subscription'
+ ? isGrokAssignmentAllowed(db, readHostGrokConnectionRef(connectionRef), model)
+ : isModelAllowedDefault(provider, model, db),
getModelAllowlistState: (provider, model) => getModelAllowlistStateDefault(provider, model, db),
}
}
@@ -379,13 +404,23 @@ export async function validateHostSpec(
}
}
const connectionRef =
- provider === 'codex-subscription' ? resolvedCodexConnectionRef(model) : undefined
+ provider === 'codex-subscription'
+ ? resolvedCodexConnectionRef(model)
+ : provider === 'grok-subscription'
+ ? readHostGrokConnectionRef(
+ typeof model.connectionRef === 'string' ? model.connectionRef : undefined
+ )
+ : undefined
if (provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)) {
// Persist the sentinel so empty and unassigned are not two Host states.
model.connectionRef = CODEX_UNASSIGNED_CONNECTION_KEY
}
+ if (provider === 'grok-subscription' && isGrokUnassignedConnectionKey(connectionRef)) {
+ model.connectionRef = GROK_UNASSIGNED_CONNECTION_KEY
+ }
const skipCodexAllowlist =
- provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)
+ (provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)) ||
+ (provider === 'grok-subscription' && isGrokUnassignedConnectionKey(connectionRef))
const allowed = skipCodexAllowlist
? true
: await deps.isModelAllowed(provider, name, connectionRef)
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index 4c4ff34cb..f18f474e2 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -20,6 +20,11 @@ import {
assertCodexConnectionKey,
isCodexUnassignedConnectionKey,
} from '../../services/codexSubscriptionConnection.js'
+import { isGrokAssignmentAllowed } from '../../services/grokSubscriptionCatalog.js'
+import {
+ assertGrokConnectionKey,
+ isGrokUnassignedConnectionKey,
+} from '../../services/grokSubscriptionConnection.js'
import { listEnabledModelsWithStaleForProvider } from '../../services/llmAllowedModels.js'
import {
MAX_ALLOWLIST_ENTRY_LENGTH,
@@ -296,12 +301,20 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
// a previously stored Codex target can be edited without inventing a
// grant. Spend still fail-closes at authorize until the operator picks
// a live connection. Malformed keys stay rejected.
- if (connectionRef && !isCodexUnassignedConnectionKey(connectionRef)) {
+ const unassigned =
+ provider === 'grok-subscription'
+ ? isGrokUnassignedConnectionKey(connectionRef)
+ : isCodexUnassignedConnectionKey(connectionRef)
+ if (connectionRef && !unassigned) {
try {
- assertCodexConnectionKey(connectionRef)
+ if (provider === 'grok-subscription') assertGrokConnectionKey(connectionRef)
+ else assertCodexConnectionKey(connectionRef)
} catch {
res.status(400).json({
- error: `promptTargets[${index}].connectionRef must name an existing Codex subscription connection`,
+ error:
+ provider === 'grok-subscription'
+ ? `promptTargets[${index}].connectionRef must name an existing Grok subscription connection`
+ : `promptTargets[${index}].connectionRef must name an existing Codex subscription connection`,
})
return null
}
@@ -342,6 +355,13 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
...(brokerBacked ? { connectionRef } : {}),
})
}
+ const brokerProviders = new Set(
+ targets.filter(target => isBrokerBackedProvider(target.provider)).map(target => target.provider)
+ )
+ if (brokerProviders.size > 1) {
+ res.status(400).json({ error: 'oauth_broker_provider_conflict' })
+ return null
+ }
const brokerKeys = new Set(
targets
.filter(target => isBrokerBackedProvider(target.provider))
@@ -388,6 +408,7 @@ async function publishPromptBridgeGrantIdentity(input: {
recipeNamespace: string
recipeName: string
nextRef: string
+ provider?: string
}): Promise<{ error?: { status: number; error: string } }> {
let next = input.nextRef
if (!next) {
@@ -403,11 +424,11 @@ async function publishPromptBridgeGrantIdentity(input: {
} catch (err) {
log.error(
{ err, recipeNamespace: input.recipeNamespace, recipeName: input.recipeName },
- 'failed to read WorkflowRecipe before publishing Codex grant identity'
+ 'failed to read WorkflowRecipe before publishing grant identity'
)
return { error: { status: 503, error: 'recipe_annotation_publish_failed' } }
}
- if (recipeAgent === 'codex-subscription') {
+ if (recipeAgent === 'codex-subscription' || recipeAgent === 'grok-subscription') {
return {}
}
next = 'unassigned'
@@ -418,6 +439,7 @@ async function publishPromptBridgeGrantIdentity(input: {
namespace: input.recipeNamespace,
name: input.recipeName,
next,
+ ...(input.provider ? { provider: input.provider } : {}),
})
} catch (err) {
if (err instanceof RecipeCodexGrantIdentityError) {
@@ -601,20 +623,24 @@ export function createAdminPluginWorkloadSdkRouter(
// before (serialization only, no accept/reject change): a disabled model
// reachable solely through `allowed_models` (no promptTarget) is a
// PRE-EXISTING gap, out of R1-H3 scope.
- const brokerConnectionRef =
- promptTargets.find(
- target =>
- isBrokerBackedProvider(target.provider) &&
- target.connectionRef &&
- !isCodexUnassignedConnectionKey(target.connectionRef)
- )?.connectionRef ?? ''
- const hasBrokerTarget = promptTargets.some(target => isBrokerBackedProvider(target.provider))
+ const brokerTargets = promptTargets.filter(target => isBrokerBackedProvider(target.provider))
+ const brokerProviders = [...new Set(brokerTargets.map(target => target.provider))]
+ const brokerTarget = brokerTargets.find(
+ target =>
+ target.connectionRef &&
+ !(target.provider === 'grok-subscription'
+ ? isGrokUnassignedConnectionKey(target.connectionRef)
+ : isCodexUnassignedConnectionKey(target.connectionRef))
+ )
+ const brokerConnectionRef = brokerTarget?.connectionRef ?? ''
+ const hasBrokerTarget = brokerTargets.length > 0
if (capabilityFamily === 'promptBridge' && deps.gateway && hasBrokerTarget) {
const published = await publishPromptBridgeGrantIdentity({
gateway: deps.gateway,
recipeNamespace,
recipeName,
nextRef: brokerConnectionRef,
+ provider: brokerTarget?.provider ?? brokerProviders[0],
})
if (published.error) {
res.status(published.error.status).json({ error: published.error.error })
@@ -645,13 +671,23 @@ export function createAdminPluginWorkloadSdkRouter(
for (const target of promptTargets) {
if (!isBrokerBackedProvider(target.provider)) continue
const connectionRef = target.connectionRef ?? ''
- if (!connectionRef || isCodexUnassignedConnectionKey(connectionRef)) {
+ const unassigned =
+ target.provider === 'grok-subscription'
+ ? isGrokUnassignedConnectionKey(connectionRef)
+ : isCodexUnassignedConnectionKey(connectionRef)
+ if (!connectionRef || unassigned) {
continue
}
- const allowed = await isCodexAssignmentAllowed(db, connectionRef, target.model)
+ const allowed =
+ target.provider === 'grok-subscription'
+ ? await isGrokAssignmentAllowed(db, connectionRef, target.model)
+ : await isCodexAssignmentAllowed(db, connectionRef, target.model)
if (!allowed) {
throw new GrantModelGateError({
- error: 'codex_connection_not_allowed',
+ error:
+ target.provider === 'grok-subscription'
+ ? 'grok_connection_not_allowed'
+ : 'codex_connection_not_allowed',
connectionRef: target.connectionRef ?? '',
model: target.model,
})
@@ -870,20 +906,22 @@ export function createAdminPluginWorkloadSdkRouter(
}
if (deps.gateway) {
const remaining = await listGrants({ recipeNamespace, recipeName })
- const remainingRef =
- remaining
- .flatMap(grant => grant.promptTargets)
- .find(
- target =>
- isBrokerBackedProvider(target.provider) &&
- target.connectionRef &&
- !isCodexUnassignedConnectionKey(target.connectionRef)
- )?.connectionRef ?? ''
+ const remainingTarget = remaining
+ .flatMap(grant => grant.promptTargets)
+ .find(
+ target =>
+ isBrokerBackedProvider(target.provider) &&
+ target.connectionRef &&
+ !(target.provider === 'grok-subscription'
+ ? isGrokUnassignedConnectionKey(target.connectionRef)
+ : isCodexUnassignedConnectionKey(target.connectionRef))
+ )
const published = await publishPromptBridgeGrantIdentity({
gateway: deps.gateway,
recipeNamespace,
recipeName,
- nextRef: remainingRef,
+ nextRef: remainingTarget?.connectionRef ?? '',
+ provider: remainingTarget?.provider,
})
if (published.error) {
res.status(published.error.status).json({ error: published.error.error })
diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.ts
index e3d92157e..e754477b7 100644
--- a/control-api/src/routes/admin/recipes.ts
+++ b/control-api/src/routes/admin/recipes.ts
@@ -34,6 +34,7 @@ import { K8sNotFoundError } from '../../services/resourceService.js'
import { invalidSecretDataKeyReason } from '../../services/secretKeys.js'
import {
SUBSCRIPTION_CONNECTION_REF_ANNOTATION,
+ collectRecipeOauthBrokerProviders,
readSubscriptionConnectionRef,
} from '../../services/subscriptionGrantIdentity.js'
import {
@@ -884,6 +885,14 @@ function validateRecipeBody(body: RecipeBody): ValidationError[] {
return errors // no point checking spec fields if spec is invalid
}
errors.push(...validateWorkflowRecipeLimits(body.spec))
+ const brokerIds = collectRecipeOauthBrokerProviders(body.spec as Record<string, unknown>)
+ if (brokerIds.length > 1) {
+ errors.push({
+ field: 'spec.agent.provider',
+ message:
+ 'a WorkflowRecipe may declare at most one oauth-broker provider across agent and steps',
+ })
+ }
const runRetention = body.spec.runRetention
if (runRetention !== undefined) {
diff --git a/control-api/src/services/recipeCodexGrantIdentity.ts b/control-api/src/services/recipeCodexGrantIdentity.ts
index 6f1f7050a..7ff807696 100644
--- a/control-api/src/services/recipeCodexGrantIdentity.ts
+++ b/control-api/src/services/recipeCodexGrantIdentity.ts
@@ -7,6 +7,11 @@ import {
getSafeCodexSubscriptionConnection,
isCodexUnassignedConnectionKey,
} from './codexSubscriptionConnection.js'
+import {
+ GROK_UNASSIGNED_CONNECTION_KEY,
+ getSafeGrokSubscriptionConnection,
+ isGrokUnassignedConnectionKey,
+} from './grokSubscriptionConnection.js'
import { K8sConflictError } from './resourceService.js'
import {
SUBSCRIPTION_CONNECTION_REF_ANNOTATION,
@@ -60,17 +65,26 @@ export async function publishRecipeGrantIdentity(input: {
name: string
next: string
db?: DbClient
+ provider?: string
}): Promise<{ published: string; resourceVersion?: string; noop: boolean }> {
- const next = isCodexUnassignedConnectionKey(input.next)
- ? CODEX_UNASSIGNED_CONNECTION_KEY
- : input.next.trim()
- if (next !== CODEX_UNASSIGNED_CONNECTION_KEY) {
- const live = await getSafeCodexSubscriptionConnection(input.db ?? pool, next)
+ const grok = input.provider === 'grok-subscription'
+ const unassignedKey = grok ? GROK_UNASSIGNED_CONNECTION_KEY : CODEX_UNASSIGNED_CONNECTION_KEY
+ const next = grok
+ ? isGrokUnassignedConnectionKey(input.next) || !input.next.trim()
+ ? GROK_UNASSIGNED_CONNECTION_KEY
+ : input.next.trim()
+ : isCodexUnassignedConnectionKey(input.next)
+ ? CODEX_UNASSIGNED_CONNECTION_KEY
+ : input.next.trim()
+ if (next !== unassignedKey) {
+ const live = grok
+ ? await getSafeGrokSubscriptionConnection(input.db ?? pool, next)
+ : await getSafeCodexSubscriptionConnection(input.db ?? pool, next)
if (!live) {
throw new RecipeCodexGrantIdentityError(
422,
- 'codex_connection_not_allowed',
- 'Codex grant is not a live connection'
+ grok ? 'grok_connection_not_allowed' : 'codex_connection_not_allowed',
+ grok ? 'Grok grant is not a live connection' : 'Codex grant is not a live connection'
)
}
}
@@ -93,16 +107,26 @@ export async function publishRecipeGrantIdentity(input: {
}
const annotations = stringMap(current.metadata?.annotations)
- const previous = readRecipeGrantIdentity(annotations)
- if (previous === next) {
+ const previous = readSubscriptionConnectionRef({
+ provider: grok ? 'grok-subscription' : 'codex-subscription',
+ annotations,
+ })
+ if (previous.ok && previous.connectionKey === next) {
return { published: next, resourceVersion: current.metadata?.resourceVersion, noop: true }
}
- const nextAnnotations = {
- ...annotations,
- [CODEX_CONNECTION_REF_ANNOTATION]: next === CODEX_UNASSIGNED_CONNECTION_KEY ? '' : next,
- [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: next === CODEX_UNASSIGNED_CONNECTION_KEY ? '' : next,
- }
+ const cleared = next === unassignedKey ? '' : next
+ const nextAnnotations = grok
+ ? {
+ ...annotations,
+ [CODEX_CONNECTION_REF_ANNOTATION]: '',
+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: cleared,
+ }
+ : {
+ ...annotations,
+ [CODEX_CONNECTION_REF_ANNOTATION]: cleared,
+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: cleared,
+ }
const spec = asRecord(current.spec) ?? {}
const labels = stringMap(current.metadata?.labels)
try {
diff --git a/control-api/test/hostSpecValidation.codexSubscription.test.ts b/control-api/test/hostSpecValidation.codexSubscription.test.ts
index 69d190824..725ef9e8b 100644
--- a/control-api/test/hostSpecValidation.codexSubscription.test.ts
+++ b/control-api/test/hostSpecValidation.codexSubscription.test.ts
@@ -9,9 +9,21 @@ const crdsDir = resolve(dirname(fileURLToPath(import.meta.url)), '../../charts/c
afterEach(() => {
delete process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED
+ delete process.env.CONTROL_API_GROK_SUBSCRIPTION_ENABLED
})
describe('codex-subscription Host admission', () => {
+ it('rejects a Grok target when the Grok management flag is absent or false', async () => {
+ const isModelAllowed = vi.fn().mockResolvedValue(true)
+ const res = await validateHostSpec(
+ { model: { provider: 'grok-subscription', name: 'grok-4.6' } },
+ { isModelAllowed }
+ )
+ expect(res).not.toBeNull()
+ expect(res!.errors[0].message).toMatch(/CONTROL_API_GROK_SUBSCRIPTION_ENABLED/)
+ expect(isModelAllowed).not.toHaveBeenCalled()
+ })
+
it('rejects a Codex target when the management flag is absent or false', async () => {
const isModelAllowed = vi.fn().mockResolvedValue(true)
const res = await validateHostSpec(
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index 2791fccf8..db31268c8 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -4,6 +4,7 @@ import request from 'supertest'
import { pool } from '../src/db.js'
import { createAdminPluginWorkloadSdkRouter } from '../src/routes/admin/pluginWorkloadSdk.js'
import { isCodexAssignmentAllowed } from '../src/services/codexSubscriptionCatalog.js'
+import { isGrokAssignmentAllowed } from '../src/services/grokSubscriptionCatalog.js'
import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'
import { checkAndIncrement } from '../src/services/rateLimiterService.js'
import {
@@ -56,6 +57,10 @@ vi.mock('../src/services/codexSubscriptionCatalog.js', () => ({
isCodexAssignmentAllowed: vi.fn(),
}))
+vi.mock('../src/services/grokSubscriptionCatalog.js', () => ({
+ isGrokAssignmentAllowed: vi.fn(),
+}))
+
vi.mock('../src/services/recipeCodexGrantIdentity.js', async () => {
const actual = await vi.importActual<
typeof import('../src/services/recipeCodexGrantIdentity.js')
@@ -125,6 +130,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)
+ vi.mocked(isGrokAssignmentAllowed).mockReset()
+ vi.mocked(isGrokAssignmentAllowed).mockResolvedValue(false)
getResource.mockReset()
getResource.mockResolvedValue({ spec: { pluginWorkloadSdk: {} } })
updateResource.mockReset()
@@ -647,6 +654,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
namespace: 'sandbox-recipes',
name: 'sdk-recipe',
next: 'team-plus',
+ provider: 'codex-subscription',
})
expect(publishRecipeGrantIdentity.mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(sdkDb.upsertGrant).mock.invocationCallOrder[0]!
@@ -746,6 +754,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
namespace: 'sandbox-recipes',
name: 'sdk-recipe',
next: 'unassigned',
+ provider: 'codex-subscription',
})
expect(sdkDb.upsertGrant).toHaveBeenCalled()
})
@@ -765,6 +774,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
namespace: 'sandbox-recipes',
name: 'sdk-recipe',
next: 'unassigned',
+ provider: 'codex-subscription',
})
expect(sdkDb.upsertGrant).toHaveBeenCalled()
})
@@ -836,6 +846,97 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
})
})
+ describe('grok-subscription promptTargets', () => {
+ const grokGrantBody = {
+ ...validGrantBody,
+ provider: 'grok-subscription',
+ allowedModels: ['grok-4.6'],
+ promptTargets: [
+ {
+ targetRef: 'grok-primary',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ credentialSlot: '',
+ connectionRef: 'team-grok',
+ },
+ ],
+ defaultTargetRef: 'grok-primary',
+ }
+
+ it('accepts a Grok target bound to a permitted Grok grant', async () => {
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-grok' } as never)
+ vi.mocked(isGrokAssignmentAllowed).mockResolvedValue(true)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send(grokGrantBody)
+ expect(res.status).toBe(200)
+ expect(isGrokAssignmentAllowed).toHaveBeenCalledWith(
+ expect.anything(),
+ 'team-grok',
+ 'grok-4.6'
+ )
+ expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()
+ expect(publishRecipeGrantIdentity).toHaveBeenCalledWith({
+ gateway: { getResource, updateResource },
+ namespace: 'sandbox-recipes',
+ name: 'sdk-recipe',
+ next: 'team-grok',
+ provider: 'grok-subscription',
+ })
+ })
+
+ it('fails closed when the Grok grant is unknown or does not offer the model', async () => {
+ vi.mocked(isGrokAssignmentAllowed).mockResolvedValue(false)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send(grokGrantBody)
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({
+ error: 'grok_connection_not_allowed',
+ connectionRef: 'team-grok',
+ model: 'grok-4.6',
+ })
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects reserved deployment-default on a Grok target', async () => {
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...grokGrantBody,
+ promptTargets: [
+ { ...grokGrantBody.promptTargets[0]!, connectionRef: 'deployment-default' },
+ ],
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toContain('Grok subscription connection')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects mixed Codex and Grok promptTargets', async () => {
+ vi.mocked(isGrokAssignmentAllowed).mockResolvedValue(true)
+ vi.mocked(isCodexAssignmentAllowed).mockResolvedValue(true)
+ const res = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...grokGrantBody,
+ promptTargets: [
+ grokGrantBody.promptTargets[0]!,
+ {
+ targetRef: 'codex-fallback',
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ credentialSlot: '',
+ connectionRef: 'team-plus',
+ },
+ ],
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('oauth_broker_provider_conflict')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+ })
+
// ── Pieza D: no-worsening tolerance for grant `allowed_models` (G3) ─────────
describe('no-worsening tolerance', () => {
const buildAppWithEmit = (emit: (event: unknown) => void) => {
diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.ts
index ffe9d38fc..baf06c8a6 100644
--- a/control-api/test/routes.adminRecipes.test.ts
+++ b/control-api/test/routes.adminRecipes.test.ts
@@ -275,6 +275,26 @@ describe.sequential('routes/admin/recipes', () => {
})
})
+ it('POST /admin/recipes — rejects mixed oauth-broker providers on agent and steps', async () => {
+ const res = await api.post('/admin/recipes').send({
+ metadata: { name: 'mixed-broker' },
+ spec: {
+ agent: { provider: 'grok-subscription', model: 'grok-4.6' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [
+ {
+ id: 'draft',
+ instruction: 'Write',
+ timeoutSeconds: 600,
+ agent: { provider: 'codex-subscription', model: 'gpt-5.1' },
+ },
+ ],
+ },
+ })
+ expect(res.status).toBe(422)
+ expect(res.body.errors[0].message).toMatch(/at most one oauth-broker/)
+ })
+
it('POST /admin/recipes — rejects a Codex recipe without a named grant', async () => {
const res = await api
.post('/admin/recipes')
diff --git a/control-api/test/services.recipeCodexGrantIdentity.test.ts b/control-api/test/services.recipeCodexGrantIdentity.test.ts
index 0113d8cc4..f64e4971b 100644
--- a/control-api/test/services.recipeCodexGrantIdentity.test.ts
+++ b/control-api/test/services.recipeCodexGrantIdentity.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { getSafeCodexSubscriptionConnection } from '../src/services/codexSubscriptionConnection.js'
+import { getSafeGrokSubscriptionConnection } from '../src/services/grokSubscriptionConnection.js'
import {
publishRecipeGrantIdentity,
readRecipeGrantIdentity,
@@ -16,6 +17,16 @@ vi.mock('../src/services/codexSubscriptionConnection.js', async () => {
}
})
+vi.mock('../src/services/grokSubscriptionConnection.js', async () => {
+ const actual = await vi.importActual<
+ typeof import('../src/services/grokSubscriptionConnection.js')
+ >('../src/services/grokSubscriptionConnection.js')
+ return {
+ ...actual,
+ getSafeGrokSubscriptionConnection: vi.fn(),
+ }
+})
+
const liveGrant = {
id: '11111111-1111-1111-1111-111111111111',
connectionKey: 'team-plus',
@@ -32,6 +43,11 @@ describe('recipe Codex grant identity', () => {
updateResource.mockReset()
vi.mocked(getSafeCodexSubscriptionConnection).mockReset()
vi.mocked(getSafeCodexSubscriptionConnection).mockResolvedValue(liveGrant as never)
+ vi.mocked(getSafeGrokSubscriptionConnection).mockReset()
+ vi.mocked(getSafeGrokSubscriptionConnection).mockResolvedValue({
+ ...liveGrant,
+ connectionKey: 'team-grok',
+ } as never)
})
it('reads empty and blank annotations as unassigned', () => {
@@ -145,4 +161,55 @@ describe('recipe Codex grant identity', () => {
})
).rejects.toMatchObject({ status: 409, error: 'conflict' })
})
+
+ it('publishes a Grok grant on the canonical annotation and clears the Codex alias', async () => {
+ getResource.mockResolvedValue({
+ metadata: {
+ resourceVersion: '4',
+ annotations: { 'clerum.io/codex-connection-ref': 'leftover' },
+ },
+ spec: { agent: { provider: 'grok-subscription' } },
+ })
+ await expect(
+ publishRecipeGrantIdentity({
+ gateway: { getResource, updateResource },
+ namespace: 'sandbox-recipes',
+ name: 'grok-recipe',
+ next: 'team-grok',
+ provider: 'grok-subscription',
+ })
+ ).resolves.toMatchObject({ published: 'team-grok', noop: false })
+ expect(getSafeGrokSubscriptionConnection).toHaveBeenCalledWith(expect.anything(), 'team-grok')
+ expect(getSafeCodexSubscriptionConnection).not.toHaveBeenCalled()
+ expect(updateResource).toHaveBeenCalledWith(
+ 'workflowrecipes',
+ 'grok-recipe',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ annotations: {
+ 'clerum.io/codex-connection-ref': '',
+ 'clerum.io/subscription-connection-ref': 'team-grok',
+ },
+ }),
+ }),
+ 'sandbox-recipes'
+ )
+ })
+
+ it('rejects a named Grok publish when the Grok grant is not live', async () => {
+ vi.mocked(getSafeGrokSubscriptionConnection).mockResolvedValueOnce(null)
+ await expect(
+ publishRecipeGrantIdentity({
+ gateway: { getResource, updateResource },
+ namespace: 'sandbox-recipes',
+ name: 'grok-recipe',
+ next: 'team-grok',
+ provider: 'grok-subscription',
+ })
+ ).rejects.toMatchObject({
+ status: 422,
+ error: 'grok_connection_not_allowed',
+ })
+ expect(getResource).not.toHaveBeenCalled()
+ })
})
diff --git a/packages/codex-catalog-projection/index.test.cjs b/packages/codex-catalog-projection/index.test.cjs
index d533588f0..e7a2daea6 100644
--- a/packages/codex-catalog-projection/index.test.cjs
+++ b/packages/codex-catalog-projection/index.test.cjs
@@ -557,7 +557,9 @@ test('toEligibleGrokPolicyBinding mints only for an assigned eligible Grok model
model: 'grok-4.6',
})
assert.equal(projection.toEligibleGrokPolicyBinding(cm, 'unassigned', 'grok-4.6').reason, 'unassigned')
+ assert.equal(projection.toEligibleGrokPolicyBinding(cm, 'unassigned', 'grok-4.6').binding, null)
assert.equal(projection.toEligibleGrokPolicyBinding(cm, '', 'grok-4.6').reason, 'unassigned')
+ assert.equal(projection.toEligibleGrokPolicyBinding(cm, '', 'grok-4.6').binding, null)
assert.equal(
projection.toEligibleGrokPolicyBinding(cm, 'team-grok', 'missing-model').binding,
null
diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.sh
index 2bbcbbe32..7ec27e0e6 100755
--- a/scripts/tests/test-codex-subscription-t0.sh
+++ b/scripts/tests/test-codex-subscription-t0.sh
@@ -227,6 +227,7 @@ run_group "control-api" "control-api" \
"test/services.codexSubscriptionConnection.test.ts" \
"test/services.llmAllowedModelsConfigMap.test.ts" \
"test/services.codexSubscriptionOAuth.test.ts" \
+ "test/services.grokSubscriptionOAuth.test.ts" \
"test/services.codexSubscriptionCatalog.test.ts" \
"test/services.llmProviderAttemptAuthorizer.test.ts" \
"test/services.llmProviderAttemptAuthorizer.grok.test.ts" \
@@ -283,6 +284,7 @@ run_group "workflow-runtime-core" "packages/workflow-runtime-core" \
run_group "workflow-recipes" "workflow-recipes" \
"src/workflow/codexExecutionProjection.test.ts" \
+ "src/workflow/codexRecipeVerdict.test.ts" \
"src/workflow/workflowReconciler.codexScopeProvenance.test.ts" \
"src/workflow/llmAllowedModelsSnapshot.test.ts" \
"src/workflow/networkPolicyFactory.codex.test.ts" \
diff --git a/scripts/tests/test-grok-subscription-t0.sh b/scripts/tests/test-grok-subscription-t0.sh
index b9e6c3073..2031a7d32 100755
--- a/scripts/tests/test-grok-subscription-t0.sh
+++ b/scripts/tests/test-grok-subscription-t0.sh
@@ -89,10 +89,15 @@ require_file control-api/test/services.grokProviderAttemptRedemption.test.ts
require_file control-api/test/db.grokSubscriptionMigration.test.ts
require_file control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
require_file control-api/test/subscriptionGrantIdentity.test.ts
+require_file control-api/test/routes.adminPluginWorkloadSdk.test.ts
+require_file control-api/test/services.recipeCodexGrantIdentity.test.ts
+require_file control-api/test/hostSpecValidation.codexSubscription.test.ts
require_file scripts/tests/test-grok-llm-proxy-deploy-contract.sh
require_file tests/e2e/fixtures/grok-subscription/sanitized-upstream-contract.json
require_file workflow-recipes/src/workflow/codexRecipeVerdict.test.ts
require_file workflow-recipes/src/workflow/sdkOnlyGrokBinding.test.ts
+require_file workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts
+require_file workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts
require_file mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
require_file packages/codex-catalog-projection/index.test.cjs
require_file control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsx
@@ -130,7 +135,7 @@ run_group "grok-llm-proxy freeze+origin" \
bash -lc "cd '${ROOT}/grok-llm-proxy' && npx vitest run test/contractFreeze.test.ts test/originPolicy.test.ts --no-file-parallelism"
run_group "control-api grok grant/oauth/redeem/authorize" \
- bash -lc "cd '${ROOT}/control-api' && npx vitest run test/db.grokSubscriptionMigration.test.ts test/services.grokSubscriptionConnection.test.ts test/services.grokSubscriptionOAuth.test.ts test/services.grokSubscriptionCatalog.test.ts test/services.grokProviderAttemptRedemption.test.ts test/services.llmProviderAttemptAuthorizer.grok.test.ts test/subscriptionGrantIdentity.test.ts --no-file-parallelism"
+ bash -lc "cd '${ROOT}/control-api' && npx vitest run test/db.grokSubscriptionMigration.test.ts test/services.grokSubscriptionConnection.test.ts test/services.grokSubscriptionOAuth.test.ts test/services.grokSubscriptionCatalog.test.ts test/services.grokProviderAttemptRedemption.test.ts test/services.llmProviderAttemptAuthorizer.grok.test.ts test/subscriptionGrantIdentity.test.ts test/routes.adminPluginWorkloadSdk.test.ts test/services.recipeCodexGrantIdentity.test.ts test/hostSpecValidation.codexSubscription.test.ts --no-file-parallelism"
run_group "workflow-recipes grok SDK" \
bash -lc "cd '${ROOT}/workflow-recipes' && npx vitest run src/workflow/codexRecipeVerdict.test.ts src/workflow/sdkOnlyGrokBinding.test.ts src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts src/reconciler/pluginWorkloadSdkValidator.test.ts tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts --no-file-parallelism"