Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: close Fable R2 attestation and extract-T0 holes
Jose Gabriel Ramirez Encinas668b21eb6865
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex f0f668785..c81f91d0b 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -69,6 +69,7 @@ jobs:- packages/workflow-sdk- packages/network-policy-core- packages/llm-provider-attempt-contract+ - packages/llm-providers- packages/codex-catalog-projection- codex-llm-proxydiff --git a/Makefile b/Makefileindex 6e57d83c5..9343c6691 100644--- a/Makefile+++ b/Makefile@@ -50,7 +50,8 @@ SERVICES := \packages/gfs-interaction-policy \packages/workflow-runtime-core \packages/workflow-sdk \- packages/llm-provider-attempt-contract+ packages/llm-provider-attempt-contract \+ packages/llm-providers# Services that have unit testsTEST_SERVICES := \@@ -74,7 +75,8 @@ TEST_SERVICES := \packages/workflow-runtime-core \packages/workflow-sdk \packages/network-policy-core \- packages/llm-provider-attempt-contract+ packages/llm-provider-attempt-contract \+ packages/llm-providers# ── Optional private infra (gcp-*, promotion) ──────────────────────────────-include Makefile.infra@@ -126,6 +128,10 @@ test-unit-all: ## Run unit tests across all servicestest-codex-subscription-t0: ## Run the Codex subscription T0 aggregator (counts, no skips)@bash scripts/tests/test-codex-subscription-t0.sh+.PHONY: test-llm-subscription-extract-t0+test-llm-subscription-extract-t0: ## Run the wave-1 oauth-broker extract T0 aggregator+ @bash scripts/tests/test-llm-subscription-extract-t0.sh+# ── Build Preflight ──────────────────────────────────────────────────.PHONY: build-preflightbuild-preflight: ## Run local build preflight across deployable packagesdiff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 94148d62e..997496ac6 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.553",+ "version": "0.1.554","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.553",+ "version": "0.1.554","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.jsonindex 989dbe548..4a60ece3d 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.553",+ "version": "0.1.554","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex ba1340332..e9a8c4404 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -64,7 +64,7 @@ const BASE = SUBSCRIPTION_ADMIN_BASEexport function mountSubscriptionAdminRoutes(router: Router,- options: { providerId: string; enabled: () => boolean }+ options: { providerIds: readonly string[]; enabled: (providerId: string) => boolean }): void {router.use(SUBSCRIPTION_ADMIN_BASE, (req: Request, res: Response, next: NextFunction) => {const providerId = typeof req.params.providerId === 'string' ? req.params.providerId : ''@@ -72,11 +72,11 @@ export function mountSubscriptionAdminRoutes(res.status(404).json({ error: 'not_found' })return}- if (providerId !== options.providerId) {+ if (!options.providerIds.includes(providerId)) {res.status(404).json({ error: 'not_found' })return}- if (!options.enabled()) {+ if (!options.enabled(providerId)) {res.status(404).json({ error: 'disabled' })return}@@ -218,8 +218,9 @@ export function createAdminCodexSubscriptionRouter(): Router {const router = Router()mountSubscriptionAdminRoutes(router, {- providerId: 'codex-subscription',- enabled: () => config.codexSubscriptionEnabled,+ providerIds: ['codex-subscription'],+ enabled: providerId =>+ providerId === 'codex-subscription' ? config.codexSubscriptionEnabled : false,})async function listHostsOrUnavailable(): Promise<HostRecord[] | null> {diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.tsindex f91df1c1e..812bfd184 100644--- a/control-api/src/routes/admin/recipes.ts+++ b/control-api/src/routes/admin/recipes.ts@@ -1265,17 +1265,40 @@ function readRequestedCodexRecipeGrant(body: RecipeBody): string {provider: 'codex-subscription',annotations: body.metadata?.annotations,})- if (!result.ok) return CODEX_UNASSIGNED_CONNECTION_KEY+ if (!result.ok) {+ throw new RecipeGrantAnnotationDisagreeError(result.message)+ }return result.connectionKey}+class RecipeGrantAnnotationDisagreeError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'RecipeGrantAnnotationDisagreeError'+ }+}+function validateCodexRecipeGrant(body: RecipeBody,opts?: { allowOmittedGrant?: boolean }): ValidationError[] {if (!recipeUsesCodexBroker(body.spec)) return []if (opts?.allowOmittedGrant && !bodyHasCodexGrantAnnotation(body)) return []- const key = readRequestedCodexRecipeGrant(body)+ let key: string+ try {+ key = readRequestedCodexRecipeGrant(body)+ } catch (err) {+ if (err instanceof RecipeGrantAnnotationDisagreeError) {+ return [+ {+ field: `metadata.annotations.${CODEX_CONNECTION_REF_ANNOTATION}`,+ rule: 'subscriptionAnnotationsDisagree',+ message: err.message,+ },+ ]+ }+ throw err+ }if (isCodexUnassignedConnectionKey(key)) {return [{@@ -1314,20 +1337,20 @@ function sanitizeRecipeCodexAnnotation(currentSpec?: Record<string, unknown>): Record<string, string> {const incoming = readRequestedCodexRecipeGrant(body)+ const mirrored = (key: string) => ({+ [CODEX_CONNECTION_REF_ANNOTATION]: key,+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,+ })if (recipeUsesCodexBroker(body.spec)) {if (!bodyHasCodexGrantAnnotation(body)) return {}- return {- [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(incoming) ? '' : incoming,- }+ return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)}const leavingCodex = recipeUsesCodexBroker(currentSpec) && !recipeHasPluginWorkloadSdk(body.spec)if (leavingCodex) {- return { [CODEX_CONNECTION_REF_ANNOTATION]: '' }+ return mirrored('')}if (bodyHasCodexGrantAnnotation(body)) {- return {- [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(incoming) ? '' : incoming,- }+ return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)}void currentAnnotationsreturn {}diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.tsindex 12fc85f06..b6f6610bb 100644--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts@@ -4,7 +4,10 @@ import { asyncHandler } from '../../http/asyncHandler.js'import type { K8sGateway } from '../../k8s.js'import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'import { rootLogger } from '../../observability/logger.js'-import { readHostCodexConnectionRef } from '../../services/codexSubscriptionConnection.js'+import {+ CODEX_UNASSIGNED_CONNECTION_KEY,+ readHostCodexConnectionRef,+} from '../../services/codexSubscriptionConnection.js'import {LlmProviderAttemptAuthorizeError,authorizeLlmProviderAttempt,@@ -47,6 +50,7 @@ function sendAuthorizeError(res: Response, err: unknown): void {export type LiveBrokerAssignment = {liveBrokerProviders: string[]liveConnectionRef: string+ annotations?: Record<string, string>}function throwAttestError(result: { ok: false; code: string; message: string }): never {@@ -76,17 +80,11 @@ export async function resolveHostAssignedAssignment()) as { metadata?: { annotations?: Record<string, string> }; spec?: Record<string, unknown> }const spec = recipe?.spec && typeof recipe.spec === 'object' ? recipe.spec : {}const liveBrokerProviders = collectRecipeOauthBrokerProviders(spec)- const annotationProvider =- liveBrokerProviders[0] ??- (typeof (spec.agent as { provider?: string } | undefined)?.provider === 'string'- ? String((spec.agent as { provider: string }).provider)- : 'codex-subscription')- const read = readSubscriptionConnectionRef({- provider: annotationProvider,+ return {+ liveBrokerProviders,+ liveConnectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,annotations: recipe?.metadata?.annotations,- })- if (!read.ok) throwAttestError(read)- return { liveBrokerProviders, liveConnectionRef: read.connectionKey }+ }} catch (err) {if (err instanceof LlmProviderAttemptAuthorizeError) throw errthrow new LlmProviderAttemptAuthorizeError(@@ -123,7 +121,13 @@ export async function resolveHostAssignedConnectionKey(hostRef: string): Promise<string> {const assignment = await resolveHostAssignedAssignment(gateway, hostRef)- return assignment.liveConnectionRef+ if (!assignment.annotations) return assignment.liveConnectionRef+ const read = readSubscriptionConnectionRef({+ provider: assignment.liveBrokerProviders[0] ?? 'codex-subscription',+ annotations: assignment.annotations,+ })+ if (!read.ok) throwAttestError(read)+ return read.connectionKey}export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Router {diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.tsindex 453ec369c..fff3b460e 100644--- a/control-api/src/services/codexSubscriptionOAuth.ts+++ b/control-api/src/services/codexSubscriptionOAuth.ts@@ -851,6 +851,7 @@ async function post(method: 'POST',headers: { 'content-type': contentType, accept: 'application/json' },body,+ redirect: 'manual',signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),})} catch (err) {@@ -860,6 +861,16 @@ async function post('Codex OAuth upstream unreachable')}+ if (response.status >= 300 && response.status < 400) {+ log.warn(+ { event: 'codex_oauth_redirect_denied', status: response.status },+ 'Codex OAuth upstream returned a redirect'+ )+ throw new CodexSubscriptionOAuthError(+ 'provider_unavailable',+ 'Codex OAuth upstream returned a redirect'+ )+ }const json = (await response.json().catch(() => ({}))) as Record<string, unknown>return { ok: response.ok, status: response.status, body: json }}diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.tsindex e1bd8909c..7745c6187 100644--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts@@ -28,7 +28,11 @@ import {pluginWorkloadSdkSpendOutcomeExists,promoteReservedOauthBrokerProviderAttempt,} from './pluginWorkloadSdkDb.js'-import { attestRequestedBrokerProvider } from './subscriptionGrantIdentity.js'+import {+ attestLiveBrokerTarget,+ attestRequestedBrokerProvider,+ readSubscriptionConnectionRef,+} from './subscriptionGrantIdentity.js'const log = rootLogger.child({ module: 'llm-provider-attempt-authorizer' })const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'@@ -92,14 +96,13 @@ export type LlmProviderAttemptAuthorizerDeps = {getModelState: typeof getCodexCatalogModelStateresolveConnectionKey: (hostRef: string) => Promise<string>/**- * Live oauth-broker targets on the Host/recipe. When omitted, authorize- * treats the requested provider as the only live target so existing unit- * tests that mock only the connection key keep working. Production routes- * must pass the K8s-attested assignment.+ * Live oauth-broker targets on the Host/recipe. Required: a missing+ * assignment must not fall back to `request.provider` (that made D6 a no-op).*/- resolveAssignment?: (hostRef: string) => Promise<{+ resolveAssignment: (hostRef: string) => Promise<{liveBrokerProviders: string[]liveConnectionRef: string+ annotations?: Record<string, string>}>evaluateBudget: typeof evaluateBudgetCheckgetActiveReservation: typeof getActiveReservation@@ -115,6 +118,10 @@ const defaultDeps = (): LlmProviderAttemptAuthorizerDeps => ({getConnection: getSafeCodexSubscriptionConnection,getModelState: getCodexCatalogModelState,resolveConnectionKey: async () => CODEX_UNASSIGNED_CONNECTION_KEY,+ resolveAssignment: async () => ({+ liveBrokerProviders: [],+ liveConnectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,+ }),evaluateBudget: evaluateBudgetCheck,getActiveReservation,getMaxGeneration: getMaxLlmProviderAttemptGeneration,@@ -264,16 +271,29 @@ export async function authorizeLlmProviderAttempt()}- const assignment = resolvedDeps.resolveAssignment- ? await resolvedDeps.resolveAssignment(caller.hostRef)- : {- liveBrokerProviders: [request.provider],- liveConnectionRef: await resolvedDeps.resolveConnectionKey(caller.hostRef),- }+ const assignment = await resolvedDeps.resolveAssignment(caller.hostRef)+ const liveTarget = attestLiveBrokerTarget({+ requestedProvider: request.provider,+ liveBrokerProviders: assignment.liveBrokerProviders,+ })+ if (!liveTarget.ok) {+ throw new LlmProviderAttemptAuthorizeError(liveTarget.code, liveTarget.message)+ }+ let resolvedConnectionRef = assignment.liveConnectionRef+ if (assignment.annotations) {+ const read = readSubscriptionConnectionRef({+ provider: request.provider,+ annotations: assignment.annotations,+ })+ if (!read.ok) {+ throw new LlmProviderAttemptAuthorizeError(read.code, read.message)+ }+ resolvedConnectionRef = read.connectionKey+ }const attested = attestRequestedBrokerProvider({requestedProvider: request.provider,liveBrokerProviders: assignment.liveBrokerProviders,- liveConnectionRef: assignment.liveConnectionRef,+ liveConnectionRef: resolvedConnectionRef,})if (!attested.ok) {throw new LlmProviderAttemptAuthorizeError(attested.code, attested.message)diff --git a/control-api/src/services/recipeCodexGrantIdentity.ts b/control-api/src/services/recipeCodexGrantIdentity.tsindex 0864637c1..6f1f7050a 100644--- a/control-api/src/services/recipeCodexGrantIdentity.ts+++ b/control-api/src/services/recipeCodexGrantIdentity.ts@@ -8,7 +8,10 @@ import {isCodexUnassignedConnectionKey,} from './codexSubscriptionConnection.js'import { K8sConflictError } from './resourceService.js'-import { readSubscriptionConnectionRef } from './subscriptionGrantIdentity.js'+import {+ SUBSCRIPTION_CONNECTION_REF_ANNOTATION,+ readSubscriptionConnectionRef,+} from './subscriptionGrantIdentity.js'export class RecipeCodexGrantIdentityError extends Error {constructor(@@ -98,6 +101,7 @@ export async function publishRecipeGrantIdentity(input: {const nextAnnotations = {...annotations,[CODEX_CONNECTION_REF_ANNOTATION]: next === CODEX_UNASSIGNED_CONNECTION_KEY ? '' : next,+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: next === CODEX_UNASSIGNED_CONNECTION_KEY ? '' : next,}const spec = asRecord(current.spec) ?? {}const labels = stringMap(current.metadata?.labels)diff --git a/control-api/src/services/subscriptionGrantIdentity.ts b/control-api/src/services/subscriptionGrantIdentity.tsindex d31131024..7caac20c9 100644--- a/control-api/src/services/subscriptionGrantIdentity.ts+++ b/control-api/src/services/subscriptionGrantIdentity.ts@@ -58,11 +58,6 @@ export function collectRecipeOauthBrokerProviders(spec: Record<string, unknown>)if (isPlainObject(step) && isPlainObject(step.agent)) push(step.agent.provider)}}- if (Array.isArray(spec.promptTargets)) {- for (const target of spec.promptTargets) {- if (isPlainObject(target)) push(target.provider)- }- }return providers}@@ -109,11 +104,10 @@ export function readSubscriptionConnectionRef(input: {return { ok: true, connectionKey: readHostCodexConnectionRef(canonical) }}-export function attestRequestedBrokerProvider(input: {+export function attestLiveBrokerTarget(input: {requestedProvider: stringliveBrokerProviders: string[]- liveConnectionRef: string-}): SubscriptionGrantAttestResult {+}): Exclude<SubscriptionGrantAttestResult, { ok: true }> | { ok: true; provider: string } {if (!isOauthBroker(input.requestedProvider)) {return {ok: false,@@ -128,6 +122,16 @@ export function attestRequestedBrokerProvider(input: {message: 'requested oauth-broker provider is not a live target on this resource',}}+ return { ok: true, provider: input.requestedProvider }+}++export function attestRequestedBrokerProvider(input: {+ requestedProvider: string+ liveBrokerProviders: string[]+ liveConnectionRef: string+}): SubscriptionGrantAttestResult {+ const target = attestLiveBrokerTarget(input)+ if (!target.ok) return targetconst connectionKey = readHostCodexConnectionRef(input.liveConnectionRef)if (isCodexUnassignedConnectionKey(connectionKey) ||diff --git a/control-api/test/hostSpecValidation.oauthBrokerExtract.test.ts b/control-api/test/hostSpecValidation.oauthBrokerExtract.test.tsnew file mode 100644index 000000000..8f2350d51--- /dev/null+++ b/control-api/test/hostSpecValidation.oauthBrokerExtract.test.ts@@ -0,0 +1,36 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++vi.mock('@clerum/llm-providers', async () => {+ const actual =+ await vi.importActual<typeof import('@clerum/llm-providers')>('@clerum/llm-providers')+ return {+ ...actual,+ isLlmProviderId: (id: unknown): id is (typeof actual.PROVIDER_IDS)[number] =>+ actual.isLlmProviderId(id) || id === 'fixture-broker',+ PROVIDER_AUTH_MODE: {+ ...actual.PROVIDER_AUTH_MODE,+ 'fixture-broker': 'oauth-broker',+ },+ }+})++const { validateHostSpec } = await import('../src/routes/admin/hostSpecValidation.js')++describe('oauth-broker extract admission', () => {+ afterEach(() => {+ delete process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED+ })++ it('rejects two distinct oauth-broker ids on one Host', async () => {+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'+ const res = await validateHostSpec(+ {+ model: { provider: 'codex-subscription', name: 'gpt-5.1' },+ allowedModels: [{ provider: 'fixture-broker', name: 'fixture-1' }],+ },+ { isModelAllowed: vi.fn().mockResolvedValue(true) }+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].message).toMatch(/at most one oauth-broker/)+ })+})diff --git a/control-api/test/routes.admin.codexSubscription.oauthBrokerExtract.test.ts b/control-api/test/routes.admin.codexSubscription.oauthBrokerExtract.test.tsnew file mode 100644index 000000000..1f750bff8--- /dev/null+++ b/control-api/test/routes.admin.codexSubscription.oauthBrokerExtract.test.ts@@ -0,0 +1,48 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express, { type NextFunction, type Request, type Response } from 'express'+import request from 'supertest'++vi.mock('@clerum/llm-providers', async () => {+ const actual =+ await vi.importActual<typeof import('@clerum/llm-providers')>('@clerum/llm-providers')+ return {+ ...actual,+ isLlmProviderId: (id: unknown): boolean =>+ actual.isLlmProviderId(id) || id === 'fixture-broker',+ PROVIDER_AUTH_MODE: {+ ...actual.PROVIDER_AUTH_MODE,+ 'fixture-broker': 'oauth-broker',+ },+ }+})++vi.mock('../src/db.js', () => ({+ pool: { query: vi.fn() },+}))++const { config } = await import('../src/config.js')+const { createCodexCatalogTransportFromEnv } =+ await import('../src/services/codexSubscriptionCatalog.js')+const { createAdminCodexSubscriptionRouter } =+ await import('../src/routes/admin/codexSubscription.js')++describe('subscription admin extract guard', () => {+ beforeEach(() => {+ config.codexSubscriptionEnabled = true+ })++ it('404s a fixture oauth-broker that this router does not host', async () => {+ const app = express()+ app.use(express.json())+ app.use(+ (req: Request & { adminAuth?: { sub: string } }, _res: Response, next: NextFunction) => {+ req.adminAuth = { sub: 'admin-1' }+ next()+ }+ )+ app.use(createAdminCodexSubscriptionRouter(createCodexCatalogTransportFromEnv()))+ const res = await request(app).get('/admin/llm/providers/fixture-broker/connections')+ expect(res.status).toBe(404)+ expect(res.body).toEqual({ error: 'not_found' })+ })+})diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.attestation.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.attestation.test.tsnew file mode 100644index 000000000..99653a8a3--- /dev/null+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.attestation.test.ts@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { hashCodexCompletionRequestV1 } from '@clerum/llm-provider-attempt-contract'+import { config } from '../src/config.js'+import { createMcpHostLlmProviderAttemptRoutes } from '../src/routes/mcp-host/llmProviderAttempts.routes.js'+import { computeCodexPolicyHash } from '../src/services/llmProviderAttemptAuthorizer.js'+import * as mcpHostJwt from '../src/utils/auth/mcpHostJwtToken.js'++vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))++vi.mock('../src/observability/metrics.js', async importOriginal => {+ const actual = await importOriginal<typeof import('../src/observability/metrics.js')>()+ return {+ ...actual,+ rateLimitHitsTotal: { inc: vi.fn() },+ }+})++const REQUEST = {+ schemaVersion: 'codex-completion-request.v1' as const,+ requestId: 'req-001',+ idempotencyKey: 'idem-001',+ provider: 'codex-subscription' as const,+ model: 'gpt-5.1',+ messages: [{ role: 'user' as const, content: 'hello' }],+}++describe('authorize D6 live-target witness', () => {+ beforeEach(() => {+ config.codexSubscriptionEnabled = true+ })++ it('returns 403 host_binding_mismatch for a Codex body on a static-only Host', async () => {+ const app = express()+ app.use(express.json({ limit: '1mb' }))+ const api = express.Router()+ api.use(+ createMcpHostLlmProviderAttemptRoutes({+ getResource: vi.fn().mockResolvedValue({+ spec: { model: { provider: 'openai', name: 'gpt-5.1' }, secretRef: 'llm' },+ }),+ } as never)+ )+ app.use('/api/v1', api)++ const token = mcpHostJwt.issueMcpHostAccessJwt('default', 'research-host', ['research-host'], {+ workflowControlScopes: ['llm:codex:execute'],+ }).token+ const res = await request(app)+ .post('/api/v1/mcp-host/llm/provider-attempts/authorize')+ .set('Authorization', `Bearer ${token}`)+ .send({+ request: REQUEST,+ invocationId: 'invocation-1',+ attemptGeneration: 1,+ providerAttemptIndex: 1,+ policyRevision: 4,+ policyHash: computeCodexPolicyHash({+ model: REQUEST.model,+ catalogRevision: 4,+ credentialRevision: 3,+ }),+ requestHash: hashCodexCompletionRequestV1(REQUEST),+ })+ expect(res.status).toBe(403)+ expect(res.body).toEqual({ error: 'host_binding_mismatch' })+ })+})diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.tsindex b3780e961..fe243e505 100644--- a/control-api/test/services.codexSubscriptionOAuth.test.ts+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts@@ -377,6 +377,35 @@ describe('codex subscription OAuth broker', () => {expect(repos.expireState).toHaveBeenCalled()})+ it('does not follow OAuth token redirects and treats 3xx as provider_unavailable', async () => {+ const handle = JSON.stringify({ deviceAuthId: 'deviceauth_secret', userCode: 'ABCD-EFGH' })+ repos.peekState.mockResolvedValue({+ safe: {+ state: 'dev-redir',+ flow: 'device',+ intent: 'connect',+ status: 'pending',+ expiresAt: new Date(Date.now() + 60_000),+ consumedAt: null,+ cancelledAt: null,+ createdAt: new Date(),+ },+ deviceCode: handle,+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: false,+ status: 307,+ json: async () => ({}),+ })+ await expect(pollCodexDevice(deps(fetchFn), 'dev-redir')).rejects.toMatchObject({+ code: 'provider_unavailable',+ })+ expect(fetchFn).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ redirect: 'manual' })+ )+ })+it('exchanges a completed device poll through the Codex device callback', async () => {const handle = JSON.stringify({ deviceAuthId: 'deviceauth_secret', userCode: 'ABCD-EFGH' })repos.peekState.mockResolvedValue({diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.tsindex 598cfb2f3..057805ad6 100644--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts@@ -116,13 +116,20 @@ function deps(overrides: Partial<LlmProviderAttemptAuthorizerDeps> = {}): LlmProviderAttemptAuthorizerDeps {const db = { query: vi.fn() }+ const resolveConnectionKey =+ overrides.resolveConnectionKey ?? vi.fn().mockResolvedValue('deployment-default')+ const resolveAssignment =+ overrides.resolveAssignment ??+ (async (hostRef: string) => ({+ liveBrokerProviders: ['codex-subscription'],+ liveConnectionRef: await resolveConnectionKey(hostRef),+ }))return {enabled: true,db,withTransaction: async work => work(db as never),getConnection: vi.fn().mockResolvedValue(connection()),getModelState: vi.fn().mockResolvedValue({ enabled: true, stale: false }),- resolveConnectionKey: vi.fn().mockResolvedValue('deployment-default'),evaluateBudget: vi.fn().mockResolvedValue({ allowed: true, reservationIds: ['res-1'] }),getActiveReservation: vi.fn().mockResolvedValue({ id: 'res-1' }),getMaxGeneration: vi.fn().mockResolvedValue(0),@@ -136,6 +143,8 @@ function deps(claims: { jti: 'jti-ticket' },}),...overrides,+ resolveConnectionKey,+ resolveAssignment,}}@@ -500,14 +509,14 @@ describe('authorizeLlmProviderAttempt', () => {})it('rejects an unassigned Host connectionRef as unassigned_connection', async () => {- await expect(- authorizeLlmProviderAttempt(claims(), body(), {- ...current,- resolveConnectionKey: async () => 'unassigned',- })- ).rejects.toMatchObject({ code: 'unassigned_connection' })- expect(current.getConnection).not.toHaveBeenCalled()- expect(current.insertAttempt).not.toHaveBeenCalled()+ const unassigned = deps({+ resolveConnectionKey: async () => 'unassigned',+ })+ await expect(authorizeLlmProviderAttempt(claims(), body(), unassigned)).rejects.toMatchObject({+ code: 'unassigned_connection',+ })+ expect(unassigned.getConnection).not.toHaveBeenCalled()+ expect(unassigned.insertAttempt).not.toHaveBeenCalled()})it('fails closed for every Host on a revoked grant and leaves another grant usable', async () => {diff --git a/control-api/test/services.recipeCodexGrantIdentity.test.ts b/control-api/test/services.recipeCodexGrantIdentity.test.tsindex 1bdcb21b9..0113d8cc4 100644--- a/control-api/test/services.recipeCodexGrantIdentity.test.ts+++ b/control-api/test/services.recipeCodexGrantIdentity.test.ts@@ -115,7 +115,10 @@ describe('recipe Codex grant identity', () => {{metadata: {labels: { app: 'recipe' },- annotations: { 'clerum.io/codex-connection-ref': '' },+ annotations: {+ 'clerum.io/codex-connection-ref': '',+ 'clerum.io/subscription-connection-ref': '',+ },resourceVersion: '9',},spec: { pluginWorkloadSdk: { family: 'promptBridge' } },diff --git a/control-api/test/subscriptionGrantIdentity.test.ts b/control-api/test/subscriptionGrantIdentity.test.tsindex 4f3b50f2d..644eff149 100644--- a/control-api/test/subscriptionGrantIdentity.test.ts+++ b/control-api/test/subscriptionGrantIdentity.test.ts@@ -99,12 +99,21 @@ describe('readSubscriptionConnectionRef', () => {})describe('collectRecipeOauthBrokerProviders', () => {- it('includes Codex promptTargets when the recipe agent is static', () => {+ it('includes Codex step agents when the recipe agent is static', () => {expect(collectRecipeOauthBrokerProviders({agent: { provider: 'openai' },- promptTargets: [{ provider: 'codex-subscription' }],+ steps: [{ agent: { provider: 'codex-subscription' } }],})).toEqual(['codex-subscription'])})++ it('does not treat promptTargets as a recipe spec field', () => {+ expect(+ collectRecipeOauthBrokerProviders({+ agent: { provider: 'openai' },+ promptTargets: [{ provider: 'codex-subscription' }],+ })+ ).toEqual([])+ })})diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex a485c2635..47760cf25 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.331",+ "version": "0.1.332","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.331",+ "version": "0.1.332","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 75e24cbd9..8946336ac 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.331",+ "version": "0.1.332","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.oauthBrokerExtract.test.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.oauthBrokerExtract.test.tsnew file mode 100644index 000000000..382cd8150--- /dev/null+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.oauthBrokerExtract.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it, vi } from 'vitest'++vi.mock('@clerum/llm-providers', async () => {+ const actual =+ await vi.importActual<typeof import('@clerum/llm-providers')>('@clerum/llm-providers')+ return {+ ...actual,+ isLlmProviderId: (id: unknown): boolean =>+ actual.isLlmProviderId(id) || id === 'fixture-broker',+ PROVIDER_AUTH_MODE: {+ ...actual.PROVIDER_AUTH_MODE,+ 'fixture-broker': 'oauth-broker',+ },+ }+})++vi.mock('../llm/registryCore.js', async () => {+ const actual =+ await vi.importActual<typeof import('../llm/registryCore.js')>('../llm/registryCore.js')+ return {+ ...actual,+ isLlmProvider: (id: string) => actual.isLlmProvider(id) || id === 'fixture-broker',+ }+})++const { configurePluginWorkloadSdkBootstrapIdentity } = await import('./bootstrapIdentity.js')++describe('oauth-broker extract bootstrap', () => {+ it('uses contractVersion 3 for an injected fixture broker', async () => {+ const result = await configurePluginWorkloadSdkBootstrapIdentity(+ {+ capabilityFamily: 'promptBridge',+ provider: 'fixture-broker',+ model: 'fixture-1',+ },+ { capabilityFamily: 'promptBridge' }+ )+ expect(result.contractVersion).toBe(3)+ expect(result.policyReason).toBe('codex_execution_binding_missing')+ })+})diff --git a/scripts/tests/test-llm-subscription-extract-t0.sh b/scripts/tests/test-llm-subscription-extract-t0.shnew file mode 100755index 000000000..beec28d7f--- /dev/null+++ b/scripts/tests/test-llm-subscription-extract-t0.sh@@ -0,0 +1,163 @@+#!/usr/bin/env bash+# Wave-1 oauth-broker extract T0 aggregator.+# Fails when a required suite is missing, executes zero tests, reports+# skipped/todo cases, or exits non-zero.+set -u++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+FAIL=0+GROUPS_RUN=0++pass() { echo "PASS: $1"; }+fail() { echo "FAIL: $1"; FAIL=1; }++require_file() {+ local rel="$1"+ if [[ ! -f "${ROOT}/${rel}" ]]; then+ fail "missing required suite ${rel}"+ return 1+ fi+ return 0+}++strip_ansi() {+ sed $'s/\033\\[[0-9;]*m//g'+}++assert_executed_counts() {+ local name="$1"+ local log="$2"+ local normalized+ normalized="$(mktemp)"+ strip_ansi <"$log" >"$normalized"++ local vitest_passed+ vitest_passed="$(+ grep -Eo 'Tests[[:space:]]+[1-9][0-9]* passed' "$normalized" | head -n 1 || true+ )"+ local node_pass+ node_pass="$(+ grep -E 'pass[[:space:]]+[1-9][0-9]*$' "$normalized" | awk '{print $NF}' | tail -n 1 || true+ )"++ if [[ -z "${vitest_passed}" && -z "${node_pass}" ]]; then+ fail "${name}: executed zero passing tests"+ echo "----- ${name} reporter -----"+ cat "$normalized"+ rm -f "$normalized"+ return 1+ fi++ if grep -Eq '(Test Files|Tests).*[1-9][0-9]* skipped' "$normalized"; then+ fail "${name}: Vitest reported skipped tests"+ rm -f "$normalized"+ return 1+ fi+ if grep -Eq '(Test Files|Tests).*[1-9][0-9]* todo' "$normalized"; then+ fail "${name}: Vitest reported todo tests"+ rm -f "$normalized"+ return 1+ fi+ if grep -Eq '^(#|ℹ) skipped[[:space:]]+[1-9]' "$normalized"; then+ fail "${name}: node:test reported skipped tests"+ rm -f "$normalized"+ return 1+ fi+ if grep -Eq '^(#|ℹ) todo[[:space:]]+[1-9]' "$normalized"; then+ fail "${name}: node:test reported todo tests"+ rm -f "$normalized"+ return 1+ fi+ if grep -Eiq 'no test files|no tests found' "$normalized"; then+ fail "${name}: reporter found no tests"+ rm -f "$normalized"+ return 1+ fi++ rm -f "$normalized"+ return 0+}++run_group() {+ local name="$1"+ local prefix="$2"+ shift 2+ local files=("$@")+ local rel+ if [[ "${#files[@]}" -eq 0 ]]; then+ fail "${name}: group listed no suite files"+ return 1+ fi+ for rel in "${files[@]}"; do+ require_file "${prefix}/${rel}" || return 1+ done++ local log+ log="$(mktemp)"+ local npm_args=(--prefix "${ROOT}/${prefix}" test --)+ npm_args+=("${files[@]}")++ echo "── ${name} ──"+ if ! (+ cd "${ROOT}"+ FORCE_COLOR=0 NO_COLOR=1 npm "${npm_args[@]}"+ ) >"$log" 2>&1; then+ fail "${name}: command failed"+ cat "$log"+ rm -f "$log"+ return 1+ fi++ if ! assert_executed_counts "$name" "$log"; then+ rm -f "$log"+ return 1+ fi++ GROUPS_RUN=$((GROUPS_RUN + 1))+ pass "${name}"+ rm -f "$log"+}++require_ci_matrix_entry() {+ local entry="$1"+ if ! grep -Eq "^[[:space:]]+- ${entry}$" "${ROOT}/.github/workflows/ci-public.yml"; then+ fail "ci-public.yml matrix is missing ${entry}"+ return 1+ fi+ pass "ci-public.yml matrix includes ${entry}"+}++echo "LLM subscription extract T0 aggregator"++require_ci_matrix_entry "packages/llm-providers"++run_group "llm-providers" "packages/llm-providers" "index.test.cjs"++run_group "control-api-extract" "control-api" \+ "test/subscriptionGrantIdentity.test.ts" \+ "test/hostSpecValidation.oauthBrokerExtract.test.ts" \+ "test/routes.mcp-host.llmProviderAttempts.attestation.test.ts" \+ "test/routes.admin.codexSubscription.oauthBrokerExtract.test.ts" \+ "test/services.codexSubscriptionOAuth.test.ts"++run_group "mcp-host-extract" "mcp-host" \+ "src/pluginWorkloadSdk/bootstrapIdentity.oauthBrokerExtract.test.ts"++echo "── deploy-contract ──"+require_file "scripts/tests/test-codex-llm-proxy-deploy-contract.sh" || true+if bash "${ROOT}/scripts/tests/test-codex-llm-proxy-deploy-contract.sh"; then+ GROUPS_RUN=$((GROUPS_RUN + 1))+ pass "deploy-contract"+else+ fail "deploy-contract"+fi++if [[ "${GROUPS_RUN}" -ne 4 ]]; then+ fail "expected 4 T0 groups, ran ${GROUPS_RUN}"+fi++if [[ "${FAIL}" -ne 0 ]]; then+ echo "LLM subscription extract T0 FAILED"+ exit 1+fi+echo "LLM subscription extract T0 passed (${GROUPS_RUN} groups)"