Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(crds,control-api): tie remote secret refs to clientMode and pin bearerInBody false (R3-H8)
Diego Zacarias50a5550babf6
diff --git a/charts/clerum-crds/crds/mcpserver.yaml b/charts/clerum-crds/crds/mcpserver.yamlindex c141f992c..ad11483a0 100644--- a/charts/clerum-crds/crds/mcpserver.yaml+++ b/charts/clerum-crds/crds/mcpserver.yaml@@ -279,9 +279,10 @@ spec:bearerInBody:type: booleandescription: >-- REMOTE only (D-8). Token goes in the request body, not the- Authorization header. No default (required-by-CEL for remote).- Immutable (pinned at install; runtime never re-derives).+ REMOTE only (D-8). Whether the AS wants the token in the request+ body instead of the Authorization header. Must be false: the+ runtime only sends the header (enforced by CEL). No default+ (required-by-CEL for remote). Immutable (pinned at install).supportsRefresh:type: booleandescription: >-@@ -665,8 +666,11 @@ spec:# charset). Exempts ONLY remote (source == 'remote' short-circuits);# baked (source absent) AND generic get the slug narrow, since a# generic client_id IS spec.oauth.id and must be a callback-path-safe slug.- - rule: "!has(self.oauth) || (has(self.oauth.source) && self.oauth.source == 'remote') || !has(self.oauth.id) || self.oauth.id.matches('^[a-z0-9-]{1,63}$')"- message: "baked/generic spec.oauth.id must match ^[a-z0-9-]{1,63}$"+ # 'remote' is reserved: baked/generic callbacks route by /oauth-callback/<id>,+ # and /oauth-callback/remote is the single stable redirect every remote+ # client registers, so a baked/generic server with that id would share it.+ - rule: "!has(self.oauth) || (has(self.oauth.source) && self.oauth.source == 'remote') || !has(self.oauth.id) || (self.oauth.id.matches('^[a-z0-9-]{1,63}$') && self.oauth.id != 'remote')"+ message: "baked/generic spec.oauth.id must match ^[a-z0-9-]{1,63}$ and must not be 'remote' (reserved for the remote OAuth callback)"# BAKED-REQ: baked (no source) requires the classic adapter quartet.- rule: "!has(self.oauth) || has(self.oauth.source) || (has(self.oauth.id) && has(self.oauth.provider) && has(self.oauth.clientIdRef) && has(self.oauth.clientSecretRef))"message: "baked spec.oauth (no source) requires id, provider, clientIdRef and clientSecretRef"@@ -727,14 +731,21 @@ spec:# no secret); confidential = both refs. Mixed pairing is rejected.- rule: "!has(self.oauth) || !has(self.oauth.source) || self.oauth.source != 'generic' || (has(self.oauth.clientIdRef) == has(self.oauth.clientSecretRef))"message: "generic spec.oauth must set clientIdRef and clientSecretRef together (confidential) or neither (public)"- # REMOTE-SECRET-PAIRING: remote secret refs are BOTH-OR-NEITHER. Unlike- # generic, remote must NOT tie refs to clientMode: the three valid remote- # shapes are public (no refs), DCR-confidential (no refs — the secret lives- # in the encrypted dynamic_clients store, DEC-8), and pre-registered-- # confidential (both refs). So confidential is legal WITH or WITHOUT refs;- # the only invalid shape is exactly-one-ref (a half-declared secret source).- - rule: "!has(self.oauth) || !has(self.oauth.source) || self.oauth.source != 'remote' || (has(self.oauth.clientIdRef) == has(self.oauth.clientSecretRef))"- message: "remote spec.oauth must set clientIdRef and clientSecretRef together or neither"+ # REMOTE-SECRET-PAIRING: the three valid remote shapes are public (no refs),+ # DCR-confidential (no refs — the secret lives in the encrypted+ # dynamic_clients store) and pre-registered-confidential (both refs). So+ # refs are both-or-neither, and public additionally forbids them: a public+ # client has no secret, and the runtime cannot honor refs declared on one.+ # Confidential stays legal WITH or WITHOUT refs, so presence of refs must+ # not be required by clientMode (that would break DCR-confidential).+ - rule: "!has(self.oauth) || !has(self.oauth.source) || self.oauth.source != 'remote' || ((has(self.oauth.clientIdRef) == has(self.oauth.clientSecretRef)) && (!has(self.oauth.clientMode) || self.oauth.clientMode != 'public' || !has(self.oauth.clientIdRef)))"+ message: "remote spec.oauth must set clientIdRef and clientSecretRef together or neither, and neither when clientMode is public"+ # REMOTE-BEARER-HEADER: mcp-host always sends the access token in the+ # Authorization header, so a remote server that needs it in the request+ # body cannot be served. The field stays required (REMOTE-REQ) but only+ # false is admissible.+ - rule: "!has(self.oauth) || !has(self.oauth.source) || self.oauth.source != 'remote' || !has(self.oauth.bearerInBody) || self.oauth.bearerInBody == false"+ message: "remote spec.oauth.bearerInBody must be false; the access token is only sent in the Authorization header"# SOURCE-VALUE-IMM: IMM-5 pins source PRESENCE; this pins the VALUE so a# generic⇄remote flip in place is rejected even though both keep source set.- rule: "!has(oldSelf.oauth) || !has(self.oauth) || !has(oldSelf.oauth.source) || !has(self.oauth.source) || oldSelf.oauth.source == self.oauth.source"diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 298bf1c70..759d3f66c 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.672",+ "version": "0.1.673","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.672",+ "version": "0.1.673","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 c71904398..caf4e10e7 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.672",+ "version": "0.1.673","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/callback.ts b/control-api/src/oauth/callback.tsindex 66d80c33d..33b7b30a2 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -3,6 +3,10 @@ import type { PinnedTransport } from '../http/pinnedFetch.js'import { pinnedFetch } from '../http/pinnedFetch.js'import type { DnsResolver } from '../http/validateMcpServerSpec.js'import { getDynamicClient } from './dynamicClientStore.js'+import {+ type RemoteOAuthSpecIncoherence,+ RemoteOAuthSpecIncoherentError,+} from './mcpServerOAuthSpec.js'import { deriveCodeVerifier } from './pkce.js'import {type GenericAdapterConfig,@@ -198,7 +202,8 @@ export interface McpServerOAuthReader {/*** Resolve an OAuth McpServer by name from the mcp-servers namespace. Returns* null when the server does not exist or is not a usable OAuth server, so- * callers fail closed. May throw {@link RecipeNotFoundError} for a hard 404.+ * callers fail closed. May throw {@link RecipeNotFoundError} for a hard 404, or+ * {@link RemoteOAuthSpecIncoherentError} for a remote spec the runtime cannot honor.*/read(mcpServerName: string): Promise<McpServerOAuthSubject | null>}@@ -340,6 +345,11 @@ export type CallbackResult =* 403, no persist.*/| { kind: 'context_membership_denied' }+ /**+ * mcp subject whose remote `spec.oauth` the runtime cannot honor (public client+ * with secret refs, or bearerInBody). Fail closed BEFORE the code is exchanged.+ */+ | { kind: 'remote_oauth_spec_incoherent'; reason: RemoteOAuthSpecIncoherence }| { kind: 'secret_missing'; secret: string }| { kind: 'unsupported_provider'; provider: string }| { kind: 'provider_token_exchange_failed'; status: number; body: string }@@ -493,6 +503,9 @@ async function handleMcpOAuthCallback(subject = await deps.mcpServerReader.read(claims.mcpServerName)} catch (err) {if (err instanceof RecipeNotFoundError) return { kind: 'server_not_found' }+ if (err instanceof RemoteOAuthSpecIncoherentError) {+ return { kind: 'remote_oauth_spec_incoherent', reason: err.reason }+ }throw err}if (!subject) return { kind: 'server_not_found' }diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.tsindex f957da27b..16c7f7f1e 100644--- a/control-api/src/oauth/mcpServerOAuthSpec.ts+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts@@ -11,6 +11,7 @@* All read the SAME fields the SAME way and derive the SAME `oauth_grants` key* (`buildMcpServerGrantKey`), so the rule lives here once.*/+import { rootLogger } from '../observability/logger.js'import type {GenericClientRouting,OAuthClientDecl,@@ -20,6 +21,8 @@ import type {import { MAX_EXTRA_AUTHORIZE_PARAMS, MAX_EXTRA_AUTHORIZE_PARAM_VALUE_LEN } from './genericKnobs.js'import type { OAuthGrantKey } from './store.js'+const log = rootLogger.child({ module: 'mcp-server-oauth-spec' })+export interface McpServerOAuthDecl {id?: unknownprovider?: unknown@@ -52,7 +55,7 @@ export interface McpServerOAuthDecl {/** Minimal structural shape needed to resolve a server's OAuth grant coordinate. */export interface McpServerOAuthSpecInput {- metadata?: { uid?: unknown }+ metadata?: { uid?: unknown; name?: unknown }spec?: {oauth?: McpServerOAuthDecl// `spec.contextRef` is REQUIRED + singular on the CRD ("the context this@@ -188,6 +191,60 @@ export interface ResolvedServerOAuthSubject {crUid?: string}+export type RemoteOAuthSpecIncoherence = 'public_client_with_secret_refs' | 'bearer_in_body'++/**+ * A remote `spec.oauth` the admission rules reject but that reached the apiserver+ * anyway (CRD applied after the object, or a write that bypassed validation). The+ * runtime cannot honor it, so consent, authorize-URL minting and token issuance+ * refuse it with this specific error instead of degrading to a generic failure.+ */+export class RemoteOAuthSpecIncoherentError extends Error {+ readonly code = 'remote_oauth_spec_incoherent'+ constructor(readonly reason: RemoteOAuthSpecIncoherence) {+ super(`remote spec.oauth is incoherent: ${reason}`)+ this.name = 'RemoteOAuthSpecIncoherentError'+ }+}++function remoteOAuthSpecIncoherence(oauth: McpServerOAuthDecl): RemoteOAuthSpecIncoherence | null {+ if (+ oauth.clientMode === 'public' &&+ (oauth.clientIdRef != null || oauth.clientSecretRef != null)+ ) {+ return 'public_client_with_secret_refs'+ }+ if (oauth.bearerInBody === true) return 'bearer_in_body'+ return null+}++/**+ * Runtime mirror of the remote-carril coherence rules of the McpServer CRD+ * (REMOTE-SECRET-PAIRING for `public`, REMOTE-BEARER-HEADER). Throws+ * {@link RemoteOAuthSpecIncoherentError} for a remote server whose shape no+ * install path produces; a no-op for every other lane.+ *+ * Deliberately NOT applied by {@link resolveServerOAuth}: that coordinate backs+ * revoke and the grant-existence sweep, and an incoherent server must still be+ * disconnectable and must not push the sweep into its fail-open branch.+ */+export function assertRemoteOAuthSpecCoherent(server: McpServerOAuthSpecInput): void {+ const oauth = server.spec?.oauth+ if (!oauth || oauth.source !== 'remote') return+ const reason = remoteOAuthSpecIncoherence(oauth)+ if (!reason) return+ const name = server.metadata?.name+ log.warn(+ {+ event: 'remote_oauth_spec_incoherent',+ mcpServerName: typeof name === 'string' ? name : undefined,+ reason,+ },+ 'remote mcp-server oauth spec is incoherent; refusing consent and token issuance'+ )+ throw new RemoteOAuthSpecIncoherentError(reason)+}+/** Extract + type-validate the remote routing block from an untrusted `spec.oauth`. */function extractRemoteRouting(oauth: McpServerOAuthDecl): RemoteClientRouting | null {const clientMode = oauth.clientMode@@ -224,7 +281,8 @@ function readRef(/*** Classify a remote client's secret source (DEC-18): refs present ⇒ K8s Secret* (pre-registered confidential); no refs + confidential ⇒ encrypted DCR store;- * no refs + public ⇒ no secret.+ * no refs + public ⇒ no secret. `public` with refs never reaches here:+ * {@link assertRemoteOAuthSpecCoherent} rejects it first.*/function resolveRemoteSecretSource(oauth: McpServerOAuthDecl,@@ -321,8 +379,10 @@ function normalizeScopes(scopes: unknown): string[] | undefined {* Resolve a McpServer's full OAuth subject (decl + grant routing) for the U5* consent flow. Returns null when the server carries no usable OAuth* 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).+ * closed. Throws {@link RemoteOAuthSpecIncoherentError} for a remote server whose+ * shape the runtime cannot honor (see {@link assertRemoteOAuthSpecCoherent}).+ * Same field-reading rule as {@link resolveServerOAuth} — kept here so the+ * authorize-URL minter and the callback never drift (D4).** Two lanes (C4/DEC-23), keyed uniformly by `oauth.id` (the install backfills it* for every remote mode, so the grant coordinate is uniform):@@ -349,6 +409,7 @@ export function resolveServerOAuthSubject(// ─── Remote lane (`source:'remote'`) ─────────────────────────────────────if (oauth.source === 'remote') {+ assertRemoteOAuthSpecCoherent(server)const remote = extractRemoteRouting(oauth)if (!remote) return nullconst secretSource = resolveRemoteSecretSource(oauth, remote.clientMode)diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.tsindex 7365883b0..1872093d3 100644--- a/control-api/src/routes/external/oauthCallback.ts+++ b/control-api/src/routes/external/oauthCallback.ts@@ -168,6 +168,10 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {return res.status(400).json({ error: 'server_missing_context' })case 'context_membership_denied':return res.status(403).json({ error: 'context_membership_denied' })+ case 'remote_oauth_spec_incoherent':+ return res+ .status(409)+ .json({ error: 'remote_oauth_spec_incoherent', reason: result.reason })case 'secret_missing':return res.status(503).json(integrationNotConfigured(oauthClientId, result.secret))case 'unsupported_provider':diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.tsindex c47816682..5ed8d33db 100644--- a/control-api/src/routes/internal/oauth.ts+++ b/control-api/src/routes/internal/oauth.ts@@ -19,6 +19,7 @@ import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'import { integrationNotConfigured, isSecretNotFound } from '../../oauth/integrationNotConfigured.js'import {type McpServerOAuthSpecInput,+ RemoteOAuthSpecIncoherentError,buildMcpServerGrantKey,resolveServerOAuth,resolveServerOAuthSubject,@@ -190,18 +191,29 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {}const authType = server?.spec?.auth?.type- const resolved = resolveServerOAuthSubject(server)- if (authType !== 'oauth' || !resolved) {+ let subject: ReturnType<typeof resolveServerOAuthSubject> = null+ let incoherent: RemoteOAuthSpecIncoherentError | undefined+ try {+ subject = resolveServerOAuthSubject(server)+ } catch (err) {+ if (!(err instanceof RemoteOAuthSpecIncoherentError)) throw err+ incoherent = err+ }+ // An incoherent remote server is refused only after the membership gate, so+ // a non-member learns nothing about its configuration; until then the gates+ // run on its grant coordinate, derived by the same rule.+ const coord = subject ?? (incoherent ? resolveServerOAuth(server) : null)+ if (authType !== 'oauth' || !coord) {return res.status(400).json({ error: 'not_oauth_server' })}// Context-identity servers: the AUTHORITATIVE Context is spec.contextRef.// A body contextId, if present, must match it (cross-context guard).- if (resolved.grantScope === 'context') {- if (!resolved.contextRef) {+ if (coord.grantScope === 'context') {+ if (!coord.contextRef) {return res.status(400).json({ error: 'server_missing_context' })}- if (typeof contextId === 'string' && contextId !== resolved.contextRef) {+ if (typeof contextId === 'string' && contextId !== coord.contextRef) {return res.status(400).json({ error: 'context_mismatch' })}}@@ -222,13 +234,16 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {// (D4). Deliberately NOT resolveInvocableMcpServersForContexts: that// applies U3's grant-presence gate, which filters out servers WITHOUT a// grant — exactly the ones connect exists to bootstrap (chicken-and-egg).- if (!resolved.contextRef) {+ if (!coord.contextRef) {return res.status(403).json({ error: 'context_membership_denied' })}const { contextIds } = await getUserContexts(userId)- if (!contextIds.includes(resolved.contextRef)) {+ if (!contextIds.includes(coord.contextRef)) {return res.status(403).json({ error: 'context_membership_denied' })}+ if (incoherent) throw incoherent+ const resolved = subject+ if (!resolved) return res.status(400).json({ error: 'not_oauth_server' })const oauthClientId = resolved.decl.id// Remote lane registers ONE stable redirect_uri (`/oauth-callback/remote`),@@ -297,6 +312,9 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {return res.status(500).json({ error: 'internal_error' })}} catch (err) {+ if (err instanceof RemoteOAuthSpecIncoherentError) {+ return res.status(409).json({ error: err.code, reason: err.reason })+ }next(err)}}diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex 985bcb5eb..f4d9b4653 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -15,6 +15,8 @@ import { deriveOAuthEncryptionKey } from '../oauth/encryption.js'import { integrationNotConfigured, isSecretNotFound } from '../oauth/integrationNotConfigured.js'import {type McpServerOAuthDecl,+ RemoteOAuthSpecIncoherentError,+ assertRemoteOAuthSpecCoherent,buildMcpServerGrantKey,readCrUid,resolveServerOAuth,@@ -469,6 +471,9 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {if (authType !== 'oauth' || !resolved) {return res.status(400).json({ error: 'not_oauth_server' })}+ // Checked up front, not only through the refresh reader: a still-fresh+ // access token is served without ever reading the owner declaration.+ assertRemoteOAuthSpecCoherent(server)// Bifurcate by grantScope read from the server. The KEY comes from the// shared derivation (`buildMcpServerGrantKey`, D4) so the mint, the@@ -565,6 +570,9 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {.json({ error: 'refresh_failed', status: result.status, detail: result.detail })}} catch (err) {+ if (err instanceof RemoteOAuthSpecIncoherentError) {+ return res.status(409).json({ error: err.code, reason: err.reason })+ }next(err)}}diff --git a/control-api/test/crd.mcpServerOauth.test.ts b/control-api/test/crd.mcpServerOauth.test.tsindex b649a44c2..f1d1da423 100644--- a/control-api/test/crd.mcpServerOauth.test.ts+++ b/control-api/test/crd.mcpServerOauth.test.ts@@ -425,7 +425,7 @@ describe('McpServer CRD — OAuth surface (U1)', () => {// evaluator is vendored, that limitation is R3-S8), NOT behavioral checks. Semantic// verification (half-ref rejected on create / ref repoint rejected on update) is// `kubectl --dry-run=server` against a live cluster, not here.- it('pairs remote client_id/secret refs both-or-neither (REMOTE-SECRET-PAIRING)', () => {+ it('pairs remote refs both-or-neither and forbids them on public (REMOTE-SECRET-PAIRING)', () => {const rule = specRules.find(r =>r.rule.includes("self.oauth.source != 'remote'") &&@@ -435,9 +435,28 @@ describe('McpServer CRD — OAuth surface (U1)', () => {Boolean(r.message?.includes('together or neither')))expect(rule, 'REMOTE-SECRET-PAIRING rule present').toBeDefined()- // both-or-neither ⇒ the rule must NOT tie refs to clientMode; requiring refs for- // confidential would break DCR-confidential (secret in the encrypted store, DEC-8).- expect(rule?.rule).not.toContain('clientMode')+ // RP-R4-CUI1-01: public carries no refs. clientMode is has()-guarded so a remote+ // object missing it (already rejected by REMOTE-REQ) cannot CEL-error here.+ expect(rule?.rule).toContain(+ "(!has(self.oauth.clientMode) || self.oauth.clientMode != 'public' || !has(self.oauth.clientIdRef))"+ )+ expect(rule?.message).toMatch(/neither when clientMode is public/)+ // Confidential stays legal WITH or WITHOUT refs: requiring refs for confidential+ // would break DCR-confidential (secret in the encrypted store, DEC-8).+ expect(rule?.rule).not.toContain("clientMode == 'confidential'")+ expect(rule?.rule).not.toContain("clientMode != 'confidential'")+ })++ it('pins remote bearerInBody to false in its own rule (REMOTE-BEARER-HEADER)', () => {+ const rule = specRules.find(r => r.rule.includes('self.oauth.bearerInBody == false'))+ expect(rule, 'REMOTE-BEARER-HEADER rule present').toBeDefined()+ expect(rule?.rule).toBe(+ "!has(self.oauth) || !has(self.oauth.source) || self.oauth.source != 'remote' || !has(self.oauth.bearerInBody) || self.oauth.bearerInBody == false"+ )+ expect(rule?.message).toMatch(/bearerInBody must be false/)+ // A distinct rule, not folded into REMOTE-REQ (which only pins presence).+ const remoteReq = specRules.find(r => r.message?.includes('remote spec.oauth requires'))+ expect(remoteReq?.rule).not.toContain('bearerInBody == false')})it('pins the remote secret posture (ref pair) as immutable across UPDATE (REMOTE-SECRET-IMM)', () => {@@ -479,6 +498,19 @@ describe('McpServer CRD — OAuth surface (U1)', () => {expect(rule?.rule).toContain("has(self.oauth.source) && self.oauth.source == 'remote'")})+ it("reserves oauth.id 'remote' for baked/generic, inside the slug conjunct (DA-3)", () => {+ const rule = specRules.find(r => r.rule.includes("self.oauth.id.matches('^[a-z0-9-]{1,63}$')"))+ expect(rule?.rule).toContain(+ "(self.oauth.id.matches('^[a-z0-9-]{1,63}$') && self.oauth.id != 'remote')"+ )+ // The remote carril stays exempt: its id is the AS-assigned client_id and its+ // callback segment is the reserved constant, not the id.+ expect(rule?.rule).toMatch(+ /^!has\(self\.oauth\) \|\| \(has\(self\.oauth\.source\) && self\.oauth\.source == 'remote'\) \|\|/+ )+ expect(rule?.message).toMatch(/must not be 'remote'/)+ })+it('re-gates REMOTE-REQ on source == remote so generic is not caught (REMOTE-REQ)', () => {// Anchor on the message: the positive `has(self.oauth.clientMode)` substring// also appears (negated) in BAKED-FORBID-REMOTE-FIELDS, so a rule-only matchdiff --git a/control-api/test/oauth.remoteSpecCoherence.test.ts b/control-api/test/oauth.remoteSpecCoherence.test.tsnew file mode 100644index 000000000..4b3a25e71--- /dev/null+++ b/control-api/test/oauth.remoteSpecCoherence.test.ts@@ -0,0 +1,327 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import request from 'supertest'+import { createApp } from '../src/app.js'+import { config } from '../src/config.js'+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'+import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'+import {+ type McpServerOAuthSpecInput,+ resolveServerOAuth,+ resolveServerOAuthSubject,+} from '../src/oauth/mcpServerOAuthSpec.js'+import { signOAuthState } from '../src/oauth/state.js'+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'+import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'+import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'+import {+ PILOTS,+ type PilotFixture,+ makeDiscoveryTransport,+} from './fixtures/remoteOAuthDiscovery.js'+import { MockGateway } from './mockGateway.js'++/**+ * Invariant 8 (R3-H8 / RP-R4-CUI1-01 / RP-R4-MED-01): a remote McpServer the CRD+ * now rejects — `public` with secret refs, or `bearerInBody: true` — can still+ * exist (written before the CRD was applied, or by a validation-bypassing write).+ * Consent, authorize-URL minting and token issuance must refuse it with the+ * specific `remote_oauth_spec_incoherent` error; revoke must keep working.+ *+ * T1: every CR is built by the real producers (`discoverRemoteOAuth` →+ * `buildRemoteOAuthSpec`). `bearerInBody: true` is what the builder emits for a+ * resource that only accepts the body, but the install route rejects it+ * (`400 bearer_in_body_unsupported`), so it only persists through a write that+ * bypasses the route (kubectl/GitOps). `public` + refs has NO producer at all: it+ * is the pre-registered-confidential output with `clientMode` flipped, i.e. the+ * in-place edit such a direct write would make.+ *+ * Errors are matched by `code`, not by class, so this file runs against the+ * parent sha (where the class does not exist) and fails there by assertion.+ */++const mockPoolQuery = vi.fn()+vi.mock('../src/db.js', () => ({+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },+}))+vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ backendAvailable: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))++const MCP_NS = config.mcpServersNamespace+const CONTEXT = 'ctx-9'+const PRE_REGISTERED_CLIENT_ID = 'client-abc'+const CIMD_SELF = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'+const RPC_PROXY_TOKEN = 'dev-rpc-proxy-token'+const ENCRYPTION_KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)++async function discover(pilot: PilotFixture): Promise<DiscoveryResult> {+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, {+ transport: makeDiscoveryTransport(pilot),+ resolveDns: async () => ['93.184.216.34'],+ })+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)+ return outcome.result+}++/** Sentry, but its protected resource only accepts the bearer in the body. */+function bodyOnlyPilot(): PilotFixture {+ const base = PILOTS.sentry+ const prm = { ...JSON.parse(base.prm.json), bearer_methods_supported: ['body'] }+ return { ...base, prm: { ...base.prm, json: JSON.stringify(prm) } }+}++let headerDiscovery: DiscoveryResult+let bodyDiscovery: DiscoveryResult++beforeAll(async () => {+ headerDiscovery = await discover(PILOTS.sentry)+ bodyDiscovery = await discover(bodyOnlyPilot())+})++function publicWithRefsOAuth(): Record<string, unknown> {+ const oauth = buildRemoteOAuthSpec(headerDiscovery, {+ clientMode: 'confidential',+ grantScope: 'user',+ clientSecretName: 'srv-oauth-client',+ preRegisteredClientId: PRE_REGISTERED_CLIENT_ID,+ }) as unknown as Record<string, unknown>+ return { ...oauth, clientMode: 'public' }+}++function bearerInBodyOAuth(): Record<string, unknown> {+ return buildRemoteOAuthSpec(bodyDiscovery, {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CIMD_SELF,+ }) as unknown as Record<string, unknown>+}++const INCOHERENT = [+ {+ label: 'public + secret refs',+ oauth: publicWithRefsOAuth,+ reason: 'public_client_with_secret_refs',+ },+ { label: 'bearerInBody: true', oauth: bearerInBodyOAuth, reason: 'bearer_in_body' },+] as const++function crFrom(+ name: string,+ oauth: Record<string, unknown>+): McpServerOAuthSpecInput & {+ metadata: { name: string }+ spec: Record<string, unknown>+} {+ return { metadata: { name }, spec: { contextRef: CONTEXT, auth: { type: 'oauth' }, oauth } }+}++function thrownBy(fn: () => unknown): { code?: unknown; reason?: unknown } | undefined {+ try {+ fn()+ } catch (err) {+ return err as { code?: unknown; reason?: unknown }+ }+ return undefined+}++describe('resolver mirror of the remote CRD coherence rules', () => {+ it('the bearer-in-body producer really emits bearerInBody: true', () => {+ expect(bearerInBodyOAuth().bearerInBody).toBe(true)+ })++ for (const c of INCOHERENT) {+ it(`${c.label}: resolveServerOAuthSubject throws remote_oauth_spec_incoherent`, () => {+ const err = thrownBy(() => resolveServerOAuthSubject(crFrom('srv', c.oauth())))+ expect(err?.code).toBe('remote_oauth_spec_incoherent')+ expect(err?.reason).toBe(c.reason)+ })++ it(`${c.label}: the refresh reader (normalizeMcpServerOwnerDecl) refuses it too`, () => {+ const err = thrownBy(() => normalizeMcpServerOwnerDecl(crFrom('srv', c.oauth()) as never))+ expect(err?.code).toBe('remote_oauth_spec_incoherent')+ })++ it(`${c.label}: resolveServerOAuth still yields the grant coordinate (revoke, sweep)`, () => {+ const r = resolveServerOAuth(crFrom('srv', c.oauth()))+ expect(r?.oauthClientId).toBe(c.oauth().id)+ expect(r?.grantScope).toBe('user')+ expect(r?.contextRef).toBe(CONTEXT)+ })+ }++ it('coherent remote shapes still resolve (pre-registered confidential, CIMD public)', () => {+ const preRegistered = buildRemoteOAuthSpec(headerDiscovery, {+ clientMode: 'confidential',+ grantScope: 'user',+ clientSecretName: 'srv-oauth-client',+ preRegisteredClientId: PRE_REGISTERED_CLIENT_ID,+ }) as unknown as Record<string, unknown>+ expect(resolveServerOAuthSubject(crFrom('a', preRegistered))?.decl.secretSource?.kind).toBe(+ 'k8s-secret'+ )+ const cimd = buildRemoteOAuthSpec(headerDiscovery, {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CIMD_SELF,+ }) as unknown as Record<string, unknown>+ expect(resolveServerOAuthSubject(crFrom('b', cimd))?.decl.secretSource?.kind).toBe('public')+ })+})++describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_incoherent', () => {+ let gateway: MockGateway+ let app: ReturnType<typeof createApp>+ const originalBrokerEnabled = config.mcpOauthBrokerEnabled++ beforeEach(() => {+ gateway = new MockGateway(MCP_NS)+ app = createApp(gateway as never)+ mockPoolQuery.mockReset()+ mockPoolQuery.mockImplementation((sql: unknown) => {+ const text = typeof sql === 'string' ? sql : ''+ if (text.includes('FROM user_contexts')) {+ return Promise.resolve({ rows: [{ context_id: CONTEXT }], rowCount: 1 })+ }+ if (text.includes('DELETE FROM oauth_grants')) {+ return Promise.resolve({ rows: [], rowCount: 1 })+ }+ return Promise.resolve({ rows: [], rowCount: 0 })+ })+ config.mcpOauthBrokerEnabled = true+ })++ afterEach(() => {+ config.mcpOauthBrokerEnabled = originalBrokerEnabled+ })++ async function seed(name: string, oauth: Record<string, unknown>): Promise<string> {+ const created = (await gateway.createResource('mcpservers', crFrom(name, oauth), MCP_NS)) as {+ metadata: { uid: string }+ }+ gateway.seedSecret('srv-oauth-client', MCP_NS, {+ data: {+ client_id: Buffer.from(PRE_REGISTERED_CLIENT_ID).toString('base64'),+ client_secret: Buffer.from('pre-registered-secret').toString('base64'),+ },+ })+ return created.metadata.uid+ }++ for (const c of INCOHERENT) {+ it(`${c.label}: POST /internal/mcp-oauth/authorize-url → 409, no URL minted`, async () => {+ await seed('srv', c.oauth())+ const res = await request(app)+ .post('/api/v1/internal/mcp-oauth/authorize-url')+ .set('Authorization', `Bearer ${RPC_PROXY_TOKEN}`)+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'srv', userId: 'user-1' })+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'remote_oauth_spec_incoherent', reason: c.reason })+ })++ it(`${c.label}: authorize-url for a non-member → 403, configuration not disclosed`, async () => {+ await seed('srv', c.oauth())+ mockPoolQuery.mockImplementation((sql: unknown) => {+ const text = typeof sql === 'string' ? sql : ''+ if (text.includes('FROM user_contexts')) {+ return Promise.resolve({ rows: [{ context_id: 'ctx-other' }], rowCount: 1 })+ }+ return Promise.resolve({ rows: [], rowCount: 0 })+ })+ const res = await request(app)+ .post('/api/v1/internal/mcp-oauth/authorize-url')+ .set('Authorization', `Bearer ${RPC_PROXY_TOKEN}`)+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'srv', userId: 'user-2' })+ expect(res.status).toBe(403)+ expect(res.body).toEqual({ error: 'context_membership_denied' })+ })++ it(`${c.label}: POST /mcp-oauth/user-token → 409 even with a fresh stored token`, async () => {+ const oauth = c.oauth()+ const uid = await seed('srv', oauth)+ mockPoolQuery.mockImplementation((sql: unknown) => {+ const text = typeof sql === 'string' ? sql : ''+ if (text.includes('FROM oauth_grants')) {+ return Promise.resolve({+ rows: [+ {+ owner_kind: 'mcpserver',+ recipe_namespace: MCP_NS,+ recipe_name: 'srv',+ user_id: 'user-1',+ context_id: null,+ bootstrapped_by_user_id: null,+ oauth_client_id: oauth.id,+ grant_kind: 'user',+ provider: 'remote',+ access_token_encrypted: encryptOAuthSecret(ENCRYPTION_KEY, 'LIVE-ACCESS'),+ refresh_token_encrypted: encryptOAuthSecret(ENCRYPTION_KEY, 'LIVE-REFRESH'),+ access_token_expires_at: new Date(Date.now() + 3600_000),+ updated_at: new Date(),+ background: false,+ cr_uid: uid,+ },+ ],+ rowCount: 1,+ })+ }+ return Promise.resolve({ rows: [], rowCount: 0 })+ })+ const token = issueMcpHostControlJwt('mcp-host', 'standalone', ['mcp-host/standalone'], {+ scopes: ['oauth:user-token'],+ }).token+ const res = await request(app)+ .post('/api/v1/mcp-oauth/user-token')+ .set('Authorization', `Bearer ${token}`)+ .send({ mcpServerName: 'srv', userId: 'user-1' })+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'remote_oauth_spec_incoherent', reason: c.reason })+ expect(JSON.stringify(res.body)).not.toContain('LIVE-ACCESS')+ })++ it(`${c.label}: GET /oauth-callback/remote → 409, nothing persisted`, async () => {+ const oauth = c.oauth()+ await seed('srv', oauth)+ const state = signOAuthState(config.oauthStateHmacSecret, {+ subjectKind: 'mcp',+ mcpServerName: 'srv',+ userId: 'user-1',+ oauthClientId: oauth.id,+ grantKind: 'user',+ background: false,+ } as Parameters<typeof signOAuthState>[1])+ const res = await request(app)+ .get('/api/v1/oauth-callback/remote')+ .query({ code: 'AUTH_CODE', state, iss: oauth.issForCallback })+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'remote_oauth_spec_incoherent', reason: c.reason })+ const grantWrites = mockPoolQuery.mock.calls.filter(+ ([sql]) =>+ typeof sql === 'string' && /INSERT INTO oauth_grants|UPDATE oauth_grants/.test(sql)+ )+ expect(grantWrites).toHaveLength(0)+ })++ it(`${c.label}: DELETE /internal/mcp-oauth/grant still revokes (204)`, async () => {+ await seed('srv', c.oauth())+ const res = await request(app)+ .delete('/api/v1/internal/mcp-oauth/grant')+ .set('Authorization', `Bearer ${RPC_PROXY_TOKEN}`)+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'srv', userId: 'user-1' })+ expect(res.status).toBe(204)+ const deletes = mockPoolQuery.mock.calls.filter(+ ([sql]) => typeof sql === 'string' && sql.includes('DELETE FROM oauth_grants')+ )+ expect(deletes).toHaveLength(1)+ })+ }+})diff --git a/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.tsindex b62692038..f1333b46b 100644--- a/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts+++ b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts@@ -31,7 +31,11 @@ import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'import { bootstrapSharedOAuthGrant, getOAuthGrant } from '../src/oauth/store.js'import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'import { runProactiveRefreshSweep } from '../src/services/oauthProactiveRefreshCron.js'-import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'+import {+ PILOTS,+ type PilotFixture,+ makeDiscoveryTransport,+} from './fixtures/remoteOAuthDiscovery.js'import { MockGateway } from './mockGateway.js'const VALIDATED_IP = '93.184.216.34'@@ -261,4 +265,98 @@ describeRealPostgres('proactive refresh sweep — installation identity (real Po)expect(rows).toEqual([{ has_rt: true, cr_uid: null }])})++ // Invariant 8: a remote CR the CRD now rejects (public + secret refs, or+ // bearerInBody: true) may still exist from a write that bypassed the install+ // route. The sweep must not spend its refresh token; the row counts as `error`.+ it('never POSTs the refresh of an incoherent remote server; the row counts as error', async () => {+ await dbPool.query('DELETE FROM oauth_grants')+ const gateway = new MockGateway(NS)+ const PRE_REGISTERED_ID = 'client-abc'++ // public + refs has no producer: the pre-registered-confidential output with+ // clientMode flipped, as an in-place edit would leave it. The Secret exists so+ // the only thing that can stop the POST is the coherence check.+ const preRegistered = buildRemoteOAuthSpec(discovery, {+ clientMode: 'confidential',+ grantScope: 'context',+ clientSecretName: 'srv-oauth-client',+ preRegisteredClientId: PRE_REGISTERED_ID,+ })+ gateway.seedSecret('srv-oauth-client', NS, {+ data: {+ client_id: Buffer.from(PRE_REGISTERED_ID).toString('base64'),+ client_secret: Buffer.from('pre-registered-secret').toString('base64'),+ },+ })++ // bearerInBody: true is what the real builder emits for a body-only resource;+ // the install route rejects it, so only a bypassing write can persist it.+ const bodyOnly: PilotFixture = {+ ...PILOTS.notion,+ prm: {+ ...PILOTS.notion.prm,+ json: JSON.stringify({+ ...JSON.parse(PILOTS.notion.prm.json),+ bearer_methods_supported: ['body'],+ }),+ },+ }+ const bodyOutcome = await discoverRemoteOAuth(bodyOnly.mcpUrl, {+ transport: makeDiscoveryTransport(bodyOnly),+ resolveDns: async () => [VALIDATED_IP],+ })+ if (!bodyOutcome.ok) throw new Error(`fixture discovery failed: ${bodyOutcome.error.kind}`)+ const bearerInBody = buildRemoteOAuthSpec(bodyOutcome.result, {+ clientMode: 'public',+ grantScope: 'context',+ cimdClientId: oauthId(),+ })+ expect(bearerInBody.bearerInBody).toBe(true)++ const cases = [+ { name: 'cron-pubrefs', oauth: { ...preRegistered, clientMode: 'public' as const } },+ { name: 'cron-bib', oauth: bearerInBody },+ ]+ for (const c of cases) {+ await gateway.createResource(+ 'mcpservers',+ {+ metadata: { name: c.name },+ spec: { contextRef: CONTEXT, auth: { type: 'oauth' }, oauth: c.oauth },+ },+ NS+ )+ const cr = (await gateway.getResource('mcpservers', c.name, NS)) as {+ metadata: { uid: string }+ }+ const { inserted } = await bootstrapSharedOAuthGrant(db, KEY, {+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: c.name,+ contextId: CONTEXT,+ oauthClientId: c.oauth.id as string,+ bootstrappedByUserId: 'user-1',+ provider: 'remote',+ accessToken: `AT-${c.name}`,+ refreshToken: `RT-${c.name}`,+ accessTokenExpiresInSec: IN_WINDOW_SEC,+ crUid: cr.metadata.uid,+ })+ expect(inserted).toBe(true)+ }++ tokenEndpoint.posts.length = 0+ const summary = await sweep(gateway)++ expect(summary.candidates).toBe(2)+ expect(summary.outcomes.error).toBe(2)+ expect(summary.outcomes.ok).toBe(0)+ expect(tokenEndpoint.posts).toHaveLength(0)+ const { rows } = await dbPool.query(+ `SELECT recipe_name FROM oauth_grants+ WHERE refresh_token_encrypted IS NOT NULL ORDER BY recipe_name`+ )+ expect(rows).toEqual([{ recipe_name: 'cron-bib' }, { recipe_name: 'cron-pubrefs' }])+ })})