Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): validate Grok Host subsets and fallbacks against the Host grant
Jose Gabriel Ramirez Encinasc0416181041f
diff --git a/charts/clerum-crds/crds/host.yaml b/charts/clerum-crds/crds/host.yamlindex 4af629905..736cb0bb2 100644--- a/charts/clerum-crds/crds/host.yaml+++ b/charts/clerum-crds/crds/host.yaml@@ -28,11 +28,11 @@ spec:- host- contextRefx-kubernetes-validations:- - rule: "(has(self.model) && self.model.provider == 'codex-subscription' && (!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider != 'codex-subscription'))) || (has(self.model) && self.model.provider == 'grok-subscription' && (!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider != 'grok-subscription'))) || (has(self.secretRef) && size(self.secretRef) > 0)"+ - rule: "(has(self.model) && has(self.model.provider) && self.model.provider == 'codex-subscription' && (!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider != 'codex-subscription'))) || (has(self.model) && has(self.model.provider) && self.model.provider == 'grok-subscription' && (!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider != 'grok-subscription'))) || (has(self.secretRef) && size(self.secretRef) > 0)"message: spec.secretRef is required unless every LLM target is the same oauth-broker provider- rule: "!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, (f.provider == 'codex-subscription' || f.provider == 'grok-subscription') && has(f.credentialSlot))"message: credentialSlot is not supported for oauth-broker providers- - rule: "!(((has(self.model) && self.model.provider == 'codex-subscription') || (has(self.llmPolicy) && has(self.llmPolicy.fallbacks) && self.llmPolicy.fallbacks.exists(f, f.provider == 'codex-subscription')) || (has(self.allowedModels) && self.allowedModels.exists(m, m.provider == 'codex-subscription'))) && ((has(self.model) && self.model.provider == 'grok-subscription') || (has(self.llmPolicy) && has(self.llmPolicy.fallbacks) && self.llmPolicy.fallbacks.exists(f, f.provider == 'grok-subscription')) || (has(self.allowedModels) && self.allowedModels.exists(m, m.provider == 'grok-subscription'))))"+ - rule: "!(((has(self.model) && has(self.model.provider) && self.model.provider == 'codex-subscription') || (has(self.llmPolicy) && has(self.llmPolicy.fallbacks) && self.llmPolicy.fallbacks.exists(f, f.provider == 'codex-subscription')) || (has(self.allowedModels) && self.allowedModels.exists(m, m.provider == 'codex-subscription'))) && ((has(self.model) && has(self.model.provider) && self.model.provider == 'grok-subscription') || (has(self.llmPolicy) && has(self.llmPolicy.fallbacks) && self.llmPolicy.fallbacks.exists(f, f.provider == 'grok-subscription')) || (has(self.allowedModels) && self.allowedModels.exists(m, m.provider == 'grok-subscription'))))"message: a Host may declare at most one oauth-broker providerproperties:host:diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 6d49b16ad..df5c2fd8b 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.571",+ "version": "0.1.572","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.571",+ "version": "0.1.572","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.jsonindex bd0138c83..a9ca5d154 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.571",+ "version": "0.1.572","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.tsindex a164d6243..cfac73eca 100644--- a/control-api/src/routes/admin/hostSpecValidation.ts+++ b/control-api/src/routes/admin/hostSpecValidation.ts@@ -78,6 +78,68 @@ function oauthBrokerFlagEnabled(provider: string): boolean {return true}+function isOauthBrokerProviderId(provider: string): provider is LlmProviderId {+ return isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker'+}++function readHostBrokerConnectionRef(provider: LlmProviderId, value: unknown): string {+ const raw = typeof value === 'string' ? value : null+ return provider === 'grok-subscription'+ ? readHostGrokConnectionRef(raw)+ : readHostCodexConnectionRef(raw)+}++function isUnassignedBrokerConnectionRef(provider: LlmProviderId, connectionRef: string): boolean {+ return provider === 'grok-subscription'+ ? isGrokUnassignedConnectionKey(connectionRef)+ : isCodexUnassignedConnectionKey(connectionRef)+}++/**+ * The Host's single oauth-broker grant, resolved ONCE per write and shared by the+ * primary, per-host subset (allowedModels) and fallback gates (RP-001). Admission+ * (`validateCodexBrokerAdmission`) already guarantees at most one broker id per+ * Host, so the provider is the primary's when it is a broker, else the one broker+ * named by a fallback/subset entry. The grant key always lives in+ * `spec.model.connectionRef` (empty/missing reads as `unassigned`). `null` means+ * the Host references no oauth-broker target.+ */+type HostBrokerContext = { provider: LlmProviderId; connectionRef: string } | null++function resolveHostBrokerContext(spec: Record<string, unknown>): HostBrokerContext {+ const model = isPlainObject(spec.model) ? spec.model : undefined+ const primary = typeof model?.provider === 'string' ? model.provider.trim() : ''+ const provider = isOauthBrokerProviderId(primary)+ ? primary+ : collectHostLlmTargets(spec)+ .map(target => target.provider)+ .find(isOauthBrokerProviderId)+ if (!provider) return null+ return { provider, connectionRef: readHostBrokerConnectionRef(provider, model?.connectionRef) }+}++/**+ * Allowlist/grant gate for one `(provider, model)` entry. A broker entry is+ * checked against the Host's grant key (skipped when the Host is `unassigned`:+ * an unassigned Host cannot spend, so there is nothing to validate). A static+ * entry never receives a grant key.+ */+async function isHostEntryAllowed(+ deps: HostSpecValidationDeps,+ broker: HostBrokerContext,+ provider: string,+ model: string+): Promise<boolean> {+ if (!isOauthBrokerProviderId(provider)) return deps.isModelAllowed(provider, model, undefined)+ // Admission guarantees broker?.provider === provider here; a mismatch fails+ // closed by letting the deps resolve a missing key as unassigned.+ const connectionRef = broker?.provider === provider ? broker.connectionRef : undefined+ if (connectionRef !== undefined && isUnassignedBrokerConnectionRef(provider, connectionRef)) {+ return true+ }+ return deps.isModelAllowed(provider, model, connectionRef)+}+type HostLlmTarget = {provider: stringfield: string@@ -194,6 +256,54 @@ function validateCodexBrokerAdmission(return null}+/**+ * Array caps mirrored from charts/clerum-crds/crds/host.yaml `maxItems`+ * (`spec.allowedModels` and `spec.llmPolicy.fallbacks`; parity pinned by+ * test/hostSpecValidation.limits.test.ts). control-api answers a field-level 422+ * instead of surfacing the apiserver's schema rejection.+ */+export const HOST_ALLOWED_MODELS_MAX_ITEMS = 32+export const HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS = 8++function hostLlmPolicyFallbacks(spec: Record<string, unknown> | undefined): unknown {+ return isPlainObject(spec) && isPlainObject(spec.llmPolicy) ? spec.llmPolicy.fallbacks : undefined+}++/**+ * Reject an array over its CRD cap only when this write GREW it versus the+ * stored Host: a Host persisted before the cap existed may still be saved+ * unchanged or shrunk (no-worsening, like the allowlist tolerance). On create+ * there is no stored array, so any over-cap array is rejected.+ */+function validateHostArrayCaps(+ spec: Record<string, unknown>,+ stored: Record<string, unknown> | undefined+): { errors: Array<{ field: string; message: string }> } | null {+ const caps: Array<{ field: string; max: number; incoming: unknown; before: unknown }> = [+ {+ field: 'spec.allowedModels',+ max: HOST_ALLOWED_MODELS_MAX_ITEMS,+ incoming: spec.allowedModels,+ before: isPlainObject(stored) ? stored.allowedModels : undefined,+ },+ {+ field: 'spec.llmPolicy.fallbacks',+ max: HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS,+ incoming: hostLlmPolicyFallbacks(spec),+ before: hostLlmPolicyFallbacks(stored),+ },+ ]+ for (const cap of caps) {+ if (!Array.isArray(cap.incoming) || cap.incoming.length <= cap.max) continue+ const storedLength = Array.isArray(cap.before) ? cap.before.length : 0+ if (cap.incoming.length <= storedLength) continue+ return {+ errors: [{ field: cap.field, message: `${cap.field} must contain at most ${cap.max} items` }],+ }+ }+ return null+}+const HostApprovalSchema = z.object({defaultPolicy: z.string().optional(),@@ -357,8 +467,12 @@ export async function validateHostSpec(}if (structuralErrors.length > 0) return { errors: structuralErrors }+ const capErrors = validateHostArrayCaps(spec, context.stored)+ if (capErrors) return capErrors+const brokerErrors = validateCodexBrokerAdmission(spec)if (brokerErrors) return brokerErrors+ const broker = resolveHostBrokerContext(spec)// No-worsening tolerance context (Pieza D), computed once and shared by the 3// global-allowlist gates below. On create `context.stored` is absent, so@@ -403,36 +517,28 @@ export async function validateHostSpec(],}}+ const primaryIsBroker = isOauthBrokerProviderId(provider)const connectionRef =- provider === 'codex-subscription'- ? resolvedCodexConnectionRef(model)- : provider === 'grok-subscription'- ? readHostGrokConnectionRef(- typeof model.connectionRef === 'string' ? model.connectionRef : undefined- )- : undefined- if (provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)) {+ primaryIsBroker && broker?.provider === provider ? broker.connectionRef : undefined+ if (+ primaryIsBroker &&+ connectionRef !== undefined &&+ isUnassignedBrokerConnectionRef(provider, connectionRef)+ ) {// Persist the sentinel so empty and unassigned are not two Host states.- model.connectionRef = CODEX_UNASSIGNED_CONNECTION_KEY+ model.connectionRef =+ provider === 'grok-subscription'+ ? GROK_UNASSIGNED_CONNECTION_KEY+ : CODEX_UNASSIGNED_CONNECTION_KEY}- if (provider === 'grok-subscription' && isGrokUnassignedConnectionKey(connectionRef)) {- model.connectionRef = GROK_UNASSIGNED_CONNECTION_KEY- }- const skipCodexAllowlist =- (provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)) ||- (provider === 'grok-subscription' && isGrokUnassignedConnectionKey(connectionRef))- const allowed = skipCodexAllowlist- ? true- : await deps.isModelAllowed(provider, name, connectionRef)+ const allowed = await isHostEntryAllowed(deps, broker, provider, name)// Switching connectionRef is a new assignment even when (provider, model)// already lived on the Host. A revoked/unknown grant must not ride the// identity/channels full-replace tolerance. An unchanged revoked ref stays// tolerable so operators can still save unrelated fields.const storedConnectionRef = storedBrokerConnectionRef(context.stored)const connectionAssignmentChanged =- (provider === 'codex-subscription' || provider === 'grok-subscription') &&- storedConnectionRef !== undefined &&- storedConnectionRef !== connectionRef+ primaryIsBroker && storedConnectionRef !== undefined && storedConnectionRef !== connectionRefif (!allowed &&(connectionAssignmentChanged || !toleratePair(provider, name, 'primary', tol))@@ -457,16 +563,13 @@ export async function validateHostSpec(// (same fail-closed gate as spec.model.name), so a broken fallback is caught// on write instead of surfacing only during the incident it was meant to// absorb (spec V16). `credentialSlot`, when present, is format-checked only.- const hostCodexConnectionRef = resolvedCodexConnectionRef(- isPlainObject(spec.model) ? spec.model : undefined- )- const policyErrors = await validateLlmPolicy(spec.llmPolicy, deps, tol, hostCodexConnectionRef)+ const policyErrors = await validateLlmPolicy(spec.llmPolicy, deps, tol, broker)if (policyErrors) return policyErrors// Topic 3a per-host allowlist. Runs AFTER the global-allowlist gates above, so// by the time coherence is checked the primary + fallbacks are already known// to be valid GLOBAL pairs; this narrows them to the host's offered subset.- const allowedModelsErrors = await validateAllowedModels(spec, deps, tol, hostCodexConnectionRef)+ const allowedModelsErrors = await validateAllowedModels(spec, deps, tol, broker)if (allowedModelsErrors) return allowedModelsErrors// The write PASSED validation: hand the queued tolerations to the caller via@@ -618,38 +721,22 @@ async function maybeWarnStale(}}-/**- * Decide whether a disallowed `(provider, model)` may be tolerated at `gate`- * because the write does not worsen a pre-existing incoherence AND the pair does- * not GAIN activeness (role-scoped, mini-spec 01 v2). On tolerance, QUEUES the- * audit event (not emitted until the whole write persists) and returns true so- * the gate skips its rejection.- */-function resolvedCodexConnectionRef(model: unknown): string {- if (!isPlainObject(model)) return CODEX_UNASSIGNED_CONNECTION_KEY- return readHostCodexConnectionRef(- typeof model.connectionRef === 'string' ? model.connectionRef : null- )-}-function storedBrokerConnectionRef(stored: Record<string, unknown> | undefined): string | undefined {if (!isPlainObject(stored) || !isPlainObject(stored.model)) return undefinedconst provider = typeof stored.model.provider === 'string' ? stored.model.provider.trim() : ''- if (provider === 'codex-subscription') {- return readHostCodexConnectionRef(- typeof stored.model.connectionRef === 'string' ? stored.model.connectionRef : null- )- }- if (provider === 'grok-subscription') {- return readHostGrokConnectionRef(- typeof stored.model.connectionRef === 'string' ? stored.model.connectionRef : null- )- }- return undefined+ if (!isOauthBrokerProviderId(provider)) return undefined+ return readHostBrokerConnectionRef(provider, stored.model.connectionRef)}+/**+ * Decide whether a disallowed `(provider, model)` may be tolerated at `gate`+ * because the write does not worsen a pre-existing incoherence AND the pair does+ * not GAIN activeness (role-scoped, mini-spec 01 v2). On tolerance, QUEUES the+ * audit event (not emitted until the whole write persists) and returns true so+ * the gate skips its rejection.+ */function toleratePair(provider: string,model: string,@@ -699,7 +786,7 @@ async function validateAllowedModels(spec: Record<string, unknown>,deps: HostSpecValidationDeps,tol: HostToleranceBundle,- connectionRef: string+ broker: HostBrokerContext): Promise<{ errors: Array<{ field: string; message: string }> } | null> {const allowedModels = spec.allowedModelsif (allowedModels === undefined) return null@@ -741,14 +828,7 @@ async function validateAllowedModels(// catalog can never be offered by a host — unless tolerating a pre-existing// incoherence this write does not worsen (Pieza D). A tolerated pair is still// added to `offered` so the coherence gate below sees the host as offering it.- const allowed =- provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)- ? true- : await deps.isModelAllowed(- provider,- model,- provider === 'codex-subscription' ? connectionRef : undefined- )+ const allowed = await isHostEntryAllowed(deps, broker, provider, model)if (!allowed && !toleratePair(provider, model, 'subset', tol)) {return {errors: [@@ -828,7 +908,7 @@ async function validateLlmPolicy(llmPolicy: unknown,deps: HostSpecValidationDeps,tol: HostToleranceBundle,- connectionRef: string+ broker: HostBrokerContext): Promise<{ errors: Array<{ field: string; message: string }> } | null> {if (llmPolicy === undefined) return nullif (!isPlainObject(llmPolicy)) {@@ -917,14 +997,7 @@ async function validateLlmPolicy(// Allowlist gate LAST: it is the only async (DB) check, so cheap structural// rejections above avoid a needless query. Tolerated (Pieza D) when the pair// is a pre-existing incoherence this write does not worsen.- const allowed =- provider === 'codex-subscription' && isCodexUnassignedConnectionKey(connectionRef)- ? true- : await deps.isModelAllowed(- provider,- model,- provider === 'codex-subscription' ? connectionRef : undefined- )+ const allowed = await isHostEntryAllowed(deps, broker, provider, model)if (!allowed && !toleratePair(provider, model, 'fallback', tol)) {return {errors: [diff --git a/control-api/test/crd.hostCel.test.ts b/control-api/test/crd.hostCel.test.tsnew file mode 100644index 000000000..6e36f354a--- /dev/null+++ b/control-api/test/crd.hostCel.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { dirname, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import { parse } from 'yaml'++// B-M2: `spec.model.provider` is optional in host.yaml, and CEL errors on a+// missing field instead of treating it as false. Every Host CEL rule must guard a+// `self.model.provider` read with `has(self.model.provider)` so a Host whose+// `spec.model` omits provider (accepted before the oauth-broker rules) is not+// rejected by an evaluation error. No CEL runtime is available here, so this is a+// static contract over the rule text.+const crdsDir = resolve(dirname(fileURLToPath(import.meta.url)), '../../charts/clerum-crds/crds')++function collectRules(node: unknown, out: string[] = []): string[] {+ if (Array.isArray(node)) {+ node.forEach(child => collectRules(child, out))+ return out+ }+ if (node && typeof node === 'object') {+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {+ if (key === 'x-kubernetes-validations' && Array.isArray(value)) {+ for (const entry of value) {+ if (entry && typeof (entry as { rule?: unknown }).rule === 'string') {+ out.push((entry as { rule: string }).rule)+ }+ }+ }+ collectRules(value, out)+ }+ }+ return out+}++const GUARDED_READ =+ /has\(self\.model\) && has\(self\.model\.provider\) && self\.model\.provider ==/g++describe('host.yaml CEL rules', () => {+ const rules = collectRules(parse(readFileSync(resolve(crdsDir, 'host.yaml'), 'utf8')))++ it('reads self.model.provider in at least one rule (the guard contract is not vacuous)', () => {+ expect(rules.some(rule => rule.includes('self.model.provider'))).toBe(true)+ })++ it('guards every self.model.provider read with has(self.model) and has(self.model.provider)', () => {+ for (const rule of rules) {+ const reads = rule.match(/(?<!has\()self\.model\.provider\b/g) ?? []+ const guarded = rule.match(GUARDED_READ) ?? []+ expect({ rule, reads: reads.length }).toEqual({ rule, reads: guarded.length })+ }+ })+})diff --git a/control-api/test/hostSpecValidation.grokSubscription.test.ts b/control-api/test/hostSpecValidation.grokSubscription.test.tsindex 80ba89856..07117c721 100644--- a/control-api/test/hostSpecValidation.grokSubscription.test.ts+++ b/control-api/test/hostSpecValidation.grokSubscription.test.ts@@ -50,3 +50,167 @@ describe('grok-subscription Host admission', () => {expect(isModelAllowed).toHaveBeenCalledWith('grok-subscription', 'grok-4.6', 'revoked-grok')})})++// RP-001: the Host's oauth-broker grant must reach the per-host subset+// (allowedModels) and the same-broker fallback gates, not only the primary.+// The stub answers per grant key, so a gate that drops or swaps the key fails.+describe('oauth-broker connectionRef reaches allowedModels and fallbacks (RP-001)', () => {+ afterEach(() => {+ delete process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED+ })++ const brokers = [+ {+ provider: 'grok-subscription',+ flag: 'CONTROL_API_GROK_SUBSCRIPTION_ENABLED',+ key: 'team-grok',+ primary: 'grok-4.6',+ extra: 'grok-4.6-mini',+ },+ {+ provider: 'codex-subscription',+ flag: 'CONTROL_API_CODEX_SUBSCRIPTION_ENABLED',+ key: 'team-codex',+ primary: 'gpt-5.5',+ extra: 'gpt-5.5-mini',+ },+ ] as const++ const grantOffers = (key: string) =>+ vi.fn(async (_provider: string, _model: string, connectionRef?: string) => {+ return connectionRef === key+ })++ for (const b of brokers) {+ describe(b.provider, () => {+ it('accepts a subset entry the selected grant offers and checks it against that grant', async () => {+ process.env[b.flag] = 'true'+ const isModelAllowed = grantOffers(b.key)+ const res = await validateHostSpec(+ {+ model: { provider: b.provider, name: b.primary, connectionRef: b.key },+ allowedModels: [+ { provider: b.provider, model: b.primary },+ { provider: b.provider, model: b.extra },+ ],+ },+ { isModelAllowed }+ )+ expect(res).toBeNull()+ expect(isModelAllowed).toHaveBeenCalledWith(b.provider, b.extra, b.key)+ })++ it('accepts a same-broker fallback the selected grant offers and checks it against that grant', async () => {+ process.env[b.flag] = 'true'+ const isModelAllowed = grantOffers(b.key)+ const res = await validateHostSpec(+ {+ model: { provider: b.provider, name: b.primary, connectionRef: b.key },+ llmPolicy: { fallbacks: [{ provider: b.provider, model: b.extra }] },+ },+ { isModelAllowed }+ )+ expect(res).toBeNull()+ expect(isModelAllowed).toHaveBeenCalledWith(b.provider, b.extra, b.key)+ })++ it('rejects a subset entry only another grant offers (model_not_allowed)', async () => {+ process.env[b.flag] = 'true'+ const isModelAllowed = vi.fn(+ async (_provider: string, model: string, connectionRef?: string) =>+ model === b.extra ? connectionRef === 'other-grant' : connectionRef === b.key+ )+ const res = await validateHostSpec(+ {+ model: { provider: b.provider, name: b.primary, connectionRef: b.key },+ allowedModels: [+ { provider: b.provider, model: b.primary },+ { provider: b.provider, model: b.extra },+ ],+ },+ { isModelAllowed }+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].field).toBe('spec.allowedModels[1].model')+ expect(res!.errors[0].message).toContain('model_not_allowed')+ })++ it('rejects a same-broker fallback when the selected grant is revoked (model_not_allowed)', async () => {+ process.env[b.flag] = 'true'+ // The revoked grant still covers the primary through no-worsening+ // tolerance on an unchanged stored Host; the NEW fallback must not ride it.+ const isModelAllowed = vi.fn(async () => false)+ const stored = {+ model: { provider: b.provider, name: b.primary, connectionRef: 'revoked-grant' },+ }+ const res = await validateHostSpec(+ {+ model: { provider: b.provider, name: b.primary, connectionRef: 'revoked-grant' },+ llmPolicy: { fallbacks: [{ provider: b.provider, model: b.extra }] },+ },+ { isModelAllowed },+ { stored, hostRef: { namespace: 'mcp-host', name: 'agent' }, tolerations: [] }+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].field).toBe('spec.llmPolicy.fallbacks[0].model')+ expect(isModelAllowed).toHaveBeenCalledWith(b.provider, b.extra, 'revoked-grant')+ })++ it('does not leak the broker connectionRef to a static-provider subset entry', async () => {+ process.env[b.flag] = 'true'+ const isModelAllowed = vi.fn(async () => true)+ const res = await validateHostSpec(+ {+ model: { provider: b.provider, name: b.primary, connectionRef: b.key },+ secretRef: 'llm-keys',+ allowedModels: [+ { provider: b.provider, model: b.primary },+ { provider: 'openai', model: 'gpt-5.1' },+ ],+ llmPolicy: { fallbacks: [{ provider: 'openai', model: 'gpt-5.1' }] },+ },+ { isModelAllowed }+ )+ expect(res).toBeNull()+ expect(isModelAllowed).toHaveBeenCalledWith('openai', 'gpt-5.1', undefined)+ expect(isModelAllowed).not.toHaveBeenCalledWith('openai', 'gpt-5.1', b.key)+ })++ it('skips grant lookups for broker subset/fallback entries on an unassigned Host', async () => {+ process.env[b.flag] = 'true'+ const isModelAllowed = vi.fn(async () => false)+ const res = await validateHostSpec(+ {+ model: { provider: b.provider, name: b.primary },+ allowedModels: [+ { provider: b.provider, model: b.primary },+ { provider: b.provider, model: b.extra },+ ],+ llmPolicy: { fallbacks: [{ provider: b.provider, model: b.extra }] },+ },+ { isModelAllowed }+ )+ expect(res).toBeNull()+ expect(isModelAllowed).not.toHaveBeenCalled()+ })+ })+ }++ it('uses the Grok grant for a Grok fallback behind a static primary', async () => {+ process.env.CONTROL_API_GROK_SUBSCRIPTION_ENABLED = 'true'+ const isModelAllowed = vi.fn(+ async (provider: string, _model: string, connectionRef?: string) =>+ provider === 'openai' ? connectionRef === undefined : connectionRef === 'team-grok'+ )+ const res = await validateHostSpec(+ {+ model: { provider: 'openai', name: 'gpt-5.1', connectionRef: 'team-grok' },+ secretRef: 'llm-keys',+ llmPolicy: { fallbacks: [{ provider: 'grok-subscription', model: 'grok-4.6' }] },+ },+ { isModelAllowed }+ )+ expect(res).toBeNull()+ expect(isModelAllowed).toHaveBeenCalledWith('grok-subscription', 'grok-4.6', 'team-grok')+ })+})diff --git a/control-api/test/hostSpecValidation.limits.test.ts b/control-api/test/hostSpecValidation.limits.test.tsnew file mode 100644index 000000000..f00e02776--- /dev/null+++ b/control-api/test/hostSpecValidation.limits.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { dirname, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import { parse } from 'yaml'+import {+ HOST_ALLOWED_MODELS_MAX_ITEMS,+ HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS,+ validateHostSpec,+} from '../src/routes/admin/hostSpecValidation.js'++// B-M8 / NV-03: host.yaml caps allowedModels (32) and llmPolicy.fallbacks (8).+// control-api mirrors them as a field-level 422 before any allowlist lookup, but+// only when the array GREW past the cap versus the stored Host, so an existing+// over-limit Host (written before the cap) can still be saved unchanged or shrunk.++const crdsDir = resolve(dirname(fileURLToPath(import.meta.url)), '../../charts/clerum-crds/crds')++const subset = (n: number) =>+ Array.from({ length: n }, (_, i) => ({ provider: 'openai', model: `gpt-${i}` }))+const fallbacks = (n: number) =>+ Array.from({ length: n }, (_, i) => ({ provider: 'openai', model: `gpt-${i}` }))+const hostRef = { namespace: 'mcp-host', name: 'agent' }++describe('Host array caps mirror the CRD maxItems', () => {+ it('exports the CRD caps', () => {+ expect(HOST_ALLOWED_MODELS_MAX_ITEMS).toBe(32)+ expect(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS).toBe(8)+ })++ it('matches host.yaml maxItems for allowedModels and llmPolicy.fallbacks', () => {+ const doc = parse(readFileSync(resolve(crdsDir, 'host.yaml'), 'utf8'))+ const spec = doc.spec.versions[0].schema.openAPIV3Schema.properties.spec.properties+ expect(spec.allowedModels.maxItems).toBe(HOST_ALLOWED_MODELS_MAX_ITEMS)+ expect(spec.llmPolicy.properties.fallbacks.maxItems).toBe(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS)+ })++ it('accepts allowedModels and fallbacks exactly at the cap on create', async () => {+ const isModelAllowed = vi.fn().mockResolvedValue(true)+ const res = await validateHostSpec(+ {+ allowedModels: subset(HOST_ALLOWED_MODELS_MAX_ITEMS),+ llmPolicy: { fallbacks: fallbacks(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS) },+ },+ { isModelAllowed }+ )+ expect(res).toBeNull()+ })++ it('rejects allowedModels over the cap on create with a field-level 422 and no lookup', async () => {+ const isModelAllowed = vi.fn().mockResolvedValue(true)+ const res = await validateHostSpec(+ { allowedModels: subset(HOST_ALLOWED_MODELS_MAX_ITEMS + 1) },+ { isModelAllowed }+ )+ expect(res).toEqual({+ errors: [+ {+ field: 'spec.allowedModels',+ message: `spec.allowedModels must contain at most ${HOST_ALLOWED_MODELS_MAX_ITEMS} items`,+ },+ ],+ })+ expect(isModelAllowed).not.toHaveBeenCalled()+ })++ it('rejects llmPolicy.fallbacks over the cap on create with a field-level 422 and no lookup', async () => {+ const isModelAllowed = vi.fn().mockResolvedValue(true)+ const res = await validateHostSpec(+ { llmPolicy: { fallbacks: fallbacks(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS + 1) } },+ { isModelAllowed }+ )+ expect(res).toEqual({+ errors: [+ {+ field: 'spec.llmPolicy.fallbacks',+ message: `spec.llmPolicy.fallbacks must contain at most ${HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS} items`,+ },+ ],+ })+ expect(isModelAllowed).not.toHaveBeenCalled()+ })++ it('rejects an update that grows past the cap from an under-cap stored Host', async () => {+ const isModelAllowed = vi.fn().mockResolvedValue(true)+ const res = await validateHostSpec(+ { allowedModels: subset(HOST_ALLOWED_MODELS_MAX_ITEMS + 1) },+ { isModelAllowed },+ { stored: { allowedModels: subset(3) }, hostRef, tolerations: [] }+ )+ expect(res?.errors[0].field).toBe('spec.allowedModels')+ })++ it('rejects an update that grows an already over-cap stored array', async () => {+ const isModelAllowed = vi.fn().mockResolvedValue(true)+ const res = await validateHostSpec(+ { llmPolicy: { fallbacks: fallbacks(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS + 2) } },+ { isModelAllowed },+ {+ stored: { llmPolicy: { fallbacks: fallbacks(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS + 1) } },+ hostRef,+ tolerations: [],+ }+ )+ expect(res?.errors[0].field).toBe('spec.llmPolicy.fallbacks')+ })++ it('tolerates an unchanged-size or shrinking over-cap stored Host', async () => {+ const isModelAllowed = vi.fn().mockResolvedValue(true)+ const stored = {+ allowedModels: subset(HOST_ALLOWED_MODELS_MAX_ITEMS + 2),+ llmPolicy: { fallbacks: fallbacks(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS + 2) },+ }+ const unchanged = await validateHostSpec(+ structuredClone(stored),+ { isModelAllowed },+ { stored, hostRef, tolerations: [] }+ )+ expect(unchanged).toBeNull()+ const shrunk = await validateHostSpec(+ {+ allowedModels: subset(HOST_ALLOWED_MODELS_MAX_ITEMS + 1),+ llmPolicy: { fallbacks: fallbacks(HOST_LLM_POLICY_FALLBACKS_MAX_ITEMS + 1) },+ },+ { isModelAllowed },+ { stored, hostRef, tolerations: [] }+ )+ expect(shrunk).toBeNull()+ })+})