Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): oauth kernel seam — public-client signatures + endpoint URL validator
Diego Zacarias11263f25be0d
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 5d2665b68..c76225829 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.587",+ "version": "0.1.588","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.587",+ "version": "0.1.588","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 9ac84821c..d3cc0edd9 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.587",+ "version": "0.1.588","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/http/validateMcpServerSpec.ts b/control-api/src/http/validateMcpServerSpec.tsindex 332da31f9..ddbe8ef27 100644--- a/control-api/src/http/validateMcpServerSpec.ts+++ b/control-api/src/http/validateMcpServerSpec.ts@@ -160,6 +160,20 @@ async function defaultDnsResolver(hostname: string): Promise<string[]> {return answers.map(answer => answer.address)}+/**+ * From a set of resolved addresses, return the ones that must be treated as+ * BLOCKED: a non-IPv4 answer (cannot be range-checked, so fail closed) or an+ * IPv4 that overlaps a private/metadata/link-local/multicast/reserved/internal+ * range. Shared (D4) by the egress preflight and {@link validateOAuthEndpointUrl}+ * so both classify resolved IPs by the exact same rule.+ */+function filterBlockedIpv4(addresses: string[]): string[] {+ return addresses.filter(address => {+ if (ipv4ToInt(address) === null) return true+ return validatePublicCidr(`${address}/32`) !== null+ })+}+/** Parse a Kubernetes resource quantity like "4000m" or "8Gi" into a number. */function parseCpuMillicores(val: string): number | null {if (val.endsWith('m')) return parseInt(val, 10)@@ -419,10 +433,7 @@ export async function validateMcpServerSpecPreflight()return}- const blocked = addresses.filter(address => {- if (ipv4ToInt(address) === null) return true- return validatePublicCidr(`${address}/32`) !== null- })+ const blocked = filterBlockedIpv4(addresses)if (blocked.length > 0) {fields.forEach(field =>errors.push({@@ -449,6 +460,67 @@ export async function validateMcpServerSpecPreflight(return errors}+/**+ * Kernel de política sobre una URL de endpoint OAuth (spec 19 §4): scheme https ++ * host público + resolve→IP no bloqueada. Reusa isPublicDnsHostname/validatePublicCidr.+ * `resolveDns` inyectable ⇒ testeable en Vitest sin cluster. Devuelve [] si válida.+ * Seam compartido para el carril self-hosted 'generic' (S3-B2) y el remoto (spec 02);+ * hoy sin call-sites de producción — es la base del seam.+ */+export async function validateOAuthEndpointUrl(+ rawUrl: string,+ field: string,+ options: { resolveDns?: DnsResolver } = {}+): Promise<ValidationError[]> {+ let url: URL+ try {+ url = new URL(rawUrl)+ } catch {+ return [{ field, message: 'must be a valid absolute URL' }]+ }++ const errors: ValidationError[] = []+ if (url.protocol !== 'https:') {+ errors.push({ field, message: 'must use https' })+ }++ const host = url.hostname+ if (!isPublicDnsHostname(host)) {+ // Same rule as the egress preflight: only syntactically-public hosts are+ // resolved. An internal/literal/malformed host is rejected without a DNS+ // lookup (never resolve to probe internal names).+ errors.push({ field, message: 'host must be a public DNS hostname' })+ return errors+ }++ const resolveDns = options.resolveDns ?? defaultDnsResolver+ try {+ const addresses = Array.from(new Set(await resolveDns(host)))+ if (addresses.length === 0) {+ errors.push({ field, message: `host "${host}" did not resolve to an IPv4 A record` })+ } else {+ const blocked = filterBlockedIpv4(addresses)+ if (blocked.length > 0) {+ errors.push({+ field,+ message:+ `host "${host}" resolved to blocked IPv4 address(es): ${blocked.join(', ')}. ` ++ 'OAuth endpoints must not resolve to private, metadata, link-local, multicast, reserved, or internal ranges.',+ })+ }+ }+ } catch (error) {+ errors.push({+ field,+ message: `host "${host}" could not be resolved: ${+ error instanceof Error ? error.message : String(error)+ }`,+ })+ }++ return errors+}+export async function validateEgressBindingsPreflight(egressBindings: unknown,fieldPrefix = 'spec.egressBindings',diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.tsindex daa4d1039..4ef1815da 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -22,7 +22,13 @@ export interface OAuthClientDecl {id: stringprovider: stringclientIdRef: { name: string; key: string }- clientSecretRef: { name: string; key: string }+ /**+ * Confidential-client secret reference. Optional (E-19.2): a PUBLIC OAuth+ * client declares no secret, so the callback reads only the client_id Secret+ * and the token POST omits `client_secret`. When present, the confidential+ * path is byte-identical to before.+ */+ clientSecretRef?: { name: string; key: string }scopes?: string[]/*** Path B — when true, this client may be connected as a recipe-scoped@@ -461,20 +467,26 @@ async function exchangeAuthCode(return { kind: 'secret_missing', secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}` }}- let clientSecretSecret: Record<string, string>- try {- clientSecretSecret = await deps.secretReader.read(decl.clientSecretRef.name, secretNamespace)- } catch (err) {- if (err instanceof SecretNotFoundError) {- return { kind: 'secret_missing', secret: decl.clientSecretRef.name }+ // Public client (E-19.2): no clientSecretRef ⇒ skip the second Secret read and+ // exchange without a client_secret. When a ref is present the confidential+ // path is unchanged (same read, same fail-closed on missing Secret/key).+ let clientSecret: string | undefined+ if (decl.clientSecretRef) {+ let clientSecretSecret: Record<string, string>+ try {+ clientSecretSecret = await deps.secretReader.read(decl.clientSecretRef.name, secretNamespace)+ } catch (err) {+ if (err instanceof SecretNotFoundError) {+ return { kind: 'secret_missing', secret: decl.clientSecretRef.name }+ }+ throw err}- throw err- }- const clientSecret = clientSecretSecret[decl.clientSecretRef.key]- if (!clientSecret) {- return {- kind: 'secret_missing',- secret: `${decl.clientSecretRef.name}/${decl.clientSecretRef.key}`,+ clientSecret = clientSecretSecret[decl.clientSecretRef.key]+ if (!clientSecret) {+ return {+ kind: 'secret_missing',+ secret: `${decl.clientSecretRef.name}/${decl.clientSecretRef.key}`,+ }}}@@ -488,15 +500,20 @@ async function exchangeAuthCode(const codeVerifier = adapter.usesPkce? deriveCodeVerifier(deps.stateSecret, input.state): undefined- const tokenRequest = adapter.buildTokenRequest({- code: input.code,- clientId,- clientSecret,- redirectUri: input.redirectUri,- codeVerifier,- })try {+ // Build INSIDE the try: a confidential-only baked adapter (notion/monday/+ // clickup) throws when handed a public (secret-less) decl. Keeping the build+ // inside the catch turns that into a typed `provider_response_invalid` (fail+ // closed, no token) instead of an opaque 500 — symmetric with tokenHelper's+ // wrapped `buildRefreshRequest`.+ const tokenRequest = adapter.buildTokenRequest({+ code: input.code,+ clientId,+ clientSecret,+ redirectUri: input.redirectUri,+ codeVerifier,+ })const response = await deps.fetchFn(tokenRequest.url, {method: tokenRequest.method,headers: tokenRequest.headers,diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.tsindex 348b701cd..535804e9a 100644--- a/control-api/src/oauth/mcpServerOAuthSpec.ts+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts@@ -142,6 +142,16 @@ export interface ResolvedServerOAuthSubject {* declaration (missing id/provider/clientIdRef/clientSecretRef) so callers fail* closed. Same field-reading rule as {@link resolveServerOAuth} — kept here so* the authorize-URL minter and the callback never drift (D4).+ *+ * NOTE (E-19.2, deliberate deferral): the refresh-path reader+ * `normalizeMcpServerOwnerDecl` (routes/mcpOauth.ts) already treats an absent+ * `clientSecretRef` as a valid public client. This mint/callback resolver stays+ * confidential-only ON PURPOSE for now: a public mcp-server is not representable+ * in this phase (the CRD still lists `clientSecretRef` as required and there is+ * no `'generic'` provider), so no reachable server diverges between the two+ * readers today. Aligning this resolver (+ making+ * `ResolvedServerOAuthSubject.decl.clientSecretRef` optional) lands together with+ * the CRD/`'generic'` work, where the public-client path first becomes reachable.*/export function resolveServerOAuthSubject(server: McpServerOAuthSpecInputdiff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.tsindex c7da71e62..53a5cbc21 100644--- a/control-api/src/oauth/providers.ts+++ b/control-api/src/oauth/providers.ts@@ -63,7 +63,13 @@ export interface AuthorizeUrlInput {export interface TokenExchangeInput {code: stringclientId: string- clientSecret: string+ /**+ * Confidential-client secret. Optional (E-19.2): a public OAuth client has no+ * secret, so the token POST omits `client_secret`. Adapters for baked+ * confidential providers (notion/monday/clickup) fail closed when it is+ * absent; the standard form-encoded builders simply omit the field.+ */+ clientSecret?: stringredirectUri: string/*** PKCE `code_verifier`, present only for adapters with `usesPkce`. The callback@@ -83,7 +89,8 @@ export interface TokenRequest {export interface RefreshTokenInput {refreshToken: stringclientId: string- clientSecret: string+ /** Confidential-client secret; optional for public clients (E-19.2). */+ clientSecret?: string}export interface ParsedTokenResponse {@@ -156,13 +163,18 @@ function standardTokenRequest(input: TokenExchangeInput,extraHeaders: Record<string, string> = {}): TokenRequest {+ // Insertion order is load-bearing: `urlEncode` walks `Object.entries` in+ // insertion order, so `client_secret` MUST be inserted between `client_id` and+ // `redirect_uri` to keep the emitted body byte-identical to the pre-E-19.2+ // shape whenever the secret is present. A public client (no secret) omits the+ // field entirely.const params: Record<string, string> = {grant_type: 'authorization_code',code: input.code,client_id: input.clientId,- client_secret: input.clientSecret,- redirect_uri: input.redirectUri,}+ if (input.clientSecret) params.client_secret = input.clientSecret+ params.redirect_uri = input.redirectUri// PKCE: appended only when the adapter set `codeVerifier`. Non-PKCE adapters// pass no verifier, so their emitted body stays byte-identical.if (input.codeVerifier) params.code_verifier = input.codeVerifier@@ -191,15 +203,22 @@ function standardRefreshRequest(accept: 'application/json',...extraHeaders,},- body: urlEncode({- grant_type: 'refresh_token',- refresh_token: input.refreshToken,- client_id: input.clientId,- client_secret: input.clientSecret,- }),+ body: urlEncode(standardRefreshParams(input)),}}+// `client_secret` is the trailing field, so a public client (no secret) simply+// drops it and the confidential-client body is byte-identical to pre-E-19.2.+function standardRefreshParams(input: RefreshTokenInput): Record<string, string> {+ const params: Record<string, string> = {+ grant_type: 'refresh_token',+ refresh_token: input.refreshToken,+ client_id: input.clientId,+ }+ if (input.clientSecret) params.client_secret = input.clientSecret+ return params+}+function parseStandardOAuth2(body: unknown): ParsedTokenResponse {if (!isObject(body)) throw new Error('OAuth token response must be an object')return {@@ -286,6 +305,12 @@ const NOTION: OAuthProviderAdapter = {return `https://api.notion.com/v1/oauth/authorize?${urlEncode(params)}`},buildTokenRequest(input) {+ // Notion is a confidential-only baked provider (DEC-3): fail closed when a+ // public client (no secret) reaches this bespoke path. Narrows the optional+ // secret to `string` for the Basic template below.+ if (!input.clientSecret) {+ throw new Error('Notion OAuth requires a confidential client secret')+ }// Notion requires HTTP Basic auth on the token POST instead of client_id /// client_secret in the body.const basic = Buffer.from(`${input.clientId}:${input.clientSecret}`).toString('base64')@@ -405,6 +430,11 @@ const MONDAY: OAuthProviderAdapter = {return `https://auth.monday.com/oauth2/authorize?${urlEncode(params)}`},buildTokenRequest(input) {+ // monday is a confidential-only baked provider (DEC-3): fail closed when a+ // public client (no secret) reaches this bespoke path, and narrow the type.+ if (!input.clientSecret) {+ throw new Error('monday OAuth requires a confidential client secret')+ }// JSON body per the OAuth 2.1 migration doc (not form-urlencoded).const body: Record<string, string> = {grant_type: 'authorization_code',@@ -422,6 +452,10 @@ const MONDAY: OAuthProviderAdapter = {}},buildRefreshRequest(input) {+ // Confidential-only (DEC-3): fail closed for a public client, narrow the type.+ if (!input.clientSecret) {+ throw new Error('monday OAuth requires a confidential client secret')+ }return {url: 'https://auth.monday.com/oauth_ms/oauth/token',method: 'POST',@@ -463,6 +497,11 @@ const CLICKUP: OAuthProviderAdapter = {return `https://app.clickup.com/api?${urlEncode(params)}`},buildTokenRequest(input) {+ // ClickUp is a confidential-only baked provider (DEC-3): fail closed when a+ // public client (no secret) reaches this bespoke path, and narrow the type.+ if (!input.clientSecret) {+ throw new Error('ClickUp OAuth requires a confidential client secret')+ }// Bespoke: no grant_type, no redirect_uri — ClickUp accepts a form-encoded// body of client_id + client_secret + code only.return {diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.tsindex 60bdcc51e..4011fb46b 100644--- a/control-api/src/oauth/tokenHelper.ts+++ b/control-api/src/oauth/tokenHelper.ts@@ -103,23 +103,28 @@ export async function getAccessToken(return { kind: 'secret_missing', secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}` }}- let clientSecretSecret: Record<string, string>- try {- clientSecretSecret = await deps.secretReader.read(- decl.clientSecretRef.name,- input.recipeNamespace- )- } catch (err) {- if (err instanceof SecretNotFoundError) {- return { kind: 'secret_missing', secret: decl.clientSecretRef.name }+ // Public client (E-19.2): no clientSecretRef ⇒ refresh without a client_secret.+ // When a ref is present the confidential path is unchanged.+ let clientSecret: string | undefined+ if (decl.clientSecretRef) {+ let clientSecretSecret: Record<string, string>+ try {+ clientSecretSecret = await deps.secretReader.read(+ decl.clientSecretRef.name,+ input.recipeNamespace+ )+ } catch (err) {+ if (err instanceof SecretNotFoundError) {+ return { kind: 'secret_missing', secret: decl.clientSecretRef.name }+ }+ throw err}- throw err- }- const clientSecret = clientSecretSecret[decl.clientSecretRef.key]- if (!clientSecret) {- return {- kind: 'secret_missing',- secret: `${decl.clientSecretRef.name}/${decl.clientSecretRef.key}`,+ clientSecret = clientSecretSecret[decl.clientSecretRef.key]+ if (!clientSecret) {+ return {+ kind: 'secret_missing',+ secret: `${decl.clientSecretRef.name}/${decl.clientSecretRef.key}`,+ }}}diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex c5ee97884..191e634e6 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -58,7 +58,7 @@ import { extractBearerToken } from '../utils/extractBearerToken.js'* Both branches ship in v1; the `context` branch is governed/exercised by U6.*/-interface McpServerResource {+export interface McpServerResource {metadata?: { name?: string; namespace?: string }spec?: {auth?: { type?: unknown }@@ -76,21 +76,28 @@ interface McpServerResource {* refresh path (`getAccessToken`) already consume. Returns null when the server* is not an OAuth server (no `spec.oauth`), so callers fail closed.*/-function normalizeMcpServerOwnerDecl(server: McpServerResource): RecipeWithOAuthClients | null {+export function normalizeMcpServerOwnerDecl(+ server: McpServerResource+): RecipeWithOAuthClients | null {const oauth = server.spec?.oauthif (!oauth || typeof oauth.id !== 'string' || typeof oauth.provider !== 'string') return nullconst clientIdRef = oauth.clientIdRef- const clientSecretRef = oauth.clientSecretRef- if (- !clientIdRef ||- typeof clientIdRef.name !== 'string' ||- typeof clientIdRef.key !== 'string' ||- !clientSecretRef ||- typeof clientSecretRef.name !== 'string' ||- typeof clientSecretRef.key !== 'string'- ) {+ if (!clientIdRef || typeof clientIdRef.name !== 'string' || typeof clientIdRef.key !== 'string') {return null}+ // clientSecretRef is optional (E-19.2, public client): ABSENT (null/undefined)+ // ⇒ public client (decl carries `clientSecretRef: undefined`); PRESENT-but-+ // malformed stays fail-closed (null) — a half-declared secret ref is a config+ // error, not a public client. `!= null` (not `!== undefined`) so a JSON-null+ // ref from the untrusted CR is treated as absent, never dereferenced.+ const clientSecretRef = oauth.clientSecretRef+ let normalizedSecretRef: { name: string; key: string } | undefined+ if (clientSecretRef != null) {+ if (typeof clientSecretRef.name !== 'string' || typeof clientSecretRef.key !== 'string') {+ return null+ }+ normalizedSecretRef = { name: clientSecretRef.name, key: clientSecretRef.key }+ }return {metadata: server.metadata,spec: {@@ -99,7 +106,7 @@ function normalizeMcpServerOwnerDecl(server: McpServerResource): RecipeWithOAuthid: oauth.id,provider: oauth.provider,clientIdRef: { name: clientIdRef.name, key: clientIdRef.key },- clientSecretRef: { name: clientSecretRef.name, key: clientSecretRef.key },+ clientSecretRef: normalizedSecretRef,scopes: Array.isArray(oauth.scopes)? oauth.scopes.filter((s): s is string => typeof s === 'string'): undefined,diff --git a/control-api/test/mcpOauth.normalizeOwnerDecl.test.ts b/control-api/test/mcpOauth.normalizeOwnerDecl.test.tsnew file mode 100644index 000000000..bad344539--- /dev/null+++ b/control-api/test/mcpOauth.normalizeOwnerDecl.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from 'vitest'+import { type McpServerResource, normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'++/**+ * T5 (E-19.2): normalizeMcpServerOwnerDecl treats an ABSENT clientSecretRef as a+ * valid public client (decl carries `clientSecretRef: undefined`), keeps a+ * PRESENT-but-malformed ref fail-closed (null), and still requires a well-formed+ * clientIdRef.+ */+function server(oauth: Record<string, unknown> | undefined): McpServerResource {+ return {+ metadata: { name: 'srv', namespace: 'mcp-servers' },+ spec: oauth === undefined ? {} : { oauth: oauth as never },+ }+}++const CLIENT_ID_REF = { name: 'creds', key: 'client-id' }+const CLIENT_SECRET_REF = { name: 'creds', key: 'client-secret' }++describe('normalizeMcpServerOwnerDecl', () => {+ it('public client (no clientSecretRef) → decl with clientSecretRef undefined', () => {+ const result = normalizeMcpServerOwnerDecl(+ server({ id: 'oc', provider: 'google', clientIdRef: CLIENT_ID_REF })+ )+ expect(result).not.toBeNull()+ const decl = result!.spec!.oauthClients![0]+ expect(decl.id).toBe('oc')+ expect(decl.provider).toBe('google')+ expect(decl.clientIdRef).toEqual(CLIENT_ID_REF)+ expect(decl.clientSecretRef).toBeUndefined()+ expect('clientSecretRef' in decl).toBe(true)+ })++ it('confidential client (both refs) → full decl', () => {+ const result = normalizeMcpServerOwnerDecl(+ server({+ id: 'oc',+ provider: 'notion',+ clientIdRef: CLIENT_ID_REF,+ clientSecretRef: CLIENT_SECRET_REF,+ })+ )+ expect(result).not.toBeNull()+ const decl = result!.spec!.oauthClients![0]+ expect(decl.clientIdRef).toEqual(CLIENT_ID_REF)+ expect(decl.clientSecretRef).toEqual(CLIENT_SECRET_REF)+ })++ it('malformed clientSecretRef (name not a string) → null (fail closed)', () => {+ const result = normalizeMcpServerOwnerDecl(+ server({+ id: 'oc',+ provider: 'google',+ clientIdRef: CLIENT_ID_REF,+ clientSecretRef: { name: 123, key: 'client-secret' },+ })+ )+ expect(result).toBeNull()+ })++ it('clientSecretRef: null (JSON-null from untrusted CR) → public client, never throws', () => {+ // Guard against a `!== undefined` check, which would enter the branch and+ // dereference null (TypeError → opaque 500 on the refresh path). `!= null`+ // treats a JSON-null ref from the untrusted CR as absent (public client),+ // so a malformed-as-null ref never crashes the reader.+ const result = normalizeMcpServerOwnerDecl(+ server({+ id: 'oc',+ provider: 'google',+ clientIdRef: CLIENT_ID_REF,+ clientSecretRef: null,+ })+ )+ expect(result).not.toBeNull()+ expect(result!.spec!.oauthClients![0].clientSecretRef).toBeUndefined()+ })++ it('missing clientIdRef → null', () => {+ const result = normalizeMcpServerOwnerDecl(server({ id: 'oc', provider: 'google' }))+ expect(result).toBeNull()+ })++ it('no spec.oauth → null', () => {+ expect(normalizeMcpServerOwnerDecl(server(undefined))).toBeNull()+ })+})diff --git a/control-api/test/oauth.callback.publicClient.test.ts b/control-api/test/oauth.callback.publicClient.test.tsnew file mode 100644index 000000000..9f4262e03--- /dev/null+++ b/control-api/test/oauth.callback.publicClient.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it, vi } from 'vitest'+import {+ type CallbackDeps,+ type RecipeReader,+ type RecipeWithOAuthClients,+ type SecretReader,+ handleOAuthCallback,+} from '../src/oauth/callback.js'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { signOAuthState } from '../src/oauth/state.js'++/**+ * T5 (E-19.2): a PUBLIC OAuth client (no clientSecretRef) exchanges the auth code+ * WITHOUT reading a client_secret Secret and WITHOUT sending `client_secret` in+ * the token POST. The state/decl fixtures are derived from the real minter+ * (`signOAuthState`) and the real reader shape, not hand-built protocol bytes.+ */+const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'+const ENCRYPTION_KEY = deriveOAuthEncryptionKey(+ '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'+)+const REDIRECT_URI = 'https://control.example.com/api/v1/oauth-callback/salesforce'+const USER_ID = 'user-uuid-1'++// A recipe whose salesforce oauthClient declares NO clientSecretRef (public).+function recipeWithPublicSalesforce(): RecipeWithOAuthClients {+ return {+ metadata: { name: 'crm', namespace: 'sandbox-recipes' },+ spec: {+ oauthClients: [+ {+ id: 'salesforce',+ provider: 'salesforce',+ clientIdRef: { name: 'salesforce-creds', key: 'client-id' },+ // no clientSecretRef → public client+ scopes: ['api'],+ },+ ],+ },+ }+}++it('public client: exchanges without reading or sending a client_secret', async () => {+ const db = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }) }++ const recipeReader: RecipeReader = { read: vi.fn(async () => recipeWithPublicSalesforce()) }++ // Only the client-id Secret exists; count reads to prove the secret read is skipped.+ const secretReader: SecretReader = {+ read: vi.fn(async (name: string) =>+ name === 'salesforce-creds' ? { 'client-id': 'CID' } : {}+ ),+ }++ let capturedBody = ''+ const fetchFn = vi.fn(async (_url: string, init: { body?: string }) => {+ capturedBody = init.body ?? ''+ return {+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'AT',+ refresh_token: 'RT',+ expires_in: 3600,+ token_type: 'Bearer',+ }),+ text: async () => '',+ } as Response+ })++ const deps: CallbackDeps = {+ db: db as unknown as CallbackDeps['db'],+ recipeReader,+ secretReader,+ fetchFn: fetchFn as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey: ENCRYPTION_KEY,+ }++ const state = signOAuthState(STATE_SECRET, {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'crm',+ userId: USER_ID,+ oauthClientId: 'salesforce',+ grantKind: 'user',+ background: false,+ })++ const result = await handleOAuthCallback(+ { oauthClientId: 'salesforce', code: 'AUTH_CODE', state, redirectUri: REDIRECT_URI },+ deps+ )++ expect(result.kind).toBe('ok')+ // Only the client-id Secret is read — the second (client_secret) read is skipped.+ expect(secretReader.read).toHaveBeenCalledTimes(1)+ expect(secretReader.read).toHaveBeenCalledWith('salesforce-creds', 'sandbox-recipes')+ // The token POST carries no client_secret.+ expect(capturedBody).not.toContain('client_secret')+ expect(capturedBody).toContain('grant_type=authorization_code')+ expect(capturedBody).toContain('client_id=CID')+})++describe('confidential client (control) still reads + sends client_secret', () => {+ it('reads both Secrets and sends client_secret when clientSecretRef is present', async () => {+ const db = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }) }+ const recipeReader: RecipeReader = {+ read: vi.fn(+ async (): Promise<RecipeWithOAuthClients> => ({+ metadata: { name: 'crm', namespace: 'sandbox-recipes' },+ spec: {+ oauthClients: [+ {+ id: 'salesforce',+ provider: 'salesforce',+ clientIdRef: { name: 'salesforce-creds', key: 'client-id' },+ clientSecretRef: { name: 'salesforce-creds', key: 'client-secret' },+ scopes: ['api'],+ },+ ],+ },+ })+ ),+ }+ const secretReader: SecretReader = {+ read: vi.fn(async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' })),+ }+ let capturedBody = ''+ const fetchFn = vi.fn(async (_url: string, init: { body?: string }) => {+ capturedBody = init.body ?? ''+ return {+ ok: true,+ status: 200,+ json: async () => ({ access_token: 'AT', token_type: 'Bearer' }),+ text: async () => '',+ } as Response+ })+ const deps: CallbackDeps = {+ db: db as unknown as CallbackDeps['db'],+ recipeReader,+ secretReader,+ fetchFn: fetchFn as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey: ENCRYPTION_KEY,+ }+ const state = signOAuthState(STATE_SECRET, {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'crm',+ userId: USER_ID,+ oauthClientId: 'salesforce',+ grantKind: 'user',+ background: false,+ })+ const result = await handleOAuthCallback(+ { oauthClientId: 'salesforce', code: 'AUTH_CODE', state, redirectUri: REDIRECT_URI },+ deps+ )+ expect(result.kind).toBe('ok')+ expect(secretReader.read).toHaveBeenCalledTimes(2)+ expect(capturedBody).toContain('client_secret=CSEC')+ })+})diff --git a/control-api/test/oauth.providers.golden.test.ts b/control-api/test/oauth.providers.golden.test.tsnew file mode 100644index 000000000..5db5ac82e--- /dev/null+++ b/control-api/test/oauth.providers.golden.test.ts@@ -0,0 +1,276 @@+import { describe, expect, it } from 'vitest'+import {+ KNOWN_OAUTH_PROVIDERS,+ type OAuthProvider,+ type TokenRequest,+ getOAuthProviderAdapter,+} from '../src/oauth/providers.js'++/**+ * T1 golden (spec 19 §7 T1 / invariant §6.2): the request bytes emitted by the 8+ * real, baked adapters MUST be byte-identical after E-19.2 (client-public+ * signatures). E-19.2 made `clientSecret` optional but must NOT alter any request+ * when the secret is PRESENT — the confidential path is what every baked provider+ * uses today.+ *+ * The `actual` values are DERIVED from the real producer (`getOAuthProviderAdapter`+ * / `ADAPTERS`) — never hand-built. The `GOLDEN_*` values are the frozen literal+ * bytes those adapters emitted before the change; any reorder or byte drift turns+ * this red.+ */++const REDIRECT = 'https://control.example.com/api/v1/oauth-callback/provider'+const SCOPES = ['scope-a', 'scope-b']++// Confidential-client inputs — every baked provider is confidential (DEC-3).+const AUTHORIZE_INPUT = (usesPkce: boolean) => ({+ clientId: 'cid',+ redirectUri: REDIRECT,+ state: 'signed-state',+ scopes: SCOPES,+ codeChallenge: usesPkce ? 'CHALLENGE' : undefined,+})+const TOKEN_INPUT = (usesPkce: boolean) => ({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: REDIRECT,+ codeVerifier: usesPkce ? 'VERIFIER' : undefined,+})+const REFRESH_INPUT = { refreshToken: 'RT', clientId: 'cid', clientSecret: 'csec' }++const FORM = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }+const JSON_HEADERS = { 'content-type': 'application/json', accept: 'application/json' }++const GOLDEN_AUTHORIZE: Record<OAuthProvider, string> = {+ salesforce:+ 'https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&state=signed-state&scope=scope-a%20scope-b',+ slack:+ 'https://slack.com/oauth/v2/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&state=signed-state&scope=scope-a%2Cscope-b',+ notion:+ 'https://api.notion.com/v1/oauth/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&response_type=code&owner=user&state=signed-state',+ 'microsoft-graph':+ 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&response_type=code&response_mode=query&scope=scope-a%20scope-b&state=signed-state',+ google:+ 'https://accounts.google.com/o/oauth2/v2/auth?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&response_type=code&access_type=offline&prompt=consent&state=signed-state&scope=scope-a%20scope-b',+ monday:+ 'https://auth.monday.com/oauth2/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&response_type=code&state=signed-state&scope=scope-a%20scope-b&code_challenge=CHALLENGE&code_challenge_method=S256',+ clickup:+ 'https://app.clickup.com/api?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&state=signed-state',+ vercel:+ 'https://vercel.com/oauth/authorize?client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&response_type=code&scope=scope-a%20scope-b&state=signed-state&code_challenge=CHALLENGE&code_challenge_method=S256',+}++const GOLDEN_TOKEN: Record<OAuthProvider, TokenRequest> = {+ salesforce: {+ url: 'https://login.salesforce.com/services/oauth2/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=authorization_code&code=thecode&client_id=cid&client_secret=csec&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider',+ },+ slack: {+ url: 'https://slack.com/api/oauth.v2.access',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=authorization_code&code=thecode&client_id=cid&client_secret=csec&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider',+ },+ notion: {+ url: 'https://api.notion.com/v1/oauth/token',+ method: 'POST',+ headers: { ...JSON_HEADERS, authorization: 'Basic Y2lkOmNzZWM=' },+ body: '{"grant_type":"authorization_code","code":"thecode","redirect_uri":"https://control.example.com/api/v1/oauth-callback/provider"}',+ },+ 'microsoft-graph': {+ url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=authorization_code&code=thecode&client_id=cid&client_secret=csec&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider',+ },+ google: {+ url: 'https://oauth2.googleapis.com/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=authorization_code&code=thecode&client_id=cid&client_secret=csec&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider',+ },+ monday: {+ url: 'https://auth.monday.com/oauth_ms/oauth/token',+ method: 'POST',+ headers: JSON_HEADERS,+ body: '{"grant_type":"authorization_code","client_id":"cid","client_secret":"csec","code":"thecode","redirect_uri":"https://control.example.com/api/v1/oauth-callback/provider","code_verifier":"VERIFIER"}',+ },+ clickup: {+ url: 'https://api.clickup.com/api/v2/oauth/token',+ method: 'POST',+ headers: FORM,+ body: 'client_id=cid&client_secret=csec&code=thecode',+ },+ vercel: {+ url: 'https://api.vercel.com/login/oauth/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=authorization_code&code=thecode&client_id=cid&client_secret=csec&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider&code_verifier=VERIFIER',+ },+}++// Refresh: form-encoded standard for the standard providers; JSON for monday;+// notion + clickup have no refresh token and THROW.+const GOLDEN_REFRESH: Record<OAuthProvider, TokenRequest | { throws: RegExp }> = {+ salesforce: {+ url: 'https://login.salesforce.com/services/oauth2/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=refresh_token&refresh_token=RT&client_id=cid&client_secret=csec',+ },+ slack: {+ url: 'https://slack.com/api/oauth.v2.access',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=refresh_token&refresh_token=RT&client_id=cid&client_secret=csec',+ },+ notion: { throws: /does not support refresh tokens/ },+ 'microsoft-graph': {+ url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=refresh_token&refresh_token=RT&client_id=cid&client_secret=csec',+ },+ google: {+ url: 'https://oauth2.googleapis.com/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=refresh_token&refresh_token=RT&client_id=cid&client_secret=csec',+ },+ monday: {+ url: 'https://auth.monday.com/oauth_ms/oauth/token',+ method: 'POST',+ headers: JSON_HEADERS,+ body: '{"grant_type":"refresh_token","client_id":"cid","client_secret":"csec","refresh_token":"RT"}',+ },+ clickup: { throws: /does not support refresh tokens/ },+ vercel: {+ url: 'https://api.vercel.com/login/oauth/token',+ method: 'POST',+ headers: FORM,+ body: 'grant_type=refresh_token&refresh_token=RT&client_id=cid&client_secret=csec',+ },+}++function isThrows(v: TokenRequest | { throws: RegExp }): v is { throws: RegExp } {+ return 'throws' in v+}++describe('OAuth adapters — byte-identical golden (T1, §6.2)', () => {+ it('covers all 8 baked providers', () => {+ expect([...KNOWN_OAUTH_PROVIDERS].sort()).toEqual(+ [+ 'clickup',+ 'google',+ 'microsoft-graph',+ 'monday',+ 'notion',+ 'salesforce',+ 'slack',+ 'vercel',+ ].sort()+ )+ })++ for (const provider of [...KNOWN_OAUTH_PROVIDERS]) {+ describe(provider, () => {+ const a = getOAuthProviderAdapter(provider)+ const usesPkce = a.usesPkce === true++ it('authorize URL is byte-identical', () => {+ expect(a.buildAuthorizeUrl(AUTHORIZE_INPUT(usesPkce))).toBe(GOLDEN_AUTHORIZE[provider])+ })++ it('token request is byte-identical', () => {+ expect(a.buildTokenRequest(TOKEN_INPUT(usesPkce))).toEqual(GOLDEN_TOKEN[provider])+ })++ it('refresh request matches the golden (or throws)', () => {+ const golden = GOLDEN_REFRESH[provider]+ if (isThrows(golden)) {+ expect(() => a.buildRefreshRequest(REFRESH_INPUT)).toThrow(golden.throws)+ } else {+ expect(a.buildRefreshRequest(REFRESH_INPUT)).toEqual(golden)+ }+ })+ })+ }++ // Explicit ordering guard for a standardTokenRequest provider: with the secret+ // PRESENT the body is exactly grant_type&code&client_id&client_secret&redirect_uri.+ it('standardTokenRequest keeps client_secret between client_id and redirect_uri', () => {+ const body = getOAuthProviderAdapter('salesforce').buildTokenRequest({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: REDIRECT,+ }).body+ expect(body).toBe(+ 'grant_type=authorization_code&code=thecode&client_id=cid&client_secret=csec&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider'+ )+ })+})++// ─── T5 E-19.2: public client (no secret) omits client_secret ──────────────+describe('E-19.2 public client — client_secret omitted when absent', () => {+ const a = getOAuthProviderAdapter('salesforce')++ it('token POST omits client_secret when clientSecret is undefined', () => {+ const body = a.buildTokenRequest({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: undefined,+ redirectUri: REDIRECT,+ }).body+ expect(body).not.toContain('client_secret')+ expect(body).toBe(+ 'grant_type=authorization_code&code=thecode&client_id=cid&redirect_uri=https%3A%2F%2Fcontrol.example.com%2Fapi%2Fv1%2Foauth-callback%2Fprovider'+ )+ })++ it('token POST includes client_secret when present (confidential order)', () => {+ const body = a.buildTokenRequest({+ code: 'thecode',+ clientId: 'cid',+ clientSecret: 'csec',+ redirectUri: REDIRECT,+ }).body+ expect(body).toContain('&client_secret=csec&')+ })++ it('refresh POST omits client_secret when clientSecret is undefined', () => {+ const body = a.buildRefreshRequest({+ refreshToken: 'RT',+ clientId: 'cid',+ clientSecret: undefined,+ }).body+ expect(body).not.toContain('client_secret')+ expect(body).toBe('grant_type=refresh_token&refresh_token=RT&client_id=cid')+ })++ it('refresh POST includes client_secret when present', () => {+ const body = a.buildRefreshRequest({+ refreshToken: 'RT',+ clientId: 'cid',+ clientSecret: 'csec',+ }).body+ expect(body).toBe('grant_type=refresh_token&refresh_token=RT&client_id=cid&client_secret=csec')+ })++ it('confidential-only baked adapters fail closed for a public client', () => {+ for (const provider of ['notion', 'monday', 'clickup'] as const) {+ expect(() =>+ getOAuthProviderAdapter(provider).buildTokenRequest({+ code: 'c',+ clientId: 'cid',+ clientSecret: undefined,+ redirectUri: REDIRECT,+ codeVerifier: 'V',+ })+ ).toThrow(/requires a confidential client secret/)+ }+ })+})diff --git a/control-api/test/validateMcpServerSpec.oauthEndpoint.test.ts b/control-api/test/validateMcpServerSpec.oauthEndpoint.test.tsnew file mode 100644index 000000000..0b6d72acf--- /dev/null+++ b/control-api/test/validateMcpServerSpec.oauthEndpoint.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it, vi } from 'vitest'+import { validateOAuthEndpointUrl } from '../src/http/validateMcpServerSpec.js'++/**+ * Kernel §4 (spec 19): validateOAuthEndpointUrl. https + public host + resolve→+ * non-blocked IP. `resolveDns` is injected (vi.fn) so the check runs with no+ * cluster, mirroring validateMcpServerSpec.test.ts's preflight tests.+ */+const FIELD = 'spec.oauth.tokenUrl'++describe('validateOAuthEndpointUrl (kernel §4)', () => {+ it('accepts https + public host resolving to a public IPv4', async () => {+ const resolveDns = vi.fn(async () => ['93.184.216.34'])+ const errors = await validateOAuthEndpointUrl('https://api.example.com/oauth/token', FIELD, {+ resolveDns,+ })+ expect(errors).toEqual([])+ expect(resolveDns).toHaveBeenCalledTimes(1)+ expect(resolveDns).toHaveBeenCalledWith('api.example.com')+ })++ it('rejects http scheme (still validates host + resolve)', async () => {+ const resolveDns = vi.fn(async () => ['93.184.216.34'])+ const errors = await validateOAuthEndpointUrl('http://api.example.com/token', FIELD, {+ resolveDns,+ })+ expect(errors).toEqual(+ expect.arrayContaining([expect.objectContaining({ field: FIELD, message: 'must use https' })])+ )+ // host is public + resolves clean, so `must use https` is the only error.+ expect(errors).toHaveLength(1)+ expect(resolveDns).toHaveBeenCalledTimes(1)+ })++ it('rejects a host resolving to a private range', async () => {+ const resolveDns = vi.fn(async () => ['10.0.0.5'])+ const errors = await validateOAuthEndpointUrl('https://api.example.com/token', FIELD, {+ resolveDns,+ })+ expect(errors).toEqual([+ expect.objectContaining({ field: FIELD, message: expect.stringContaining('10.0.0.5') }),+ ])+ })++ it('rejects a host resolving to the metadata IP', async () => {+ const resolveDns = vi.fn(async () => ['169.254.169.254'])+ const errors = await validateOAuthEndpointUrl('https://api.example.com/token', FIELD, {+ resolveDns,+ })+ expect(errors).toEqual([+ expect.objectContaining({+ field: FIELD,+ message: expect.stringContaining('169.254.169.254'),+ }),+ ])+ })++ it.each(['https://foo.local/token', 'https://localhost/token', 'https://10.0.0.1/token'])(+ 'rejects internal/literal host %s without resolving DNS',+ async rawUrl => {+ const resolveDns = vi.fn(async () => ['93.184.216.34'])+ const errors = await validateOAuthEndpointUrl(rawUrl, FIELD, { resolveDns })+ expect(errors).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ field: FIELD,+ message: 'host must be a public DNS hostname',+ }),+ ])+ )+ expect(resolveDns).not.toHaveBeenCalled()+ }+ )++ it('rejects a malformed URL without resolving DNS', async () => {+ const resolveDns = vi.fn(async () => ['93.184.216.34'])+ const errors = await validateOAuthEndpointUrl('not a url', FIELD, { resolveDns })+ expect(errors).toEqual([{ field: FIELD, message: 'must be a valid absolute URL' }])+ expect(resolveDns).not.toHaveBeenCalled()+ })++ it('rejects a host that does not resolve to an A record', async () => {+ const resolveDns = vi.fn(async () => [])+ const errors = await validateOAuthEndpointUrl('https://api.example.com/token', FIELD, {+ resolveDns,+ })+ expect(errors).toEqual([+ expect.objectContaining({+ field: FIELD,+ message: expect.stringContaining('did not resolve'),+ }),+ ])+ })++ it('surfaces a DNS resolution error', async () => {+ const resolveDns = vi.fn(async () => {+ throw new Error('ENOTFOUND')+ })+ const errors = await validateOAuthEndpointUrl('https://api.example.com/token', FIELD, {+ resolveDns,+ })+ expect(errors).toEqual([+ expect.objectContaining({+ field: FIELD,+ message: expect.stringContaining('could not be resolved: ENOTFOUND'),+ }),+ ])+ })++ // T1 rebind: each validation is independent — the same host that resolved to a+ // public IP on one call is rejected when it resolves to a blocked IP on the+ // next. No caching across calls.+ it('re-resolves on every call (no cross-call cache)', async () => {+ const resolveDns = vi+ .fn<(host: string) => Promise<string[]>>()+ .mockResolvedValueOnce(['93.184.216.34'])+ .mockResolvedValueOnce(['10.0.0.5'])++ const first = await validateOAuthEndpointUrl('https://rebind.example.com/token', FIELD, {+ resolveDns,+ })+ expect(first).toEqual([])++ const second = await validateOAuthEndpointUrl('https://rebind.example.com/token', FIELD, {+ resolveDns,+ })+ expect(second).toEqual([+ expect.objectContaining({ field: FIELD, message: expect.stringContaining('10.0.0.5') }),+ ])+ expect(resolveDns).toHaveBeenCalledTimes(2)+ })+})