Skip to content

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

TypeScript

fix: keep canonical-only Codex grants and lock Grok SDK/redeem paths

Jose Gabriel Ramirez Encinas266672dd0484
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 9d9c6d7c6..88835d502 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -262,7 +262,9 @@ jobs:
services.llmProviderAttemptRedemption.realPostgres.integration \
services.llmProviderAttemptFinalization.realPostgres.integration \
pluginWorkloadSdkCodexDualLedger.realPostgres.integration \
- services.grokSubscriptionConnection.realPostgres.integration
+ pluginWorkloadSdkGrokDualLedger.realPostgres.integration \
+ services.grokSubscriptionConnection.realPostgres.integration \
+ services.grokProviderAttemptRedemption.realPostgres.integration
do
grep -Fq "$suite" "$normalized_log" || {
echo "real-Postgres control-api lane omitted Codex suite ${suite}" >&2
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 58b07aaae..25e25e66b 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.569",
+ "version": "0.1.570",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.569",
+ "version": "0.1.570",
"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 2bf248d82..2bdae541b 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.569",
+ "version": "0.1.570",
"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/recipes.ts b/control-api/src/routes/admin/recipes.ts
index 1252f5855..a252a0c2d 100644
--- a/control-api/src/routes/admin/recipes.ts
+++ b/control-api/src/routes/admin/recipes.ts
@@ -1435,15 +1435,20 @@ function sanitizeRecipeCodexAnnotation(
[SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,
})
if (recipeUsesCodexBroker(body.spec)) {
- if (!bodyHasCodexGrantAnnotation(body)) return {}
+ if (!bodyHasCodexGrantAnnotation(body)) {
+ if (recipeUsesGrokBroker(currentSpec)) return mirrored('')
+ return {}
+ }
const annotations = recipeAnnotationStrings(body.metadata?.annotations) ?? {}
const alias = (annotations[CODEX_CONNECTION_REF_ANNOTATION] ?? '').trim()
const canonical = (annotations[SUBSCRIPTION_CONNECTION_REF_ANNOTATION] ?? '').trim()
if (canonical && alias && canonical !== alias) {
throw new RecipeGrantAnnotationDisagreeError('subscription connection annotations disagree')
}
- // Grok writers emit canonical only. Do not promote that leftover to a Codex grant.
- if (!alias) return mirrored('')
+ // Grok writers emit canonical only. A missing Codex alias is leftover only
+ // when the previous spec was Grok — not when a Codex writer sent the
+ // canonical key alone.
+ if (recipeUsesGrokBroker(currentSpec) && !alias) return mirrored('')
const incoming = readRequestedCodexRecipeGrant(body)
return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)
}
@@ -1455,6 +1460,8 @@ function sanitizeRecipeCodexAnnotation(
if (bodyHasCodexGrantAnnotation(body)) {
const annotations = recipeAnnotationStrings(body.metadata?.annotations) ?? {}
const alias = (annotations[CODEX_CONNECTION_REF_ANNOTATION] ?? '').trim()
+ // This path is not a Codex recipe. Missing alias must not promote a
+ // canonical leftover onto the Codex alias.
if (!alias) return mirrored('')
const incoming = readRequestedCodexRecipeGrant(body)
return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)
diff --git a/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts
new file mode 100644
index 000000000..d001e4d30
--- /dev/null
+++ b/control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts
@@ -0,0 +1,223 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes, randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { computeGrokPolicyHash } from '@clerum/grok-provider-attempt-contract'
+import { config } from '../src/config.js'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { evaluateBudgetCheck } from '../src/services/budgets/check.js'
+import { getActiveReservation } from '../src/services/budgets/reservations.js'
+import {
+ getSafeGrokSubscriptionConnection,
+ insertInitialGrokSubscriptionConnection,
+ recordGrokCatalogOutcome,
+} from '../src/services/grokSubscriptionConnection.js'
+import { authorizeLlmProviderAttempt } from '../src/services/llmProviderAttemptAuthorizer.js'
+import {
+ getMaxLlmProviderAttemptGeneration,
+ insertLlmProviderAttempt,
+ loadLlmProviderAttemptBySdkAttemptId,
+} from '../src/services/llmProviderAttemptStore.js'
+import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
+import './realPostgres.requirement.ts'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
+const NS = 'sandbox-recipes'
+const RECIPE = 'prompt-notify'
+const MODEL = 'grok-4.6'
+const CONNECTION_KEY = 'team-grok'
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+}
+
+const REQUEST = {
+ schemaVersion: 'grok-completion-request.v1' as const,
+ requestId: 'req-sdk-grok-dual',
+ idempotencyKey: 'idem-sdk-grok-dual',
+ provider: 'grok-subscription' as const,
+ model: MODEL,
+ messages: [{ role: 'user' as const, content: 'sdk grok dual ledger' }],
+}
+
+describeRealPostgres('Plugin Workload SDK Grok dual ledger on real PostgreSQL', () => {
+ const database = `sdk_grok_dual_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? `postgresql://postgres@${['127', '0', '0', '1'].join('.')}/postgres`,
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+ const previousFlag = config.grokSubscriptionEnabled
+
+ function dbClient() {
+ return { query: (text: string, values?: unknown[]) => pool.query(text, values) }
+ }
+
+ async function seedSdkAttempt(): Promise<{ invocationId: string; sdkAttemptId: string }> {
+ const invocationId = randomUUID()
+ await pool.query(
+ `INSERT INTO plugin_workload_sdk_invocations (
+ id, recipe_namespace, recipe_name, caller_ref, method, detail,
+ idempotency_key_hash, status, authorization_decision, contract_version,
+ attempt_generation, lease_expires_at
+ ) VALUES ($1, $2, $3, 'api', 'promptBridge', 'prompt', $4, 'in_progress',
+ 'allow', 2, 1, now() + interval '5 minutes')`,
+ [invocationId, NS, RECIPE, randomBytes(32).toString('hex')]
+ )
+ await pool.query(
+ `INSERT INTO plugin_workload_sdk_invocation_attempts (
+ invocation_id, recipe_namespace, recipe_name, attempt_generation,
+ method, status, lease_expires_at
+ ) VALUES ($1, $2, $3, 1, 'promptBridge', 'in_progress',
+ now() + interval '5 minutes')`,
+ [invocationId, NS, RECIPE]
+ )
+ const inserted = await pool.query<{ id: string }>(
+ `INSERT INTO plugin_workload_sdk_provider_attempts (
+ invocation_id, recipe_namespace, recipe_name, attempt_generation,
+ attempt_index, target_ref, provider, model, credential_slot, status,
+ lease_expires_at
+ ) VALUES ($1, $2, $3, 1, 1, 'grok-primary', 'grok-subscription', $4, '',
+ 'reserved', now() + interval '5 minutes')
+ RETURNING id::text AS id`,
+ [invocationId, NS, RECIPE, MODEL]
+ )
+ return { invocationId, sdkAttemptId: inserted.rows[0]!.id }
+ }
+
+ beforeAll(async () => {
+ config.grokSubscriptionEnabled = true
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ const created = await insertInitialGrokSubscriptionConnection(
+ pool,
+ KEY,
+ { refreshToken: 'refresh-sdk-grok', accountFingerprint: 'fp-sdk-grok' },
+ CONNECTION_KEY
+ )
+ await recordGrokCatalogOutcome(pool, {
+ catalogStatus: 'ready',
+ connectionStatus: 'connected',
+ expectedCredentialRevision: 1,
+ expectedCatalogRevision: 0,
+ connectionKey: CONNECTION_KEY,
+ })
+ await pool.query(
+ `INSERT INTO grok_catalog_models
+ (connection_id, model, enabled, source, discovered_at, last_seen_at, stale)
+ VALUES ($1, $2, true, 'discovery', NOW(), NOW(), false)`,
+ [created.id, MODEL]
+ )
+ }, 60_000)
+
+ afterAll(async () => {
+ config.grokSubscriptionEnabled = previousFlag
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ await adminPool.end()
+ }
+ })
+
+ it('authorizes a recipe Grok attempt bound to a reserved SDK attempt id', async () => {
+ const current = await getSafeGrokSubscriptionConnection(pool, CONNECTION_KEY)
+ expect(current?.status).toBe('connected')
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt()
+ const claims: McpHostAccessClaims = {
+ sub: `${NS}/${RECIPE}`,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRefs: [`${NS}/${RECIPE}`],
+ scope: 'workflow:approval:request',
+ workflowControlScopes: ['llm:grok:execute'],
+ iss: 'control-api',
+ aud: 'workflow-approvals',
+ jti: randomUUID(),
+ exp: Math.floor(Date.now() / 1000) + 60,
+ }
+ const authorized = await authorizeLlmProviderAttempt(
+ claims,
+ {
+ request: {
+ ...REQUEST,
+ requestId: `req-${invocationId}`,
+ idempotencyKey: `idem-${invocationId}`,
+ },
+ invocationId,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ policyRevision: current!.catalogRevision,
+ policyHash: computeGrokPolicyHash({
+ model: MODEL,
+ catalogRevision: current!.catalogRevision,
+ credentialRevision: current!.credentialRevision,
+ connectionKey: CONNECTION_KEY,
+ }),
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ targetRef: 'grok-primary',
+ },
+ {
+ enabled: true,
+ db: dbClient(),
+ withTransaction: async work => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const result = await work(client as never)
+ await client.query('COMMIT')
+ return result
+ } catch (error) {
+ try {
+ await client.query('ROLLBACK')
+ } catch {
+ // keep the original error
+ }
+ throw error
+ } finally {
+ client.release()
+ }
+ },
+ getConnection: async () => current,
+ getModelState: async () => ({ enabled: true, stale: false }),
+ resolveConnectionKey: async () => CONNECTION_KEY,
+ resolveAssignment: async () => ({
+ liveBrokerProviders: ['grok-subscription'],
+ liveConnectionRef: CONNECTION_KEY,
+ }),
+ evaluateBudget: evaluateBudgetCheck,
+ getActiveReservation,
+ getMaxGeneration: getMaxLlmProviderAttemptGeneration,
+ insertAttempt: insertLlmProviderAttempt,
+ issueTicket: async () => ({
+ executionTicket: 'unused',
+ expiresAt: new Date(),
+ claims: { jti: randomUUID() },
+ }),
+ }
+ )
+ const linked = await loadLlmProviderAttemptBySdkAttemptId(pool, sdkAttemptId)
+ expect(linked?.id).toBe(authorized.providerAttemptId)
+ expect(linked?.pluginWorkloadSdkProviderAttemptId).toBe(sdkAttemptId)
+ expect(linked?.provider).toBe('grok-subscription')
+ 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 })
+ })
+})
diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.ts
index b56f669b5..83bf8392e 100644
--- a/control-api/test/routes.adminRecipes.test.ts
+++ b/control-api/test/routes.adminRecipes.test.ts
@@ -275,6 +275,61 @@ describe.sequential('routes/admin/recipes', () => {
})
})
+ it('POST /admin/recipes — dual-writes a Codex grant sent only on the canonical key', async () => {
+ const res = await api
+ .post('/admin/recipes')
+ .send({
+ metadata: {
+ name: 'codex-canonical-only',
+ annotations: { 'clerum.io/subscription-connection-ref': 'team-a' },
+ },
+ spec: {
+ agent: { provider: 'codex-subscription', model: 'gpt-5.1' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],
+ },
+ })
+ .expect(201)
+ expect(res.body.metadata.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': 'team-a',
+ 'clerum.io/subscription-connection-ref': 'team-a',
+ })
+ })
+
+ it('PUT /admin/recipes/:name — does not promote a leftover Grok canonical key onto Codex', async () => {
+ await api
+ .post('/admin/recipes')
+ .send({
+ metadata: {
+ name: 'grok-then-codex',
+ annotations: { 'clerum.io/subscription-connection-ref': 'team-grok' },
+ },
+ spec: {
+ agent: { provider: 'grok-subscription', model: 'grok-4.6' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],
+ },
+ })
+ .expect(201)
+ const res = await api
+ .put('/admin/recipes/grok-then-codex')
+ .send({
+ metadata: {
+ annotations: { 'clerum.io/subscription-connection-ref': 'team-grok' },
+ },
+ spec: {
+ agent: { provider: 'codex-subscription', model: 'gpt-5.1' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],
+ },
+ })
+ .expect(200)
+ expect(res.body.metadata.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': '',
+ 'clerum.io/subscription-connection-ref': '',
+ })
+ })
+
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' },
diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
index ba74f5f6f..c9ffa3a56 100644
--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
@@ -122,6 +122,36 @@ describe('POST /api/v1/mcp-host/llm/provider-attempts/authorize', () => {
expect(unassigned.body).toEqual({ error: 'unassigned_connection' })
})
+ it('injects resolveAssignment from the live Host instead of the empty default', async () => {
+ const getResource = vi.fn().mockResolvedValue({
+ spec: {
+ model: { provider: 'codex-subscription', name: 'gpt-5.1', connectionRef: 'team-plus' },
+ },
+ })
+ const app = express()
+ app.use(express.json({ limit: '1mb' }))
+ const api = express.Router()
+ api.use(createMcpHostLlmProviderAttemptRoutes({ getResource } as never))
+ app.use('/api/v1', api)
+ vi.mocked(authorizer.authorizeLlmProviderAttempt).mockResolvedValueOnce({
+ providerAttemptId: '33333333-3333-4333-8333-333333333333',
+ requestHash: 'a'.repeat(64),
+ executionTicket: 'ticket.jwt',
+ expiresAt: '2026-08-20T12:00:00.000Z',
+ })
+ await request(app)
+ .post('/api/v1/mcp-host/llm/provider-attempts/authorize')
+ .set('Authorization', `Bearer ${token()}`)
+ .send({ request: { schemaVersion: 'codex-completion-request.v1' } })
+ expect(authorizer.authorizeLlmProviderAttempt).toHaveBeenCalled()
+ const injected = vi.mocked(authorizer.authorizeLlmProviderAttempt).mock.calls[0]?.[2]
+ expect(injected?.resolveAssignment).toEqual(expect.any(Function))
+ await expect(injected!.resolveAssignment!('research-host')).resolves.toEqual({
+ liveBrokerProviders: ['codex-subscription'],
+ liveConnectionRef: 'team-plus',
+ })
+ })
+
it('returns the authorize contract without leaking tokens', async () => {
const app = buildApp()
vi.mocked(authorizer.authorizeLlmProviderAttempt).mockResolvedValueOnce({
@@ -162,6 +192,20 @@ describe('resolveHostAssignedConnectionKey', () => {
})
})
+ it('reads connectionRef from a Grok Host', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({
+ spec: {
+ model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: 'team-grok' },
+ },
+ }),
+ }
+ await expect(resolveHostAssignedAssignment(gateway, 'agent-g')).resolves.toEqual({
+ liveBrokerProviders: ['grok-subscription'],
+ liveConnectionRef: 'team-grok',
+ })
+ })
+
it('fails closed when recipe subscription annotations disagree', async () => {
const gateway = {
getResource: vi.fn().mockResolvedValue({
diff --git a/control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts b/control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts
new file mode 100644
index 000000000..e64ff7ff9
--- /dev/null
+++ b/control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts
@@ -0,0 +1,180 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes, randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { redeemGrokProviderAttempt } from '../src/services/grokProviderAttemptRedemption.js'
+import { issueRegisteredGrokExecutionTicket } from '../src/services/grokProviderAttemptTicket.js'
+import {
+ getSafeGrokSubscriptionConnectionById,
+ insertInitialGrokSubscriptionConnection,
+ loadGrokSubscriptionSecrets,
+} from '../src/services/grokSubscriptionConnection.js'
+import { opaqueAttemptReceipt } from '../src/services/llmProviderAttemptRedemption.js'
+import { insertLlmProviderAttempt } from '../src/services/llmProviderAttemptStore.js'
+import './realPostgres.requirement.ts'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
+const CONNECTION_KEY = 'team-grok-redeem'
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+}
+
+describeRealPostgres('Grok ticket redemption on real PostgreSQL', () => {
+ const database = `grok_attempt_redeem_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? `postgresql://postgres@${['127', '0', '0', '1'].join('.')}/postgres`,
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+ let connectionId: string
+ const previousFlag = config.grokSubscriptionEnabled
+
+ beforeAll(async () => {
+ config.grokSubscriptionEnabled = true
+ config.oauthEncryptionKey = 'ab'.repeat(32)
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ const connection = await insertInitialGrokSubscriptionConnection(
+ pool,
+ KEY,
+ {
+ refreshToken: 'refresh-secret',
+ accessToken: 'access-usable',
+ accountFingerprint: 'fp-grok-redeem',
+ },
+ CONNECTION_KEY
+ )
+ connectionId = connection.id
+ }, 60_000)
+
+ afterAll(async () => {
+ config.grokSubscriptionEnabled = previousFlag
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ await adminPool.end()
+ }
+ })
+
+ async function issueRedeemableTicket() {
+ const attempt = await insertLlmProviderAttempt(pool, {
+ callerKind: 'host',
+ hostRef: 'research-host',
+ invocationId: `invocation-${randomUUID()}`,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ requestHash: 'd'.repeat(64),
+ policyRevision: 1,
+ policyHash: 'e'.repeat(64),
+ budgetReservationId: 'unbudgeted',
+ connectionRevision: 1,
+ connectionId,
+ })
+ const issued = await issueRegisteredGrokExecutionTicket(pool, {
+ sub: 'host/research-host',
+ hostRef: attempt.hostRef,
+ invocationId: attempt.invocationId,
+ attemptGeneration: attempt.attemptGeneration,
+ providerAttemptId: attempt.id,
+ providerAttemptIndex: attempt.providerAttemptIndex,
+ model: attempt.model,
+ requestHash: attempt.requestHash,
+ policyRevision: attempt.policyRevision,
+ policyHash: attempt.policyHash,
+ budgetReservationId: attempt.budgetReservationId,
+ connectionRevision: attempt.connectionRevision,
+ connectionId,
+ })
+ return { attempt, issued }
+ }
+
+ function redeemDeps() {
+ return {
+ enabled: true as const,
+ db: pool,
+ encryptionKey: KEY,
+ loadSecrets: loadGrokSubscriptionSecrets,
+ getConnectionById: getSafeGrokSubscriptionConnectionById,
+ withTransaction: async (work: (tx: Pool) => Promise<unknown>) => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const result = await work(client as never)
+ await client.query('COMMIT')
+ return result
+ } catch (error) {
+ try {
+ await client.query('ROLLBACK')
+ } catch {
+ // keep the original error
+ }
+ throw error
+ } finally {
+ client.release()
+ }
+ },
+ }
+ }
+
+ it('redeems an issued Grok ticket once and returns the access token', async () => {
+ const { attempt, issued } = await issueRedeemableTicket()
+ const redeemed = await redeemGrokProviderAttempt(
+ {
+ executionTicket: issued.executionTicket,
+ requestHash: attempt.requestHash,
+ },
+ redeemDeps()
+ )
+ expect(redeemed.accessToken).toBe('access-usable')
+ expect(JSON.stringify(redeemed)).not.toContain('refresh-secret')
+ expect(redeemed.attemptReceipt).toBe(
+ opaqueAttemptReceipt({
+ jti: issued.claims.jti,
+ providerAttemptId: attempt.id,
+ requestHash: attempt.requestHash,
+ })
+ )
+ })
+
+ it('lets exactly one of 20 concurrent redeems win', async () => {
+ const { attempt, issued } = await issueRedeemableTicket()
+ const results = await Promise.allSettled(
+ Array.from({ length: 20 }, () =>
+ redeemGrokProviderAttempt(
+ {
+ executionTicket: issued.executionTicket,
+ requestHash: attempt.requestHash,
+ },
+ redeemDeps()
+ )
+ )
+ )
+ const wins = results.filter(result => result.status === 'fulfilled')
+ const losses = results.filter(result => result.status === 'rejected')
+ expect(wins).toHaveLength(1)
+ expect(losses).toHaveLength(19)
+ for (const loss of losses) {
+ if (loss.status === 'rejected') {
+ expect((loss.reason as { code?: string }).code).toBe('ticket_replayed')
+ }
+ }
+ })
+})
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
index d80c027c0..f3f4fb192 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
@@ -16,6 +16,10 @@ const grokRepos = vi.hoisted(() => ({
getModelState: vi.fn(),
issueTicket: 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/grokSubscriptionConnection.js', async () => {
const actual = await vi.importActual<
@@ -47,6 +51,41 @@ vi.mock('../src/services/grokProviderAttemptTicket.js', async () => {
}
})
+vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/services/pluginWorkloadSdkDb.js')>(
+ '../src/services/pluginWorkloadSdkDb.js'
+ )
+ return {
+ ...actual,
+ 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: 'grok-primary',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ credentialSlot: '',
+ status: 'reserved',
+ credentialJti: null,
+ startedAt: new Date().toISOString(),
+ leaseExpiresAt: null,
+ completedAt: null,
+ usageRequestId: null,
+ ...overrides,
+ }
+}
+
const REQUEST = {
schemaVersion: 'grok-completion-request.v1' as const,
requestId: 'req-001',
@@ -156,6 +195,10 @@ describe('authorizeLlmProviderAttempt grok-subscription', () => {
expiresAt: new Date('2026-08-20T12:00:00.000Z'),
claims: { jti: 'jti-ticket' },
})
+ lockPluginWorkloadSdkRecipe.mockReset().mockResolvedValue(undefined)
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockReset()
+ pluginWorkloadSdkSpendOutcomeExists.mockReset().mockResolvedValue(false)
+ promoteReservedOauthBrokerProviderAttempt.mockReset().mockResolvedValue(true)
})
afterEach(() => {
@@ -235,4 +278,77 @@ describe('authorizeLlmProviderAttempt grok-subscription', () => {
expect(grokRepos.getConnection).not.toHaveBeenCalled()
expect(current.insertAttempt).not.toHaveBeenCalled()
})
+
+ it('binds a reserved Plugin Workload SDK attempt onto the Grok ledger row', async () => {
+ const sdkAttemptId = reservedSdkAttempt().id
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(reservedSdkAttempt())
+ const current = deps()
+ await authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body({ pluginWorkloadSdkProviderAttemptId: sdkAttemptId, targetRef: 'grok-primary' }),
+ current
+ )
+ expect(lockPluginWorkloadSdkRecipe).toHaveBeenCalledWith(
+ expect.anything(),
+ 'sandbox-recipes',
+ 'prompt-notify'
+ )
+ expect(current.insertAttempt).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ callerKind: 'recipe',
+ provider: 'grok-subscription',
+ })
+ )
+ expect(promoteReservedOauthBrokerProviderAttempt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: sdkAttemptId,
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ targetRef: 'grok-primary',
+ }),
+ expect.anything()
+ )
+ })
+
+ it('rejects a reserved SDK attempt whose provider is Codex', async () => {
+ getPluginWorkloadSdkProviderAttemptForUpdate.mockResolvedValue(
+ reservedSdkAttempt({ provider: 'codex-subscription' })
+ )
+ const current = deps()
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body({
+ pluginWorkloadSdkProviderAttemptId: reservedSdkAttempt().id,
+ targetRef: 'grok-primary',
+ }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'no_grant' })
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ expect(promoteReservedOauthBrokerProviderAttempt).not.toHaveBeenCalled()
+ })
+
+ it('rejects a host caller that presents a Plugin Workload SDK attempt id', async () => {
+ const current = deps()
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims(),
+ body({ pluginWorkloadSdkProviderAttemptId: reservedSdkAttempt().id }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'no_grant' })
+ expect(getPluginWorkloadSdkProviderAttemptForUpdate).not.toHaveBeenCalled()
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ })
})
diff --git a/scripts/tests/test-grok-llm-proxy-deploy-contract.sh b/scripts/tests/test-grok-llm-proxy-deploy-contract.sh
index 3db25f242..fb0985eb7 100755
--- a/scripts/tests/test-grok-llm-proxy-deploy-contract.sh
+++ b/scripts/tests/test-grok-llm-proxy-deploy-contract.sh
@@ -89,10 +89,20 @@ if cm.count("location / {\n return 403;") < 2:
np = networkpolicies.read_text()
if "name: grok-llm-proxy-ingress" not in np or "name: grok-llm-proxy-egress" not in np:
errors.append("networkpolicies missing grok-llm-proxy ingress/egress")
-if "app: grok-llm-proxy" not in np[np.find("name: control-api-rpc-gateway"): np.find("name: grok-llm-proxy-ingress") if "name: grok-llm-proxy-ingress" in np else len(np)]:
- gateway = np[np.find("name: control-api-rpc-gateway"):]
- if "app: grok-llm-proxy" not in gateway.split("egress:", 1)[0]:
- errors.append("rpc gateway ingress must admit app: grok-llm-proxy")
+docs = [chunk for chunk in np.split("\n---\n") if chunk.strip()]
+gateway = next(
+ (
+ chunk
+ for chunk in docs
+ if re.search(r"(?m)^ name: control-api-rpc-gateway\s*$", chunk)
+ ),
+ "",
+)
+ingress = ""
+if "\n ingress:\n" in gateway:
+ ingress = gateway.split("\n ingress:\n", 1)[1].split("\n egress:\n", 1)[0]
+if "app: grok-llm-proxy" not in ingress:
+ errors.append("rpc gateway ingress must admit app: grok-llm-proxy")
if "name: grok-llm-proxy-egress" not in base_kustomize.read_text():
errors.append("base kustomization must fill grok-llm-proxy-egress except")
diff --git a/scripts/tests/test-grok-subscription-t0.sh b/scripts/tests/test-grok-subscription-t0.sh
index 7c590ed68..ac638af72 100755
--- a/scripts/tests/test-grok-subscription-t0.sh
+++ b/scripts/tests/test-grok-subscription-t0.sh
@@ -97,6 +97,8 @@ require_file grok-llm-proxy/test/originPolicy.test.ts
require_file control-api/test/services.grokSubscriptionOAuth.test.ts
require_file control-api/test/services.grokProviderAttemptTicket.test.ts
require_file control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts
+require_file control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts
+require_file control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts
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