Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): add generic OAuth knob schema and pure install wiring
Diego Zacariasb34d332eda3b
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex a5035d477..beaecc0fd 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.607",+ "version": "0.1.608","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.607",+ "version": "0.1.608","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 59d3d2ffd..9919d7f2e 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.607",+ "version": "0.1.608","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/oauth/genericKnobs.ts b/control-api/src/oauth/genericKnobs.tsnew file mode 100644index 000000000..18710aa8f--- /dev/null+++ b/control-api/src/oauth/genericKnobs.ts@@ -0,0 +1,55 @@+import { z } from 'zod'+import type { GenericClientRouting } from './callback.js'++/**+ * Install-side wire knobs for the `source:'generic'` carril (S3-B4 / DEC-28).+ *+ * This is the SINGLE install-side source of truth for the 11 generic knobs plus the+ * fail-closed `supportsRefresh` flag — a 1:1 mirror of the CRD generic fields+ * (`mcpserver.yaml` generic block) and of the runtime routing shape+ * (`GenericClientRouting` = `GenericAdapterConfig` + `supportsRefresh`). It is NOT a+ * decision module (DEC-28 / D3): it is pure FORM — each field independently selects+ * one fixed wire behaviour, with no precedence, merge or ordering resolution.+ *+ * No defaults: fidelity to the CRD (which has none — a CRD default would void the+ * GENERIC-REQ presence check) and to `extractGenericRouting`, which reads the+ * booleans with `=== true` (absent ⇒ false). The install path writes the 10+ * GENERIC-REQ knobs explicitly; the wizard is what fills defaults, never the server.+ */+export const GenericOAuthKnobsSchema = z+ .object({+ authorizationEndpoint: z.string().min(1).max(2048),+ tokenEndpoint: z.string().min(1).max(2048),+ refreshEndpoint: z.string().min(1).max(2048).optional(),+ resource: z.string().min(1).max(2048).optional(),+ tokenRequestFormat: z.enum(['form', 'json']),+ tokenAuthMethod: z.enum(['body', 'basic']),+ scopeSeparator: z.enum(['space', 'comma']),+ sendScope: z.boolean(),+ usePkce: z.boolean(),+ includeResponseType: z.boolean(),+ supportsRefresh: z.boolean(),+ extraAuthorizeParams: z+ .record(z.string(), z.string().max(1024))+ .refine(o => Object.keys(o).length <= 16, { message: 'at most 16 extra authorize params' })+ .optional(),+ })+ .strict()++export type GenericOAuthKnobs = z.infer<typeof GenericOAuthKnobsSchema>++// Compile-time lockstep with the runtime routing shape (there is no single runtime+// source to derive from — the runtime keeps its own interface for the exchange/+// refresh path). If a knob is added, removed, renamed or re-typed on either side,+// this equality fails to compile, so install-side and runtime-side can never drift.+type Expect<T extends true> = T+type Equal<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false+export type _KnobsMatchRuntime = Expect<Equal<GenericOAuthKnobs, GenericClientRouting>>++/**+ * A catalog-supplied generic suggestion (E-19.6): every knob optional — the catalog+ * SUGGESTS, the admin confirms, control-api arbitrates (S-4). Validated when the+ * catalog entry is parsed; the install saga never reads it to build `spec.oauth`.+ */+export const GenericConfigSuggestionSchema = GenericOAuthKnobsSchema.partial()+export type GenericConfigSuggestion = z.infer<typeof GenericConfigSuggestionSchema>diff --git a/control-api/src/routes/admin/registryGenericOauth.ts b/control-api/src/routes/admin/registryGenericOauth.tsnew file mode 100644index 000000000..646afa3f5--- /dev/null+++ b/control-api/src/routes/admin/registryGenericOauth.ts@@ -0,0 +1,127 @@+import { z } from 'zod'+import {+ type DnsResolver,+ type ValidationError,+ validateOAuthEndpointUrl,+} from '../../http/validateMcpServerSpec.js'+import { type GenericOAuthKnobs, GenericOAuthKnobsSchema } from '../../oauth/genericKnobs.js'++/**+ * Install-side wiring for the `source:'generic'` carril (S3-B4). Kept in this leaf+ * module — depending only on the knob schema + the kernel §4 seam — so+ * `registry.ts`'s install saga can import it without an import cycle (the shared+ * `InstallOAuthSecretSchema` lives here for the same reason, reused by the baked+ * input schema in `registry.ts`).+ */++// Operator-supplied OAuth credential Secret on the install request. Either MANAGED+// (operator types values → control-api creates the Secret) or a REFERENCE to an+// existing Secret whose id/secret keys the operator names. Shared by the baked and+// the generic input schemas.+export const InstallOAuthSecretSchema = z.discriminatedUnion('mode', [+ z.object({+ mode: z.literal('managed'),+ clientId: z.string().min(1),+ clientSecret: z.string().min(1),+ }),+ z.object({+ mode: z.literal('reference'),+ secretName: z.string().min(1),+ clientIdKey: z.string().min(1),+ clientSecretKey: z.string().min(1),+ }),+])++export type InstallOAuthSecret = z.infer<typeof InstallOAuthSecretSchema>++/**+ * Operator input for a `provider:'generic'` install. `secret` is OPTIONAL — a public+ * generic client (D-A5) carries no Secret and its `client_id` IS `oauth.id` (DA-1).+ * The knobs are the operator-pinned endpoints + wire configuration.+ */+export const InstallGenericOAuthInputSchema = z.object({+ scopes: z.array(z.string()).optional(),+ grantScope: z.enum(['user', 'context']).optional(),+ secret: InstallOAuthSecretSchema.optional(),+ generic: GenericOAuthKnobsSchema,+})++export type InstallGenericOAuthInput = z.infer<typeof InstallGenericOAuthInputSchema>++/**+ * Kernel §4 (spec 19 §4) over every operator-typed endpoint, BEFORE the CR exists.+ * The generic endpoints are immutable by CEL and `authorizationEndpoint` is never+ * re-validated after install (runtime only IP-pins the token/refresh POST), so this+ * admission check is the only gate on the authorize URL. Returns [] when all pass;+ * each `field` is prefixed `oauth.generic.<knob>` for field-level UI feedback.+ */+export async function validateGenericEndpoints(+ knobs: GenericOAuthKnobs,+ options: { resolveDns?: DnsResolver } = {}+): Promise<ValidationError[]> {+ const checks: Array<{ field: string; url: string }> = [+ { field: 'oauth.generic.authorizationEndpoint', url: knobs.authorizationEndpoint },+ { field: 'oauth.generic.tokenEndpoint', url: knobs.tokenEndpoint },+ ]+ if (knobs.refreshEndpoint) {+ checks.push({ field: 'oauth.generic.refreshEndpoint', url: knobs.refreshEndpoint })+ }+ if (knobs.resource) {+ // RFC 8707 resource is an absolute URL; on a self-hosted AS it is resoluble, so+ // it passes the same kernel as the endpoints (spec 19 §4 lists all four).+ checks.push({ field: 'oauth.generic.resource', url: knobs.resource })+ }+ const errors: ValidationError[] = []+ for (const check of checks) {+ errors.push(...(await validateOAuthEndpointUrl(check.url, check.field, options)))+ }+ return errors+}++export interface GenericOAuthSpecRefs {+ clientIdRef: { name: string; key: string }+ clientSecretRef: { name: string; key: string }+}++/**+ * Pure map from install input → the flat `spec.oauth` generic object (DEC-28). Writes+ * `source:'generic'` + the 10 GENERIC-REQ knobs explicitly, plus the optional knobs+ * only when present, plus `scopes`/`grantScope`. Refs are paired — BOTH+ * (confidential) or NEITHER (public), per GENERIC-SECRET-PAIRING. NEVER `provider`,+ * `clientMode`, `issuer`, `registrationEndpoint`, `issForCallback`, `bearerInBody`+ * (GENERIC-FORBID-REMOTE-FIELDS).+ */+export function buildGenericOAuthSpec(args: {+ id: string+ knobs: GenericOAuthKnobs+ scopes: string[]+ grantScope: 'user' | 'context'+ refs?: GenericOAuthSpecRefs+}): Record<string, unknown> {+ const { id, knobs, scopes, grantScope, refs } = args+ const oauth: Record<string, unknown> = {+ source: 'generic',+ id,+ authorizationEndpoint: knobs.authorizationEndpoint,+ tokenEndpoint: knobs.tokenEndpoint,+ tokenRequestFormat: knobs.tokenRequestFormat,+ tokenAuthMethod: knobs.tokenAuthMethod,+ scopeSeparator: knobs.scopeSeparator,+ sendScope: knobs.sendScope,+ usePkce: knobs.usePkce,+ includeResponseType: knobs.includeResponseType,+ supportsRefresh: knobs.supportsRefresh,+ scopes,+ grantScope,+ }+ if (knobs.refreshEndpoint) oauth.refreshEndpoint = knobs.refreshEndpoint+ if (knobs.resource) oauth.resource = knobs.resource+ if (knobs.extraAuthorizeParams && Object.keys(knobs.extraAuthorizeParams).length > 0) {+ oauth.extraAuthorizeParams = knobs.extraAuthorizeParams+ }+ if (refs) {+ oauth.clientIdRef = refs.clientIdRef+ oauth.clientSecretRef = refs.clientSecretRef+ }+ return oauth+}diff --git a/control-api/test/oauth.genericKnobs.test.ts b/control-api/test/oauth.genericKnobs.test.tsnew file mode 100644index 000000000..a72ac4b0c--- /dev/null+++ b/control-api/test/oauth.genericKnobs.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest'+import {+ GenericConfigSuggestionSchema,+ GenericOAuthKnobsSchema,+} from '../src/oauth/genericKnobs.js'++/**+ * S3-B4 — install-side knob schema. Mirror of the CRD generic fields + the runtime+ * routing shape (the compile-time `_KnobsMatchRuntime` equality in the module is the+ * lockstep guard; these tests cover the runtime validation behaviour).+ */++const VALID = {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenRequestFormat: 'form' as const,+ tokenAuthMethod: 'body' as const,+ scopeSeparator: 'space' as const,+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+}++describe('GenericOAuthKnobsSchema', () => {+ it('accepts the 10 required knobs with no optionals', () => {+ const r = GenericOAuthKnobsSchema.safeParse(VALID)+ expect(r.success).toBe(true)+ })++ it('rejects when any required knob is missing', () => {+ for (const key of Object.keys(VALID)) {+ const { [key]: _drop, ...rest } = VALID as Record<string, unknown>+ expect(GenericOAuthKnobsSchema.safeParse(rest).success).toBe(false)+ }+ })++ it('rejects an unknown extra field (strict)', () => {+ expect(GenericOAuthKnobsSchema.safeParse({ ...VALID, provider: 'google' }).success).toBe(false)+ expect(GenericOAuthKnobsSchema.safeParse({ ...VALID, clientMode: 'public' }).success).toBe(+ false+ )+ })++ it('rejects a bad enum value', () => {+ expect(GenericOAuthKnobsSchema.safeParse({ ...VALID, tokenRequestFormat: 'xml' }).success).toBe(+ false+ )+ expect(GenericOAuthKnobsSchema.safeParse({ ...VALID, tokenAuthMethod: 'header' }).success).toBe(+ false+ )+ })++ it('accepts the optional knobs (refreshEndpoint, resource, extraAuthorizeParams)', () => {+ const r = GenericOAuthKnobsSchema.safeParse({+ ...VALID,+ refreshEndpoint: 'https://idp.example.com/refresh',+ resource: 'https://api.example.com',+ extraAuthorizeParams: { audience: 'aud-1' },+ })+ expect(r.success).toBe(true)+ })++ it('rejects more than 16 extra authorize params', () => {+ const many: Record<string, string> = {}+ for (let i = 0; i < 17; i++) many[`k${i}`] = 'v'+ expect(+ GenericOAuthKnobsSchema.safeParse({ ...VALID, extraAuthorizeParams: many }).success+ ).toBe(false)+ })++ it('rejects an extra param value longer than 1024 chars', () => {+ expect(+ GenericOAuthKnobsSchema.safeParse({+ ...VALID,+ extraAuthorizeParams: { big: 'x'.repeat(1025) },+ }).success+ ).toBe(false)+ })+})++describe('GenericConfigSuggestionSchema (E-19.6)', () => {+ it('accepts a partial suggestion (every knob optional)', () => {+ expect(GenericConfigSuggestionSchema.safeParse({ usePkce: false }).success).toBe(true)+ expect(GenericConfigSuggestionSchema.safeParse({}).success).toBe(true)+ })++ it('still rejects unknown keys and bad types', () => {+ expect(GenericConfigSuggestionSchema.safeParse({ provider: 'google' }).success).toBe(false)+ expect(GenericConfigSuggestionSchema.safeParse({ sendScope: 'yes' }).success).toBe(false)+ })+})diff --git a/control-api/test/registryGenericOauth.test.ts b/control-api/test/registryGenericOauth.test.tsnew file mode 100644index 000000000..1aef65c8a--- /dev/null+++ b/control-api/test/registryGenericOauth.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it, vi } from 'vitest'+import fc from 'fast-check'+import { type GenericOAuthKnobs, GenericOAuthKnobsSchema } from '../src/oauth/genericKnobs.js'+import {+ buildGenericOAuthSpec,+ validateGenericEndpoints,+} from '../src/routes/admin/registryGenericOauth.js'++/**+ * S3-B4 — pure install-side generic wiring. `buildGenericOAuthSpec` is a pure+ * knob→spec map; `validateGenericEndpoints` is the kernel §4 seam applied to every+ * operator-typed endpoint. `resolveDns` is injected so the kernel runs without DNS.+ */++const KNOBS: GenericOAuthKnobs = {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: 'https://idp.example.com/token',+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'body',+ scopeSeparator: 'space',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+}++const REMOTE_ONLY_KEYS = [+ 'provider',+ 'clientMode',+ 'issuer',+ 'registrationEndpoint',+ 'issForCallback',+ 'bearerInBody',+]++describe('buildGenericOAuthSpec', () => {+ it('writes source:generic + the 10 required knobs, no remote fields (public)', () => {+ const spec = buildGenericOAuthSpec({+ id: 'my-idp',+ knobs: KNOBS,+ scopes: ['a'],+ grantScope: 'user',+ })+ expect(spec.source).toBe('generic')+ expect(spec.id).toBe('my-idp')+ expect(spec.scopes).toEqual(['a'])+ expect(spec.grantScope).toBe('user')+ for (const k of REMOTE_ONLY_KEYS) expect(spec).not.toHaveProperty(k)+ // No refs in public mode.+ expect(spec).not.toHaveProperty('clientIdRef')+ expect(spec).not.toHaveProperty('clientSecretRef')+ // Optional knobs omitted when absent.+ expect(spec).not.toHaveProperty('refreshEndpoint')+ expect(spec).not.toHaveProperty('resource')+ expect(spec).not.toHaveProperty('extraAuthorizeParams')+ })++ it('carries both refs in confidential mode', () => {+ const spec = buildGenericOAuthSpec({+ id: 'my-idp',+ knobs: KNOBS,+ scopes: ['a'],+ grantScope: 'user',+ refs: {+ clientIdRef: { name: 'gen-creds', key: 'client_id' },+ clientSecretRef: { name: 'gen-creds', key: 'client_secret' },+ },+ })+ expect(spec.clientIdRef).toEqual({ name: 'gen-creds', key: 'client_id' })+ expect(spec.clientSecretRef).toEqual({ name: 'gen-creds', key: 'client_secret' })+ })++ it('carries optional knobs only when present', () => {+ const spec = buildGenericOAuthSpec({+ id: 'my-idp',+ knobs: {+ ...KNOBS,+ refreshEndpoint: 'https://idp.example.com/refresh',+ resource: 'https://api.example.com',+ extraAuthorizeParams: { audience: 'aud-1' },+ },+ scopes: ['a'],+ grantScope: 'context',+ })+ expect(spec.refreshEndpoint).toBe('https://idp.example.com/refresh')+ expect(spec.resource).toBe('https://api.example.com')+ expect(spec.extraAuthorizeParams).toEqual({ audience: 'aud-1' })+ })++ // T2: property-based — the spec never contains a remote/baked field, its knob+ // subset round-trips through the schema, and refs are paired (both or neither).+ it('property: round-trips knobs, never leaks remote fields, pairs refs', () => {+ const knobArb: fc.Arbitrary<GenericOAuthKnobs> = fc.record(+ {+ authorizationEndpoint: fc.constant('https://idp.example.com/authorize'),+ tokenEndpoint: fc.constant('https://idp.example.com/token'),+ refreshEndpoint: fc.option(fc.constant('https://idp.example.com/refresh'), {+ nil: undefined,+ }),+ resource: fc.option(fc.constant('https://api.example.com'), { nil: undefined }),+ tokenRequestFormat: fc.constantFrom('form', 'json'),+ tokenAuthMethod: fc.constantFrom('body', 'basic'),+ scopeSeparator: fc.constantFrom('space', 'comma'),+ sendScope: fc.boolean(),+ usePkce: fc.boolean(),+ includeResponseType: fc.boolean(),+ supportsRefresh: fc.boolean(),+ extraAuthorizeParams: fc.option(+ fc.dictionary(fc.string({ minLength: 1, maxLength: 8 }), fc.string({ maxLength: 8 }), {+ maxKeys: 16,+ }),+ { nil: undefined }+ ),+ },+ { withDeletedKeys: false }+ ) as fc.Arbitrary<GenericOAuthKnobs>++ fc.assert(+ fc.property(knobArb, fc.boolean(), (knobs, confidential) => {+ const refs = confidential+ ? {+ clientIdRef: { name: 's', key: 'client_id' },+ clientSecretRef: { name: 's', key: 'client_secret' },+ }+ : undefined+ const spec = buildGenericOAuthSpec({ id: 'x', knobs, scopes: [], grantScope: 'user', refs })+ for (const k of REMOTE_ONLY_KEYS) expect(spec).not.toHaveProperty(k)+ expect('clientIdRef' in spec).toBe('clientSecretRef' in spec)+ expect('clientIdRef' in spec).toBe(confidential)+ // The knob subset written to the spec re-validates against the schema.+ const {+ source: _s,+ id: _i,+ scopes: _sc,+ grantScope: _g,+ clientIdRef: _ci,+ clientSecretRef: _cs,+ ...knobSubset+ } = spec as Record<string, unknown>+ expect(GenericOAuthKnobsSchema.safeParse(knobSubset).success).toBe(true)+ })+ )+ })+})++describe('validateGenericEndpoints (kernel §4)', () => {+ const publicDns = () => vi.fn(async () => ['93.184.216.34'])++ it('returns [] when every endpoint is https + public + resolvable', async () => {+ const errors = await validateGenericEndpoints(+ {+ ...KNOBS,+ refreshEndpoint: 'https://idp.example.com/refresh',+ resource: 'https://api.example.com',+ },+ { resolveDns: publicDns() }+ )+ expect(errors).toEqual([])+ })++ it('rejects a non-https authorization endpoint (field-prefixed)', async () => {+ const errors = await validateGenericEndpoints(+ { ...KNOBS, authorizationEndpoint: 'http://idp.example.com/authorize' },+ { resolveDns: publicDns() }+ )+ expect(errors.some(e => e.field === 'oauth.generic.authorizationEndpoint')).toBe(true)+ })++ it('rejects an internal-hostname token endpoint without resolving it', async () => {+ const resolveDns = vi.fn(async () => ['93.184.216.34'])+ const errors = await validateGenericEndpoints(+ { ...KNOBS, tokenEndpoint: 'https://token.svc.cluster.local/token' },+ { resolveDns }+ )+ expect(errors.some(e => e.field === 'oauth.generic.tokenEndpoint')).toBe(true)+ })++ it('rejects a resource that resolves to a blocked (private) IP', async () => {+ const resolveDns = vi.fn(async (host: string) =>+ host === 'api.example.com' ? ['10.0.0.5'] : ['93.184.216.34']+ )+ const errors = await validateGenericEndpoints(+ { ...KNOBS, resource: 'https://api.example.com/' },+ { resolveDns }+ )+ expect(errors.some(e => e.field === 'oauth.generic.resource')).toBe(true)+ })+})