Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): open the generic branch in the install saga
Diego Zacarias1d0dcc427dfc
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 8fa990243..e21fcf1e4 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.609",+ "version": "0.1.610","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.609",+ "version": "0.1.610","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 6b17fc92c..7e01ada66 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.609",+ "version": "0.1.610","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/registry.ts b/control-api/src/routes/admin/registry.tsindex 96107e2df..9fbb7b62e 100644--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@ -11,6 +11,7 @@ import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpecimport { K8sGateway } from '../../k8s.js'import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'+import { GenericConfigSuggestionSchema } from '../../oauth/genericKnobs.js'import { getOAuthProviderAdapter, isKnownOAuthProvider } from '../../oauth/providers.js'import { rootLogger } from '../../observability/logger.js'import { type AdminUserRecord, findAdminById } from '../../services/adminAuthService.js'@@ -54,6 +55,13 @@ import {validateWorkflowRecipeLimits,} from '../../services/workflowRecipeLimits.js'import { SecretUpsertRequest } from '../../types.js'+import {+ type GenericOAuthSpecRefs,+ InstallGenericOAuthInputSchema,+ InstallOAuthSecretSchema,+ buildGenericOAuthSpec,+ validateGenericEndpoints,+} from './registryGenericOauth.js'import {EVENFIRE_REGISTRY_PULL_SECRET_NAME,shouldAttachEvenfirePullSecret,@@ -673,32 +681,23 @@ const OAUTH_CLIENT_ID_KEY = 'client_id'const OAUTH_CLIENT_SECRET_KEY = 'client_secret'// Frozen catalog contract (S1-U1 deferred): the entry MAY carry an `oauth` block-// under mcp_server_meta. `genericConfig` is Slice-3-only — accepted here but-// NEVER read in Slice 1 (S-4: the catalog suggests, it never auto-configures).+// under mcp_server_meta. `genericConfig` (E-19.6) is a typed generic SUGGESTION that+// is NEVER read to build spec.oauth (S-4: the catalog suggests, it never+// auto-configures; only the wizard-confirmed body.oauth.generic reaches the CR).+// Because it is never read, a malformed one must NEVER block an install — `.catch`+// drops a non-conforming suggestion to `undefined` instead of failing the whole+// catalog-oauth parse. This also keeps the baked path byte-identical: a baked entry+// that happens to carry a non-conforming genericConfig installs exactly as before.const CatalogOAuthBlockSchema = z.object({provider: z.string(),grantScope: z.enum(['user', 'context']).optional(),scopes: z.array(z.string()).optional(),- genericConfig: z.unknown().optional(),+ genericConfig: GenericConfigSuggestionSchema.optional().catch(undefined),})-// Operator-supplied OAuth input on the install request. The credential Secret is-// either MANAGED (operator types values → control-api creates the Secret) or a-// REFERENCE to an existing Secret whose id/secret keys the operator names.-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),- }),-])-+// `InstallOAuthSecretSchema` (managed | reference) lives in `registryGenericOauth.ts`+// so the generic input schema can reuse it without an import cycle; the baked input+// schema below imports it back.const InstallOAuthInputSchema = z.object({// Editable scopes (D-B6/E-19.3): the wizard prefills from the catalog and the// admin may override them per server (the Google family shares one provider@@ -1592,9 +1591,10 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {return}- // ── OAuth wiring (S1-U2/U3): generate spec.oauth from the catalog block- // + operator input. Only runs when the entry declares OAuth. `genericConfig`- // is NEVER read here (Slice 1 = 8 baked providers; the generic adapter is S3).+ // ── OAuth wiring (S1-U2/U3 baked · S3-B4 generic): generate spec.oauth from+ // the catalog block + operator input. Only runs when the entry declares OAuth.+ // The catalog `genericConfig` SUGGESTION is validated but NEVER read here to+ // build the spec (S-4): only the wizard-confirmed body.oauth reaches the CR.let managedOAuthSecret: { name: string; data: Record<string, string> } | undefinedlet oauthClientSecretCreated = falseconst catalogOAuthRaw = (meta as { oauth?: unknown } | null)?.oauth@@ -1606,123 +1606,265 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {}const catalogOAuth = parsedCatalog.data- // Slice 1 serves only the 8 baked providers. 'generic' and any unknown- // value fail closed here (isKnownOAuthProvider excludes the sentinel).- if (!isKnownOAuthProvider(catalogOAuth.provider)) {- res.status(400).json({- error: `oauth.provider "${catalogOAuth.provider}" is not a supported baked provider`,+ if (catalogOAuth.provider === 'generic') {+ // ── Generic self-hosted lane (S3-B4 / DEC-28) ────────────────────────+ // Opened BEFORE the isKnownOAuthProvider gate so 'generic' never enters+ // ADAPTERS/KNOWN_OAUTH_PROVIDERS; the baked path stays byte-identical.+ if (!config.oauthCallbackBaseUrl || config.oauthCallbackBaseUrl.trim().length === 0) {+ res.status(400).json({+ error:+ 'oauth: CONTROL_API_OAUTH_CALLBACK_BASE_URL is not configured; cannot install an OAuth server',+ })+ return+ }+ if (body.oauth === undefined || body.oauth === null) {+ res.status(400).json({+ error: 'oauth: generic client configuration is required (endpoints + wire knobs)',+ })+ return+ }+ const parsedGeneric = InstallGenericOAuthInputSchema.safeParse(body.oauth)+ if (!parsedGeneric.success) {+ // Zod issue paths/messages are field names + type descriptions, never+ // submitted values — cannot leak a client secret or endpoint.+ const detail = parsedGeneric.error.issues+ .map(issue => {+ const path = issue.path.join('.')+ return path ? `${path}: ${issue.message}` : issue.message+ })+ .join('; ')+ res.status(400).json({ error: `oauth: invalid generic oauth input: ${detail}` })+ return+ }+ const genericInput = parsedGeneric.data+ const knobs = genericInput.generic++ // grantScope: operator → catalog → 'user' (same order as baked).+ const grantScope = genericInput.grantScope ?? catalogOAuth.grantScope ?? 'user'++ // Scopes: operator → catalog → [] (generic has no baked adapter). GAP-6+ // (DA-4): with sendScope:true an empty scope set is rejected, exactly as+ // baked; with sendScope:false an authorize without `scope` is legal.+ const scopes = computeInstallOAuthScopes({+ operatorScopes: genericInput.scopes,+ catalogScopes: catalogOAuth.scopes,+ defaultScopes: [],})- return- }- const provider = catalogOAuth.provider+ if (scopes.length === 0 && knobs.sendScope) {+ res.status(400).json({+ error: 'oauth_scopes_required',+ message:+ 'oauth: generic client with sendScope:true requires explicit scopes; none supplied',+ })+ return+ }- // D-B4: the public callback base URL MUST be configured. Without it the- // callback would derive from the internal Host behind the funnel and the- // operator would register a broken redirect URI at the provider.- if (!config.oauthCallbackBaseUrl || config.oauthCallbackBaseUrl.trim().length === 0) {- res.status(400).json({- error:- 'oauth: CONTROL_API_OAUTH_CALLBACK_BASE_URL is not configured; cannot install an OAuth server',- })- return- }+ // Coherence (fail-closed, not a decision): Basic client auth needs a+ // secret. The composer throws at runtime without one (providers.ts); reject+ // at admission instead of creating an unusable public+basic client.+ if (knobs.tokenAuthMethod === 'basic' && genericInput.secret === undefined) {+ res.status(400).json({+ error:+ 'oauth: generic tokenAuthMethod=basic requires a client secret (confidential)',+ })+ return+ }- if (body.oauth === undefined || body.oauth === null) {- res.status(400).json({- error:- 'oauth: client credentials are required (managed values or a Secret reference)',- })- return- }- const parsedInput = InstallOAuthInputSchema.safeParse(body.oauth)- if (!parsedInput.success) {- // Describe the real validation failure. Zod issue paths/messages are- // field names and type descriptions — never the submitted values — so- // this cannot leak a client secret.- const detail = parsedInput.error.issues- .map(issue => {- const path = issue.path.join('.')- return path ? `${path}: ${issue.message}` : issue.message+ // D-B5: control-api derives the immutable id and pre-checks uniqueness. The+ // slug narrow (CEL) applies to generic too — client_id IS oauth.id (public).+ const oauthId = deriveOAuthClientId(serverName)+ if (!oauthId) {+ res+ .status(400)+ .json({ error: 'oauth: could not derive a valid oauth.id from serverName' })+ return+ }+ if (await oauthClientIdInUse(gateway, targetNs, oauthId)) {+ res.status(409).json({+ error: `oauth.id "${oauthId}" is already in use by another server; choose a different serverName`,})- .join('; ')- res.status(400).json({ error: `oauth: invalid oauth input: ${detail}` })- return- }- const oauthInput = parsedInput.data+ return+ }- // grantScope: operator selector wins, else catalog, else 'user'. Immutable- // once set (D-B7) — this saga only ever creates.- const grantScope = oauthInput.grantScope ?? catalogOAuth.grantScope ?? 'user'+ // Kernel §4 (spec 19 §4) over every operator-typed endpoint, BEFORE any+ // Secret or CR is written (0 Secrets, 0 CR on rejection). These endpoints+ // are immutable by CEL and authorize is never re-validated at runtime.+ const endpointErrors = await validateGenericEndpoints(knobs)+ if (endpointErrors.length > 0) {+ res.status(422).json({ error: 'oauth_endpoint_rejected', errors: endpointErrors })+ return+ }- // Scopes: operator edit → catalog prefill → baked defaultScopes (D-B6).- const adapter = getOAuthProviderAdapter(provider)- const scopes = computeInstallOAuthScopes({- operatorScopes: oauthInput.scopes,- catalogScopes: catalogOAuth.scopes,- defaultScopes: adapter.defaultScopes,- })- if (scopes.length === 0) {- // GAP-6: google/salesforce/slack/notion/monday/clickup have empty- // defaultScopes, so a server with no scopes supplied is rejected rather- // than created inert with scopes: [].- res.status(400).json({- error: `oauth: provider "${provider}" requires explicit scopes; none supplied`,+ // Secret refs by mode (D-B3) — confidential only. A public client (no+ // secret) carries NO refs; its client_id IS oauth.id (DA-1).+ let refs: GenericOAuthSpecRefs | undefined+ if (genericInput.secret) {+ if (genericInput.secret.mode === 'reference') {+ const verify = await verifyReferencedOAuthSecret(+ gateway,+ targetNs,+ genericInput.secret+ )+ if (!verify.ok) {+ res.status(verify.status).json({ error: verify.error })+ return+ }+ refs = {+ clientIdRef: {+ name: genericInput.secret.secretName,+ key: genericInput.secret.clientIdKey,+ },+ clientSecretRef: {+ name: genericInput.secret.secretName,+ key: genericInput.secret.clientSecretKey,+ },+ }+ } else {+ const oauthSecretName = `${serverName}-oauth-client`+ refs = {+ clientIdRef: { name: oauthSecretName, key: OAUTH_CLIENT_ID_KEY },+ clientSecretRef: { name: oauthSecretName, key: OAUTH_CLIENT_SECRET_KEY },+ }+ managedOAuthSecret = {+ name: oauthSecretName,+ data: {+ [OAUTH_CLIENT_ID_KEY]: genericInput.secret.clientId,+ [OAUTH_CLIENT_SECRET_KEY]: genericInput.secret.clientSecret,+ },+ }+ }+ }++ mcpServerSpec.auth = { type: 'oauth' }+ mcpServerSpec.oauth = buildGenericOAuthSpec({+ id: oauthId,+ knobs,+ scopes,+ grantScope,+ refs,})- return- }+ } else {+ // Baked lane (S1) — byte-identical to before, now guarded by the generic+ // branch above so 'generic' never reaches the isKnownOAuthProvider gate.+ if (!isKnownOAuthProvider(catalogOAuth.provider)) {+ res.status(400).json({+ error: `oauth.provider "${catalogOAuth.provider}" is not a supported baked provider`,+ })+ return+ }+ const provider = catalogOAuth.provider++ // D-B4: the public callback base URL MUST be configured. Without it the+ // callback would derive from the internal Host behind the funnel and the+ // operator would register a broken redirect URI at the provider.+ if (!config.oauthCallbackBaseUrl || config.oauthCallbackBaseUrl.trim().length === 0) {+ res.status(400).json({+ error:+ 'oauth: CONTROL_API_OAUTH_CALLBACK_BASE_URL is not configured; cannot install an OAuth server',+ })+ return+ }- // D-B5: control-api derives the immutable id and pre-checks uniqueness.- const oauthId = deriveOAuthClientId(serverName)- if (!oauthId) {- res- .status(400)- .json({ error: 'oauth: could not derive a valid oauth.id from serverName' })- return- }- if (await oauthClientIdInUse(gateway, targetNs, oauthId)) {- res.status(409).json({- error: `oauth.id "${oauthId}" is already in use by another server; choose a different serverName`,+ if (body.oauth === undefined || body.oauth === null) {+ res.status(400).json({+ error:+ 'oauth: client credentials are required (managed values or a Secret reference)',+ })+ return+ }+ const parsedInput = InstallOAuthInputSchema.safeParse(body.oauth)+ if (!parsedInput.success) {+ // Describe the real validation failure. Zod issue paths/messages are+ // field names and type descriptions — never the submitted values — so+ // this cannot leak a client secret.+ const detail = parsedInput.error.issues+ .map(issue => {+ const path = issue.path.join('.')+ return path ? `${path}: ${issue.message}` : issue.message+ })+ .join('; ')+ res.status(400).json({ error: `oauth: invalid oauth input: ${detail}` })+ return+ }+ const oauthInput = parsedInput.data++ // grantScope: operator selector wins, else catalog, else 'user'. Immutable+ // once set (D-B7) — this saga only ever creates.+ const grantScope = oauthInput.grantScope ?? catalogOAuth.grantScope ?? 'user'++ // Scopes: operator edit → catalog prefill → baked defaultScopes (D-B6).+ const adapter = getOAuthProviderAdapter(provider)+ const scopes = computeInstallOAuthScopes({+ operatorScopes: oauthInput.scopes,+ catalogScopes: catalogOAuth.scopes,+ defaultScopes: adapter.defaultScopes,})- return- }+ if (scopes.length === 0) {+ // GAP-6: google/salesforce/slack/notion/monday/clickup have empty+ // defaultScopes, so a server with no scopes supplied is rejected rather+ // than created inert with scopes: [].+ res.status(400).json({+ error: `oauth: provider "${provider}" requires explicit scopes; none supplied`,+ })+ return+ }- // Secret refs by mode (D-B3).- let clientIdRef: { name: string; key: string }- let clientSecretRef: { name: string; key: string }- if (oauthInput.secret.mode === 'reference') {- const verify = await verifyReferencedOAuthSecret(gateway, targetNs, oauthInput.secret)- if (!verify.ok) {- res.status(verify.status).json({ error: verify.error })+ // D-B5: control-api derives the immutable id and pre-checks uniqueness.+ const oauthId = deriveOAuthClientId(serverName)+ if (!oauthId) {+ res+ .status(400)+ .json({ error: 'oauth: could not derive a valid oauth.id from serverName' })return}- clientIdRef = { name: oauthInput.secret.secretName, key: oauthInput.secret.clientIdKey }- clientSecretRef = {- name: oauthInput.secret.secretName,- key: oauthInput.secret.clientSecretKey,+ if (await oauthClientIdInUse(gateway, targetNs, oauthId)) {+ res.status(409).json({+ error: `oauth.id "${oauthId}" is already in use by another server; choose a different serverName`,+ })+ return}- } else {- const oauthSecretName = `${serverName}-oauth-client`- clientIdRef = { name: oauthSecretName, key: OAUTH_CLIENT_ID_KEY }- clientSecretRef = { name: oauthSecretName, key: OAUTH_CLIENT_SECRET_KEY }- managedOAuthSecret = {- name: oauthSecretName,- data: {- [OAUTH_CLIENT_ID_KEY]: oauthInput.secret.clientId,- [OAUTH_CLIENT_SECRET_KEY]: oauthInput.secret.clientSecret,- },++ // Secret refs by mode (D-B3).+ let clientIdRef: { name: string; key: string }+ let clientSecretRef: { name: string; key: string }+ if (oauthInput.secret.mode === 'reference') {+ const verify = await verifyReferencedOAuthSecret(gateway, targetNs, oauthInput.secret)+ if (!verify.ok) {+ res.status(verify.status).json({ error: verify.error })+ return+ }+ clientIdRef = {+ name: oauthInput.secret.secretName,+ key: oauthInput.secret.clientIdKey,+ }+ clientSecretRef = {+ name: oauthInput.secret.secretName,+ key: oauthInput.secret.clientSecretKey,+ }+ } else {+ const oauthSecretName = `${serverName}-oauth-client`+ clientIdRef = { name: oauthSecretName, key: OAUTH_CLIENT_ID_KEY }+ clientSecretRef = { name: oauthSecretName, key: OAUTH_CLIENT_SECRET_KEY }+ managedOAuthSecret = {+ name: oauthSecretName,+ data: {+ [OAUTH_CLIENT_ID_KEY]: oauthInput.secret.clientId,+ [OAUTH_CLIENT_SECRET_KEY]: oauthInput.secret.clientSecret,+ },+ }}- }- // The CRD couples auth.type=='oauth' iff spec.oauth is present and- // forbids a static auth.secretRef alongside oauth.- mcpServerSpec.auth = { type: 'oauth' }- mcpServerSpec.oauth = {- id: oauthId,- provider,- clientIdRef,- clientSecretRef,- scopes,- grantScope,+ // The CRD couples auth.type=='oauth' iff spec.oauth is present and+ // forbids a static auth.secretRef alongside oauth.+ mcpServerSpec.auth = { type: 'oauth' }+ mcpServerSpec.oauth = {+ id: oauthId,+ provider,+ clientIdRef,+ clientSecretRef,+ scopes,+ grantScope,+ }}}diff --git a/control-api/test/routes.registryInstall.oauth.test.ts b/control-api/test/routes.registryInstall.oauth.test.tsindex df36460dd..a76dbb80d 100644--- a/control-api/test/routes.registryInstall.oauth.test.ts+++ b/control-api/test/routes.registryInstall.oauth.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import request from 'supertest'import { config } from '../src/config.js'+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'import {computeInstallOAuthScopes,createAdminRegistryRouter,@@ -438,11 +439,41 @@ describe('POST /admin/registry/install — OAuth (S1-U2/U3)', () => {expect(spec.oauth).not.toHaveProperty('genericConfig')})- it("rejects the 'generic' sentinel provider in Slice 1", async () => {+ // S-4: a MALFORMED catalog genericConfig is never read, so it must NEVER block the+ // install — the baked path installs exactly as it did before genericConfig was typed.+ it('installs a baked provider even when the catalog genericConfig is malformed', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ oauthEntry({+ provider: 'google',+ scopes: ['gmail.readonly'],+ // Wrong-typed value + unknown key: a strict parse would reject the whole+ // catalog-oauth block; the non-fatal `.catch` drops the suggestion instead.+ genericConfig: { usePkce: 'yes', bogusKnob: 123 },+ })+ )+ const { app, gw } = makeInstallApp()+ await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-gmail',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: { secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' } },+ })+ .expect(201)+ const spec = await readServerOAuth(gw, 'my-gmail')+ expect(spec.oauth?.provider).toBe('google')+ expect(spec.oauth).not.toHaveProperty('genericConfig')+ })++ // S3-B4: 'generic' now opens the generic branch. A body WITHOUT the generic knob+ // block fails closed (inv.1) — it never reaches the baked provider gate.+ it("fails closed when 'generic' is declared but body.oauth.generic is absent", async () => {vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'generic', scopes: ['x'] }))- const { app } = makeInstallApp()+ const { app, gw } = makeInstallApp()const res = await request(app).post('/admin/registry/install').send({@@ -453,7 +484,8 @@ describe('POST /admin/registry/install — OAuth (S1-U2/U3)', () => {oauth: { secret: { mode: 'managed', clientId: 'id', clientSecret: 'sec' } },}).expect(400)- expect(res.body.error).toMatch(/not a supported baked provider/)+ expect(res.body.error).toMatch(/invalid generic oauth input/)+ await expect(gw.getResource('mcpservers', 'my-generic', 'mcp-server')).rejects.toThrow()})it('requires operator oauth credentials when the catalog declares OAuth', async () => {@@ -568,3 +600,247 @@ describe('POST /admin/registry/install — OAuth (S1-U2/U3)', () => {expect(spec.auth).toBeUndefined()})})++// ─── S3-B4: generic self-hosted carril install saga ─────────────────────────+describe('generic carril install (S3-B4)', () => {+ const VALID_KNOBS = {+ 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,+ }++ async function readFullServer(gw: MockGateway, name: string) {+ return (await gw.getResource('mcpservers', name, 'mcp-server')) as {+ spec: { oauth?: Record<string, unknown>; auth?: { type?: string } }+ }+ }++ // T3: was 400 at b9a846a98 (registry.ts generic gate). Now 201 with source:generic.+ it('installs a PUBLIC generic client (no secret): CR carries source:generic + no refs', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'generic' }))+ const { app, gw } = makeInstallApp()+ await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-idp',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: { scopes: ['read', 'write'], generic: VALID_KNOBS },+ })+ .expect(201)++ const server = await readFullServer(gw, 'my-idp')+ expect(server.spec.auth?.type).toBe('oauth')+ expect(server.spec.oauth?.source).toBe('generic')+ expect(server.spec.oauth?.id).toBe('my-idp')+ expect(server.spec.oauth).not.toHaveProperty('provider')+ expect(server.spec.oauth).not.toHaveProperty('clientIdRef')+ expect(server.spec.oauth).not.toHaveProperty('clientSecretRef')+ expect(server.spec.oauth?.authorizationEndpoint).toBe('https://idp.example.com/authorize')+ expect(server.spec.oauth?.scopes).toEqual(['read', 'write'])+ // No managed Secret created for a public client.+ await expect(gw.getSecret('my-idp-oauth-client', 'mcp-server')).rejects.toThrow()++ // inv.3: the resolver (real producer→consumer) reads the CR back as public generic.+ const subject = resolveServerOAuthSubject({ spec: server.spec })+ expect(subject?.decl.provider).toBe('generic')+ expect(subject?.decl.secretSource).toEqual({ kind: 'public' })+ })++ // T3: 201 confidential — refs + managed Secret; resolver → k8s-secret.+ it('installs a CONFIDENTIAL generic client (managed secret): refs + Secret created', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'generic' }))+ const { app, gw } = makeInstallApp()+ await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-idp',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: {+ scopes: ['read'],+ secret: { mode: 'managed', clientId: 'cid', clientSecret: 'csec' },+ generic: { ...VALID_KNOBS, tokenAuthMethod: 'basic' },+ },+ })+ .expect(201)++ const server = await readFullServer(gw, 'my-idp')+ expect(server.spec.oauth?.clientIdRef).toEqual({+ name: 'my-idp-oauth-client',+ key: 'client_id',+ })+ expect(server.spec.oauth?.clientSecretRef).toEqual({+ name: 'my-idp-oauth-client',+ key: 'client_secret',+ })+ const secret = (await gw.getSecret('my-idp-oauth-client', 'mcp-server')) as {+ stringData?: Record<string, string>+ }+ expect(Object.keys(secret.stringData ?? {}).sort()).toEqual(['client_id', 'client_secret'])++ const subject = resolveServerOAuthSubject({ spec: server.spec })+ expect(subject?.decl.secretSource).toEqual({+ kind: 'k8s-secret',+ clientIdRef: { name: 'my-idp-oauth-client', key: 'client_id' },+ clientSecretRef: { name: 'my-idp-oauth-client', key: 'client_secret' },+ })+ })++ // inv.2: kernel §4 rejects an internal endpoint BEFORE any Secret/CR (422).+ it('422 oauth_endpoint_rejected for an internal token endpoint (0 Secrets, 0 CR)', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'generic' }))+ const { app, gw } = makeInstallApp()+ const createSecretSpy = vi.spyOn(gw, 'createSecret')+ const res = await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-idp',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: {+ scopes: ['read'],+ generic: { ...VALID_KNOBS, tokenEndpoint: 'https://token.svc.cluster.local/token' },+ },+ })+ .expect(422)+ expect(res.body.error).toBe('oauth_endpoint_rejected')+ expect(+ res.body.errors.some((e: { field: string }) => e.field === 'oauth.generic.tokenEndpoint')+ ).toBe(true)+ expect(createSecretSpy).not.toHaveBeenCalled()+ await expect(gw.getResource('mcpservers', 'my-idp', 'mcp-server')).rejects.toThrow()+ })++ // inv.1: tokenAuthMethod=basic without a secret is a public+basic client → reject.+ it('400 when tokenAuthMethod=basic but no secret is supplied', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'generic' }))+ const { app } = makeInstallApp()+ const res = await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-idp',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: { scopes: ['read'], generic: { ...VALID_KNOBS, tokenAuthMethod: 'basic' } },+ })+ .expect(400)+ expect(res.body.error).toMatch(/basic requires a client secret/)+ })++ // DA-4 / GAP-6: sendScope:true with no scopes ⇒ 400 oauth_scopes_required.+ it('400 oauth_scopes_required when sendScope:true and no scopes supplied', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'generic' }))+ const { app } = makeInstallApp()+ const res = await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-idp',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: { generic: { ...VALID_KNOBS, sendScope: true } },+ })+ .expect(400)+ expect(res.body.error).toBe('oauth_scopes_required')+ })++ // DA-4: sendScope:false legalises an empty scope set.+ it('allows an empty scope set when sendScope:false', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(oauthEntry({ provider: 'generic' }))+ const { app, gw } = makeInstallApp()+ await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-idp',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: { generic: { ...VALID_KNOBS, sendScope: false } },+ })+ .expect(201)+ const server = await readFullServer(gw, 'my-idp')+ expect(server.spec.oauth?.scopes).toEqual([])+ })++ // inv.5: catalog genericConfig NEVER reaches the CR; the wizard-confirmed body wins.+ it('body.oauth.generic wins over a divergent catalog genericConfig (S-4)', async () => {+ vi.mocked(getEntryVersion).mockResolvedValueOnce(+ oauthEntry({+ provider: 'generic',+ genericConfig: {+ authorizationEndpoint: 'https://evil.example.com/authorize',+ tokenEndpoint: 'https://evil.example.com/token',+ },+ })+ )+ const { app, gw } = makeInstallApp()+ await request(app)+ .post('/admin/registry/install')+ .send({+ serverName: 'my-idp',+ contextRef: 'default-context',+ registryEntryName: 'gmail-mcp',+ registryEntryVersion: '1.0.0',+ oauth: { scopes: ['read'], generic: VALID_KNOBS },+ })+ .expect(201)+ const server = await readFullServer(gw, 'my-idp')+ const raw = JSON.stringify(server.spec.oauth)+ expect(raw).not.toContain('evil.example.com')+ expect(server.spec.oauth?.authorizationEndpoint).toBe('https://idp.example.com/authorize')+ })++ // inv.10: uninstall reclaims a generic-confidential managed oauth-client Secret+ // (same derived name as baked), and a public generic server has nothing to delete.+ it('deletes the generic-confidential oauth-client Secret on uninstall', async () => {+ const gw = new MockGateway('mcp-server')+ gw.createResource('mcpservers', {+ metadata: { name: 'my-idp' },+ spec: {+ image: 'clerum/generic-mcp:1.0.0',+ auth: { type: 'oauth' },+ oauth: {+ source: 'generic',+ id: 'my-idp',+ ...VALID_KNOBS,+ clientIdRef: { name: 'my-idp-oauth-client', key: 'client_id' },+ clientSecretRef: { name: 'my-idp-oauth-client', key: 'client_secret' },+ },+ },+ })+ gw.seedSecret('my-idp-oauth-client', 'mcp-server', {+ stringData: { client_id: 'id', client_secret: 'sec' },+ })+ const res = await request(makeApp(gw)).delete('/admin/registry/uninstall/my-idp').expect(200)+ expect(res.body.deleted).toContain('Secret/my-idp-oauth-client')+ await expect(gw.getSecret('my-idp-oauth-client', 'mcp-server')).rejects.toThrow()+ })++ it('uninstall of a PUBLIC generic server (no oauth-client Secret) does not fail', async () => {+ const gw = new MockGateway('mcp-server')+ gw.createResource('mcpservers', {+ metadata: { name: 'my-idp' },+ spec: {+ image: 'clerum/generic-mcp:1.0.0',+ auth: { type: 'oauth' },+ oauth: { source: 'generic', id: 'my-idp', ...VALID_KNOBS },+ },+ })+ // The observable invariant is that uninstall of a public generic server (which+ // never created an oauth-client Secret) returns 200 and removes the server — the+ // best-effort by-name delete tolerates the absent Secret rather than failing.+ await request(makeApp(gw)).delete('/admin/registry/uninstall/my-idp').expect(200)+ await expect(gw.getResource('mcpservers', 'my-idp', 'mcp-server')).rejects.toThrow()+ })+})