Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-api): oauth broker base for mcp-servers (grants model, endpoint, crd)

Diego Zacariasa195b607a3df
diff --git a/charts/clerum-crds/crds/mcpserver.yaml b/charts/clerum-crds/crds/mcpserver.yaml
index af2fbfc4f..a2ae068ae 100644
--- a/charts/clerum-crds/crds/mcpserver.yaml
+++ b/charts/clerum-crds/crds/mcpserver.yaml
@@ -100,13 +100,111 @@ spec:
- bearer
- basic
- apiKey
- description: Authentication type.
+ - oauth
+ description: >-
+ Authentication type. `oauth` selects the control-api OAuth
+ broker (per-user or shared identity); it requires spec.oauth
+ and forbids a static secretRef/secretKey.
secretRef:
type: string
description: Name of the Kubernetes Secret containing auth credentials.
secretKey:
type: string
description: Key within the secret to use (default depends on auth type).
+ oauth:
+ type: object
+ description: >-
+ OAuth 2.1 broker configuration for this mcp-server. Present iff
+ spec.auth.type == 'oauth'. The control-api OAuth subsystem owns
+ the authorize/token/refresh flow; tokens are resolved per
+ connection just-in-time and NEVER mounted into the pod. Shape
+ mirrors WorkflowRecipe spec.oauthClients[] (a single client per
+ server).
+ required:
+ - id
+ - provider
+ - clientIdRef
+ - clientSecretRef
+ properties:
+ id:
+ type: string
+ maxLength: 63
+ pattern: "^[a-z0-9-]{1,63}$"
+ description: >-
+ Stable OAuth client identifier for this server. Surfaced as
+ the `clientId` on clerum:oauth URLs and the callback path
+ segment. Immutable once set.
+ provider:
+ type: string
+ # Known-shape adapters baked into control-api
+ # (src/oauth/providers.ts). Adding a provider is a control-api
+ # change — servers cannot speak OAuth to arbitrary endpoints.
+ # U2 extends: monday, clickup, vercel.
+ enum:
+ - salesforce
+ - slack
+ - notion
+ - microsoft-graph
+ - google
+ description: >-
+ Known-shape adapter. control-api owns the authorize/token
+ URLs and response-shape parsing per provider. Immutable.
+ clientIdRef:
+ type: object
+ required: [name, key]
+ description: >-
+ Reference to a Secret in the mcp-servers namespace holding
+ the OAuth client_id.
+ properties:
+ name:
+ type: string
+ maxLength: 253
+ key:
+ type: string
+ maxLength: 253
+ clientSecretRef:
+ type: object
+ required: [name, key]
+ description: >-
+ Reference to a Secret in the mcp-servers namespace holding
+ the OAuth client_secret.
+ properties:
+ name:
+ type: string
+ maxLength: 253
+ key:
+ type: string
+ maxLength: 253
+ scopes:
+ type: array
+ maxItems: 32
+ items:
+ type: string
+ maxLength: 128
+ description: >-
+ OAuth scopes to request. Provider-specific syntax. Include
+ the provider's offline/refresh scope when backgroundAccess
+ is true.
+ backgroundAccess:
+ type: boolean
+ description: >-
+ When true, this grant may be used by a workload without a
+ live human session (subject to the control-api background
+ gate). Requires scopes to include the provider's
+ offline/refresh scope.
+ grantScope:
+ type: string
+ enum:
+ - user
+ - context
+ default: user
+ description: >-
+ Whose OAuth identity is exercised. `user` (default): each
+ user authorizes their own grant, keyed by (server, user).
+ `context`: one shared identity per Context — a member
+ bootstraps it and the rest inherit it, keyed by
+ (server, context). Immutable once set: flipping it would
+ change in place which identity is exercised.
serverConfig:
type: object
description: Operational configuration for the MCP server runtime.
@@ -388,6 +486,25 @@ spec:
message: "spec.managed is immutable; delete and recreate the McpServer to change runtime ownership"
- rule: "!has(self.remote) || (has(self.egressBindings) && size(self.egressBindings) > 0)"
message: "Remote servers must declare at least one egressBinding for egress NetworkPolicy"
+ # OAuth coupling: auth.type=='oauth' iff spec.oauth is present.
+ # grantScope ⇒ oauth is structural (grantScope nests under oauth).
+ - rule: "((has(self.auth) && has(self.auth.type) && self.auth.type == 'oauth') == has(self.oauth))"
+ message: "spec.auth.type 'oauth' requires spec.oauth, and spec.oauth requires auth.type 'oauth'"
+ # OAuth servers must not also carry a static credential.
+ - rule: "!has(self.oauth) || !has(self.auth) || (!has(self.auth.secretRef) && !has(self.auth.secretKey))"
+ message: "OAuth mcp-servers must not declare a static auth.secretRef/secretKey"
+ # Immutability via has()-guard (patrón `managed`): these are
+ # transition rules (they reference oldSelf), so they are SKIPPED on
+ # CREATE and only enforced on UPDATE. Guarding on has(oldSelf.oauth)
+ # means create-time grantScope:'context' is allowed, and a
+ # none→oauth UPDATE is allowed, while any change to a grantScope /
+ # id / provider that ALREADY existed is rejected.
+ - rule: "!has(oldSelf.oauth) || !has(self.oauth) || oldSelf.oauth.grantScope == self.oauth.grantScope"
+ message: "spec.oauth.grantScope is immutable; delete and recreate the McpServer to change which identity is exercised"
+ - rule: "!has(oldSelf.oauth) || !has(self.oauth) || oldSelf.oauth.id == self.oauth.id"
+ message: "spec.oauth.id is immutable"
+ - rule: "!has(oldSelf.oauth) || !has(self.oauth) || oldSelf.oauth.provider == self.oauth.provider"
+ message: "spec.oauth.provider is immutable"
status:
type: object
properties:
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 49284f613..d052d9440 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index 62a5d275c..e2b561351 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.432",
+ "version": "0.1.433",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/app.ts b/control-api/src/app.ts
index c45a2c156..68928452b 100644
--- a/control-api/src/app.ts
+++ b/control-api/src/app.ts
@@ -30,6 +30,7 @@ import { createInternalUsageEventsRouter } from './routes/internal/usageEvents.j
import { createInternalWebhooksRouter } from './routes/internal/webhooks.js'
import { createInternalWorkflowApprovalReaderRouter } from './routes/internal/workflowApprovalReader.js'
import { createMcpHostRoutes } from './routes/mcp-host/index.js'
+import { createMcpOauthRouter } from './routes/mcpOauth.js'
import { createMetricsRouter } from './routes/metrics.js'
import { createRecipeOauthRouter } from './routes/recipeOauth.js'
import { createRegistryRouter } from './routes/registry.js'
@@ -197,6 +198,10 @@ export function createApp(gateway: K8sGateway) {
// token (Bearer, aud=oauth-broker). Auth is the broker token itself, not a
// Clerum cookie or service token, so it is mounted BEFORE requireInternalToken.
api.use(createRecipeOauthRouter(gateway))
+ // OAuth mcp-server broker (U1): POST /api/v1/mcp-oauth/user-token, gated by
+ // the mcp-host control JWT + scope oauth:user-token (self-authenticating, like
+ // the recipe broker — mounted before the internal-token gate below).
+ api.use(createMcpOauthRouter(gateway))
// Workflow trigger endpoints use control-ui JWT auth (admin users).
// Mounted BEFORE requireInternalToken — same pattern as mcpHost.
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index cd7a8f2a1..88638c4fd 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -5463,6 +5463,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0090_plugin_workload_sdk_runtime_contract_reconciliation',
apply: reconcilePluginWorkloadSdkRuntimeContracts,
},
+ {
+ version: '0091_oauth_grants_owner_generalization',
+ apply: applyOAuthGrantsOwnerGeneralization,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
@@ -5564,6 +5568,68 @@ async function applyOAuthServiceGrants(db: DbClient): Promise<void> {
`)
}
+async function applyOAuthGrantsOwnerGeneralization(db: DbClient): Promise<void> {
+ // U1 — generalize `oauth_grants` beyond recipe-owned grants so OAuth
+ // mcp-servers can own grants too, and introduce the `shared` (context-scoped)
+ // identity grant. NON-DESTRUCTIVE + idempotent: `recipe_namespace`/`recipe_name`
+ // are NOT renamed (they are reinterpreted as owner coordinates); the rename to
+ // `owner_*` is deferred.
+ //
+ // - `owner_kind` — discriminator; DEFAULT 'recipe' so every pre-existing row
+ // keeps its meaning and uniqueness.
+ // - `context_id` — replaces `user_id` in the key for `shared` grants (the
+ // Context the shared identity belongs to).
+ // - `bootstrapped_by_user_id` — audit: who first authorized a shared identity.
+ // OUTSIDE the key and never rewritten on refresh.
+ //
+ // The kind/user_id CHECK is REPLACED (not extended) to admit 'shared': without
+ // this, any `shared` INSERT would violate the old `user`/`service`-only CHECK.
+ await db.query(`
+ ALTER TABLE oauth_grants
+ ADD COLUMN IF NOT EXISTS owner_kind TEXT NOT NULL DEFAULT 'recipe';
+ ALTER TABLE oauth_grants
+ ADD COLUMN IF NOT EXISTS context_id TEXT;
+ ALTER TABLE oauth_grants
+ ADD COLUMN IF NOT EXISTS bootstrapped_by_user_id TEXT;
+
+ ALTER TABLE oauth_grants
+ DROP CONSTRAINT IF EXISTS oauth_grants_kind_userid_check;
+ DO $$ BEGIN
+ ALTER TABLE oauth_grants
+ ADD CONSTRAINT oauth_grants_kind_userid_check
+ CHECK ((grant_kind = 'user' AND user_id IS NOT NULL)
+ OR (grant_kind = 'service' AND user_id IS NULL)
+ OR (grant_kind = 'shared' AND user_id IS NULL
+ AND context_id IS NOT NULL
+ AND bootstrapped_by_user_id IS NOT NULL));
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ -- Recreate oauth_grants_unique as a superset with owner_kind. Existing rows
+ -- are owner_kind='recipe', so the recipe user-grant uniqueness is preserved;
+ -- a McpServer owner (owner_kind='mcpserver') with the same ns/name can now
+ -- coexist. Governs user grants (non-null user_id) across owner domains.
+ ALTER TABLE oauth_grants
+ DROP CONSTRAINT IF EXISTS oauth_grants_unique;
+ DO $$ BEGIN
+ ALTER TABLE oauth_grants
+ ADD CONSTRAINT oauth_grants_unique
+ UNIQUE (owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id);
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ -- Shared-identity uniqueness: exactly one shared grant per
+ -- (owner, ns, name, context, client). The user/service grants keep their own
+ -- uniqueness (superset constraint + oauth_grants_service_unique). The key
+ -- asymmetry is deliberate: user grants keep user_id (per-user, global across
+ -- contexts), shared grants replace it with context_id (identity scoped to the
+ -- Context, prevents cross-context leakage; sec 5.2/U6).
+ CREATE UNIQUE INDEX IF NOT EXISTS oauth_grants_shared_unique
+ ON oauth_grants (owner_kind, recipe_namespace, recipe_name, context_id, oauth_client_id)
+ WHERE grant_kind = 'shared';
+ `)
+}
+
async function ensureSchemaMigrationsTable(db: DbClient): Promise<void> {
await db.query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index 634978a9b..06b2a2b55 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -48,6 +48,20 @@ export interface RecipeReader {
read(name: string, namespace: string): Promise<RecipeWithOAuthClients | null>
}
+/**
+ * Structural alias of {@link RecipeReader} for the generalized owner model (U1).
+ *
+ * An owner declaration reader resolves a grant owner — a WorkflowRecipe, or an
+ * OAuth McpServer — to the same `{ spec: { oauthClients: [...] } }` shape the
+ * broker + refresh path already consume. The McpServer variant normalizes its
+ * single `spec.oauth` object into a one-element `oauthClients` array so the
+ * downstream code (`getAccessToken`) stays owner-agnostic. It is deliberately a
+ * plain alias (single method `read(name, namespace)`) so it can be injected
+ * per-router with a minimal blast radius — `tokenHelper.ts` and `state.ts` are
+ * untouched. (Generalizing `OAuthStateClaims` is U5, not here.)
+ */
+export type OwnerDeclReader = RecipeReader
+
export class SecretNotFoundError extends Error {}
export class RecipeNotFoundError extends Error {}
@@ -153,10 +167,7 @@ export async function handleOAuthCallback(
// ─── 3. Read clientId + clientSecret from K8s Secrets ─────────────────
let clientIdSecret: Record<string, string>
try {
- clientIdSecret = await deps.secretReader.read(
- clientDecl.clientIdRef.name,
- recipeNamespace
- )
+ clientIdSecret = await deps.secretReader.read(clientDecl.clientIdRef.name, recipeNamespace)
} catch (err) {
if (err instanceof SecretNotFoundError) {
return { kind: 'secret_missing', secret: clientDecl.clientIdRef.name }
diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.ts
index c53c1eff0..39e22036e 100644
--- a/control-api/src/oauth/store.ts
+++ b/control-api/src/oauth/store.ts
@@ -1,16 +1,37 @@
import type { DbClient } from '../db.js'
import { decryptOAuthSecret, encryptOAuthSecret } from './encryption.js'
+/**
+ * Owner domain of a grant. `recipe_namespace`/`recipe_name` are reinterpreted
+ * as the owner's coordinates:
+ * - `recipe` (default) — the historical WorkflowRecipe owner (recipe ns/name).
+ * - `mcpserver` — a McpServer owner (server ns/name); OAuth mcp-servers (U1).
+ *
+ * The column is called `owner_kind` and defaults to `'recipe'` so every row
+ * that predates the generalization keeps its meaning. Callers that omit
+ * `ownerKind` read/write the `'recipe'` domain — the recipe flows are unchanged.
+ */
+export type OAuthOwnerKind = 'recipe' | 'mcpserver'
+
/**
* Identifies one `oauth_grants` row.
*
- * - `user` grant — owned by a specific end-user (the embed Connect flow).
- * Keyed by `(recipeNamespace, recipeName, userId, oauthClientId)` and
- * governed by the `oauth_grants_unique` constraint.
+ * - `user` grant — owned by a specific end-user. Keyed by
+ * `(ownerKind, recipeNamespace, recipeName, userId, oauthClientId)` and
+ * governed by the `oauth_grants_unique` constraint. This is per-user identity:
+ * the recipe embed Connect flow, and OAuth mcp-servers with
+ * `grantScope='user'`.
* - `service` grant — owned by the recipe itself (the admin "connect for the
* recipe" flow, Path B). `user_id` is NULL; keyed by
* `(recipeNamespace, recipeName, oauthClientId)` and governed by the
* `oauth_grants_service_unique` partial index.
+ * - `shared` grant — one shared identity per `(server, context)` for an OAuth
+ * mcp-server with `grantScope='context'` (U1 data model; exercised by U6).
+ * `user_id` is NULL; `context_id` is the coordinate that replaces `user_id`
+ * in the key. Keyed by `(ownerKind, recipeNamespace, recipeName, contextId,
+ * oauthClientId)` and governed by the `oauth_grants_shared_unique` partial
+ * index. `bootstrapped_by_user_id` records who first authorized the shared
+ * identity — audit only, OUTSIDE the key and never touched on refresh.
*
* `grantKind` is required on every call so each site declares intent — there
* is no implicit default.
@@ -18,6 +39,8 @@ import { decryptOAuthSecret, encryptOAuthSecret } from './encryption.js'
export type OAuthGrantKey =
| {
grantKind: 'user'
+ /** Owner domain; omit for the historical recipe domain (defaults to `'recipe'`). */
+ ownerKind?: OAuthOwnerKind
recipeNamespace: string
recipeName: string
userId: string
@@ -25,20 +48,41 @@ export type OAuthGrantKey =
}
| {
grantKind: 'service'
+ /** Owner domain; omit for the historical recipe domain (defaults to `'recipe'`). */
+ ownerKind?: OAuthOwnerKind
+ recipeNamespace: string
+ recipeName: string
+ oauthClientId: string
+ }
+ | {
+ grantKind: 'shared'
+ /** Shared grants always belong to an mcp-server owner. */
+ ownerKind: 'mcpserver'
recipeNamespace: string
recipeName: string
+ contextId: string
oauthClientId: string
}
+/** Resolve the owner domain of a key, defaulting to the recipe domain. */
+export function resolveOwnerKind(input: { ownerKind?: OAuthOwnerKind }): OAuthOwnerKind {
+ return input.ownerKind ?? 'recipe'
+}
+
/**
* One row of `oauth_grants`. New grants of the same key replace the old.
*/
export interface OAuthGrantRow {
- grantKind: 'user' | 'service'
+ grantKind: 'user' | 'service' | 'shared'
+ ownerKind: OAuthOwnerKind
recipeNamespace: string
recipeName: string
- /** Present only for `user` grants; NULL/absent for `service` grants. */
+ /** Present only for `user` grants; NULL/absent for `service`/`shared` grants. */
userId?: string
+ /** Present only for `shared` grants; the Context the shared identity belongs to. */
+ contextId?: string
+ /** Present only for `shared` grants; who first authorized the shared identity (audit). */
+ bootstrappedByUserId?: string
oauthClientId: string
/** Provider-side identifier (salesforce, slack, ...) — denormalised for audit. */
provider: string
@@ -80,14 +124,16 @@ export async function upsertOAuthGrant(
? new Date(Date.now() + input.accessTokenExpiresInSec * 1000)
: null
+ const ownerKind = resolveOwnerKind(input)
+
if (input.grantKind === 'user') {
await db.query(
`INSERT INTO oauth_grants (
- recipe_namespace, recipe_name, user_id, oauth_client_id, grant_kind,
+ owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id, grant_kind,
provider, access_token_encrypted, refresh_token_encrypted,
access_token_expires_at, updated_at
- ) VALUES ($1, $2, $3, $4, 'user', $5, $6, $7, $8, NOW())
- ON CONFLICT (recipe_namespace, recipe_name, user_id, oauth_client_id)
+ ) VALUES ($1, $2, $3, $4, $5, 'user', $6, $7, $8, $9, NOW())
+ ON CONFLICT (owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id)
DO UPDATE SET
provider = EXCLUDED.provider,
access_token_encrypted = EXCLUDED.access_token_encrypted,
@@ -95,6 +141,7 @@ export async function upsertOAuthGrant(
access_token_expires_at = EXCLUDED.access_token_expires_at,
updated_at = NOW()`,
[
+ ownerKind,
input.recipeNamespace,
input.recipeName,
input.userId,
@@ -108,12 +155,44 @@ export async function upsertOAuthGrant(
return
}
+ if (input.grantKind === 'shared') {
+ // Refresh path ONLY. A shared grant is bootstrapped once via
+ // `bootstrapSharedOAuthGrant` (INSERT … ON CONFLICT DO NOTHING, first-wins
+ // tokens AND bootstrapper). Token refresh is a plain UPDATE by key so it
+ // never rewrites the team identity or the `bootstrapped_by_user_id` audit
+ // column (mini-spec 05 §3: conflating the two would let "the last bootstrap
+ // silently steal the identity"). The row is guaranteed to exist here because
+ // refresh only runs after a successful `getOAuthGrant`.
+ await db.query(
+ `UPDATE oauth_grants
+ SET provider = $6,
+ access_token_encrypted = $7,
+ refresh_token_encrypted = $8,
+ access_token_expires_at = $9,
+ updated_at = NOW()
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND context_id = $4 AND oauth_client_id = $5 AND grant_kind = 'shared'`,
+ [
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.contextId,
+ input.oauthClientId,
+ input.provider,
+ accessTokenEncrypted,
+ refreshTokenEncrypted,
+ accessTokenExpiresAt,
+ ]
+ )
+ return
+ }
+
await db.query(
`INSERT INTO oauth_grants (
- recipe_namespace, recipe_name, user_id, oauth_client_id, grant_kind,
+ owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id, grant_kind,
provider, access_token_encrypted, refresh_token_encrypted,
access_token_expires_at, updated_at
- ) VALUES ($1, $2, NULL, $3, 'service', $4, $5, $6, $7, NOW())
+ ) VALUES ($1, $2, $3, NULL, $4, 'service', $5, $6, $7, $8, NOW())
ON CONFLICT (recipe_namespace, recipe_name, oauth_client_id) WHERE grant_kind = 'service'
DO UPDATE SET
provider = EXCLUDED.provider,
@@ -122,15 +201,87 @@ export async function upsertOAuthGrant(
access_token_expires_at = EXCLUDED.access_token_expires_at,
updated_at = NOW()`,
[
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.oauthClientId,
+ input.provider,
+ accessTokenEncrypted,
+ refreshTokenEncrypted,
+ accessTokenExpiresAt,
+ ]
+ )
+}
+
+/**
+ * Bootstrap a `shared` (context-identity) grant: the FIRST member to authorize
+ * an OAuth mcp-server with `grantScope='context'` lends their provider identity
+ * to the whole Context.
+ *
+ * INSERT … ON CONFLICT DO NOTHING — first-wins tokens AND bootstrapper. If a
+ * concurrent second member also completes consent (both minted an authorize URL
+ * inside the state TTL), their row is a no-op: they inherit the team's grant,
+ * and `bootstrapped_by_user_id` keeps pointing at whoever landed first
+ * (mini-spec 05 §3). Distinct from the refresh path (`upsertOAuthGrant` above)
+ * on purpose: conflating them would let the last completer silently overwrite
+ * the team identity and the audit trail.
+ *
+ * Returns `{ inserted }` so the caller can tell "you bootstrapped the team" from
+ * "you joined an existing team identity".
+ */
+export type BootstrapSharedOAuthGrantInput = {
+ ownerKind: 'mcpserver'
+ recipeNamespace: string
+ recipeName: string
+ contextId: string
+ oauthClientId: string
+ /** Who authorized the shared identity (audit; from signed state claims, never a body param). */
+ bootstrappedByUserId: string
+ provider: string
+ accessToken: string
+ refreshToken?: string
+ accessTokenExpiresInSec?: number
+}
+
+export async function bootstrapSharedOAuthGrant(
+ db: DbClient,
+ encryptionKey: Buffer,
+ input: BootstrapSharedOAuthGrantInput
+): Promise<{ inserted: boolean }> {
+ const accessTokenEncrypted = encryptOAuthSecret(encryptionKey, input.accessToken)
+ const refreshTokenEncrypted = input.refreshToken
+ ? encryptOAuthSecret(encryptionKey, input.refreshToken)
+ : null
+ const accessTokenExpiresAt =
+ typeof input.accessTokenExpiresInSec === 'number'
+ ? new Date(Date.now() + input.accessTokenExpiresInSec * 1000)
+ : null
+
+ const result = await db.query(
+ `INSERT INTO oauth_grants (
+ owner_kind, recipe_namespace, recipe_name, user_id, context_id,
+ oauth_client_id, grant_kind, bootstrapped_by_user_id,
+ provider, access_token_encrypted, refresh_token_encrypted,
+ access_token_expires_at, updated_at
+ ) VALUES ($1, $2, $3, NULL, $4, $5, 'shared', $6, $7, $8, $9, $10, NOW())
+ ON CONFLICT (owner_kind, recipe_namespace, recipe_name, context_id, oauth_client_id)
+ WHERE grant_kind = 'shared'
+ DO NOTHING
+ RETURNING id`,
+ [
+ input.ownerKind,
input.recipeNamespace,
input.recipeName,
+ input.contextId,
input.oauthClientId,
+ input.bootstrappedByUserId,
input.provider,
accessTokenEncrypted,
refreshTokenEncrypted,
accessTokenExpiresAt,
]
)
+ return { inserted: (result.rowCount ?? 0) > 0 }
}
export type GetOAuthGrantInput = OAuthGrantKey & {
@@ -138,16 +289,20 @@ export type GetOAuthGrantInput = OAuthGrantKey & {
requireBackground?: boolean
}
-const SELECT_COLUMNS = `recipe_namespace, recipe_name, user_id, oauth_client_id, grant_kind,
+const SELECT_COLUMNS = `owner_kind, recipe_namespace, recipe_name, user_id, context_id,
+ bootstrapped_by_user_id, oauth_client_id, grant_kind,
provider, access_token_encrypted, refresh_token_encrypted,
access_token_expires_at, updated_at, background`
interface OAuthGrantDbRow {
+ owner_kind: OAuthOwnerKind
recipe_namespace: string
recipe_name: string
user_id: string | null
+ context_id: string | null
+ bootstrapped_by_user_id: string | null
oauth_client_id: string
- grant_kind: 'user' | 'service'
+ grant_kind: 'user' | 'service' | 'shared'
provider: string
access_token_encrypted: string
refresh_token_encrypted: string | null
@@ -164,31 +319,50 @@ export async function getOAuthGrant(
encryptionKey: Buffer,
input: GetOAuthGrantInput
): Promise<OAuthGrantRow | null> {
+ const ownerKind = resolveOwnerKind(input)
const result =
input.grantKind === 'user'
? await db.query(
`SELECT ${SELECT_COLUMNS}
FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2
- AND user_id = $3 AND oauth_client_id = $4 AND grant_kind = 'user'${
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id = $4 AND oauth_client_id = $5 AND grant_kind = 'user'${
input.requireBackground ? ' AND background = true' : ''
}`,
- [input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
- )
- : await db.query(
- `SELECT ${SELECT_COLUMNS}
- FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2
- AND user_id IS NULL AND oauth_client_id = $3 AND grant_kind = 'service'`,
- [input.recipeNamespace, input.recipeName, input.oauthClientId]
+ [ownerKind, input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
)
+ : input.grantKind === 'shared'
+ ? await db.query(
+ `SELECT ${SELECT_COLUMNS}
+ FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND context_id = $4 AND oauth_client_id = $5
+ AND grant_kind = 'shared'${input.requireBackground ? ' AND background = true' : ''}`,
+ [
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.contextId,
+ input.oauthClientId,
+ ]
+ )
+ : await db.query(
+ `SELECT ${SELECT_COLUMNS}
+ FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'`,
+ [ownerKind, input.recipeNamespace, input.recipeName, input.oauthClientId]
+ )
if (result.rows.length === 0) return null
const row = result.rows[0] as OAuthGrantDbRow
return {
grantKind: row.grant_kind,
+ ownerKind: row.owner_kind,
recipeNamespace: row.recipe_namespace,
recipeName: row.recipe_name,
userId: row.user_id ?? undefined,
+ contextId: row.context_id ?? undefined,
+ bootstrappedByUserId: row.bootstrapped_by_user_id ?? undefined,
oauthClientId: row.oauth_client_id,
provider: row.provider,
accessToken: decryptOAuthSecret(encryptionKey, row.access_token_encrypted),
@@ -206,42 +380,68 @@ export async function getOAuthGrant(
* need to know whether a grant is connected.
*/
export async function oauthGrantExists(db: DbClient, input: GetOAuthGrantInput): Promise<boolean> {
+ const ownerKind = resolveOwnerKind(input)
const result =
input.grantKind === 'user'
? await db.query(
`SELECT 1 FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2
- AND user_id = $3 AND oauth_client_id = $4 AND grant_kind = 'user'${
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id = $4 AND oauth_client_id = $5 AND grant_kind = 'user'${
input.requireBackground ? ' AND background = true' : ''
}
LIMIT 1`,
- [input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
- )
- : await db.query(
- `SELECT 1 FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2
- AND user_id IS NULL AND oauth_client_id = $3 AND grant_kind = 'service'
- LIMIT 1`,
- [input.recipeNamespace, input.recipeName, input.oauthClientId]
+ [ownerKind, input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
)
+ : input.grantKind === 'shared'
+ ? await db.query(
+ `SELECT 1 FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND context_id = $4 AND oauth_client_id = $5
+ AND grant_kind = 'shared'${input.requireBackground ? ' AND background = true' : ''}
+ LIMIT 1`,
+ [
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.contextId,
+ input.oauthClientId,
+ ]
+ )
+ : await db.query(
+ `SELECT 1 FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'
+ LIMIT 1`,
+ [ownerKind, input.recipeNamespace, input.recipeName, input.oauthClientId]
+ )
return result.rows.length > 0
}
export async function deleteOAuthGrant(db: DbClient, input: GetOAuthGrantInput): Promise<void> {
+ const ownerKind = resolveOwnerKind(input)
if (input.grantKind === 'user') {
await db.query(
`DELETE FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2
- AND user_id = $3 AND oauth_client_id = $4 AND grant_kind = 'user'`,
- [input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id = $4 AND oauth_client_id = $5 AND grant_kind = 'user'`,
+ [ownerKind, input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
+ )
+ return
+ }
+ if (input.grantKind === 'shared') {
+ await db.query(
+ `DELETE FROM oauth_grants
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND context_id = $4 AND oauth_client_id = $5 AND grant_kind = 'shared'`,
+ [ownerKind, input.recipeNamespace, input.recipeName, input.contextId, input.oauthClientId]
)
return
}
await db.query(
`DELETE FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2
- AND user_id IS NULL AND oauth_client_id = $3 AND grant_kind = 'service'`,
- [input.recipeNamespace, input.recipeName, input.oauthClientId]
+ WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
+ AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'`,
+ [ownerKind, input.recipeNamespace, input.recipeName, input.oauthClientId]
)
}
@@ -254,9 +454,12 @@ export async function setUserGrantBackground(
key: { recipeNamespace: string; recipeName: string; userId: string; oauthClientId: string },
background: boolean
): Promise<void> {
+ // Recipe-domain user grants only (Profile UI "background consent"). OAuth
+ // mcp-server grants live under owner_kind='mcpserver'; their background
+ // handling, if any, is future work — keep this scoped so the two never mix.
await db.query(
`UPDATE oauth_grants SET background = $5, updated_at = NOW()
- WHERE recipe_namespace = $1 AND recipe_name = $2
+ WHERE owner_kind = 'recipe' AND recipe_namespace = $1 AND recipe_name = $2
AND user_id = $3 AND oauth_client_id = $4 AND grant_kind = 'user'`,
[key.recipeNamespace, key.recipeName, key.userId, key.oauthClientId, background]
)
@@ -272,11 +475,14 @@ export interface UserGrantSummary {
}
/** All of a user's grants across recipes (for the Profile UI "Connected accounts" list). */
-export async function listUserOAuthGrants(db: DbClient, userId: string): Promise<UserGrantSummary[]> {
+export async function listUserOAuthGrants(
+ db: DbClient,
+ userId: string
+): Promise<UserGrantSummary[]> {
const result = await db.query(
`SELECT recipe_namespace, recipe_name, oauth_client_id, provider, background, updated_at
FROM oauth_grants
- WHERE user_id = $1 AND grant_kind = 'user'
+ WHERE owner_kind = 'recipe' AND user_id = $1 AND grant_kind = 'user'
ORDER BY recipe_name, oauth_client_id`,
[userId]
)
@@ -308,7 +514,8 @@ export async function listUserGrantsForClient(
const result = await db.query(
`SELECT user_id, background, updated_at
FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2 AND oauth_client_id = $3 AND grant_kind = 'user'
+ WHERE owner_kind = 'recipe' AND recipe_namespace = $1 AND recipe_name = $2
+ AND oauth_client_id = $3 AND grant_kind = 'user'
ORDER BY user_id`,
[key.recipeNamespace, key.recipeName, key.oauthClientId]
)
@@ -328,8 +535,8 @@ export async function listBackgroundUserGrants(
): Promise<string[]> {
const result = await db.query(
`SELECT user_id FROM oauth_grants
- WHERE recipe_namespace = $1 AND recipe_name = $2 AND oauth_client_id = $3
- AND grant_kind = 'user' AND background = true
+ WHERE owner_kind = 'recipe' AND recipe_namespace = $1 AND recipe_name = $2
+ AND oauth_client_id = $3 AND grant_kind = 'user' AND background = true
ORDER BY user_id`,
[key.recipeNamespace, key.recipeName, key.oauthClientId]
)
diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.ts
index 798946f66..e5d286348 100644
--- a/control-api/src/oauth/tokenHelper.ts
+++ b/control-api/src/oauth/tokenHelper.ts
@@ -24,7 +24,12 @@ import { type OAuthGrantKey, getOAuthGrant, upsertOAuthGrant } from './store.js'
*/
export type GetAccessTokenInput = OAuthGrantKey & {
- /** User grants only: require a background-consented grant (per-user broker, SEC-5). */
+ /**
+ * Require a background-consented grant (per-user broker, SEC-5). Parametrized,
+ * NOT pinned to `true`: the recipe background broker passes `true`; the
+ * interactive mcp-host live-session path (U1) passes `false` (there IS a live
+ * session). Honored for `user` and `shared` grants; ignored for `service`.
+ */
requireBackground?: boolean
}
@@ -148,8 +153,12 @@ export async function getAccessToken(
}
// Some providers omit refresh_token on refresh — keep the previous one.
- // Spread `...input` so the grant key (grantKind + identifiers) is carried
- // through verbatim — the refresh re-upserts the same row, user or service.
+ // Spread `...input` so the grant key (grantKind + owner/identifiers) is carried
+ // through verbatim — the refresh re-upserts the SAME row. For `user`/`service`
+ // this is ON CONFLICT DO UPDATE (identity columns excluded); for `shared` it
+ // is a plain UPDATE by key (see store.ts) that never rewrites
+ // `bootstrapped_by_user_id` or the shared identity. Columns outside the key
+ // are preserved either way.
await upsertOAuthGrant(deps.db, deps.encryptionKey, {
...input,
provider: decl.provider,
diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.ts
new file mode 100644
index 000000000..c241fd8d8
--- /dev/null
+++ b/control-api/src/routes/mcpOauth.ts
@@ -0,0 +1,362 @@
+import { type NextFunction, type Request, type Response, Router } from 'express'
+import { config } from '../config.js'
+import { pool } from '../db.js'
+import { K8sGateway } from '../k8s.js'
+import { rateLimitMiddleware } from '../middleware/rateLimitMiddleware.js'
+import {
+ type OwnerDeclReader,
+ RecipeNotFoundError,
+ type RecipeWithOAuthClients,
+ SecretNotFoundError,
+ type SecretReader,
+} from '../oauth/callback.js'
+import { deriveOAuthEncryptionKey } from '../oauth/encryption.js'
+import { integrationNotConfigured, isSecretNotFound } from '../oauth/integrationNotConfigured.js'
+import type { OAuthGrantKey } from '../oauth/store.js'
+import { getAccessToken } from '../oauth/tokenHelper.js'
+import { K8sNotFoundError } from '../services/resourceService.js'
+import {
+ type McpHostControlClaims,
+ verifyMcpHostControlJwt,
+} from '../utils/auth/mcpHostJwtToken.js'
+import { extractBearerToken } from '../utils/extractBearerToken.js'
+
+/**
+ * OAuth mcp-server broker route (U1, spec §U1).
+ *
+ * `POST /api/v1/mcp-oauth/user-token` — mcp-host exchanges its EXISTING
+ * control JWT (host-bound, `typ:'service'`, RS256, rotated with the runtime
+ * Secret) for a fresh per-connection provider access token, so the LLM can call
+ * an OAuth mcp-server tool with `Authorization: Bearer <token>`. Refresh tokens
+ * and the encryption key never leave control-api (invariant §1.1.2).
+ *
+ * Gate: the control JWT + scope `oauth:user-token`. No new static credential
+ * and no new broker-token minting infra (the híbrido design, §U1).
+ *
+ * Identity provenance:
+ * - `oauthClientId` is derived from the McpServer's `spec.oauth.id`, NEVER
+ * from the request body.
+ * - `userId` / `contextId` ride the request body. This is the accepted pattern
+ * of the mutually-authenticated mcp-host ↔ control-api seam (same as
+ * `routes/internal/oauth.ts`): the caller is authenticated by its control
+ * JWT and asserts, over that trusted channel, which end-user session /
+ * Context pod the token is for. control-api authorizes the grant against the
+ * forwarded `userId`/`contextId` (defense in depth — a wrong value simply
+ * resolves to `no_grant`). It is therefore INCORRECT to say "userId is never
+ * a body param" here.
+ *
+ * Flavor dispatch — read from the server's `spec.oauth.grantScope`:
+ * - `user` → grant key `(server, userId)` — per-user identity.
+ * - `context` → grant key `(server, contextId)` — shared identity.
+ * Both branches ship in v1; the `context` branch is governed/exercised by U6.
+ */
+
+interface McpServerOAuthDecl {
+ id?: unknown
+ provider?: unknown
+ clientIdRef?: { name?: unknown; key?: unknown }
+ clientSecretRef?: { name?: unknown; key?: unknown }
+ scopes?: unknown
+ backgroundAccess?: unknown
+ grantScope?: unknown
+}
+
+interface McpServerResource {
+ metadata?: { name?: string; namespace?: string }
+ spec?: {
+ auth?: { type?: unknown }
+ oauth?: McpServerOAuthDecl
+ // `spec.contextRef` is REQUIRED + singular on the CRD ("the context this
+ // server belongs to", mcpserver.yaml). It is the AUTHORITATIVE Context of a
+ // context-identity server — the shared grant coordinate — never the body.
+ contextRef?: unknown
+ }
+}
+
+type GrantScope = 'user' | 'context'
+
+interface ResolvedServerOAuth {
+ oauthClientId: string
+ grantScope: GrantScope
+ /** Authoritative Context of the server (spec.contextRef); undefined if absent. */
+ contextRef?: string
+}
+
+/**
+ * Normalize a McpServer's single `spec.oauth` object into the
+ * `{ spec: { oauthClients: [decl] } }` shape the owner-agnostic broker +
+ * 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 {
+ const oauth = server.spec?.oauth
+ if (!oauth || typeof oauth.id !== 'string' || typeof oauth.provider !== 'string') return null
+ const 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'
+ ) {
+ return null
+ }
+ return {
+ metadata: server.metadata,
+ spec: {
+ oauthClients: [
+ {
+ id: oauth.id,
+ provider: oauth.provider,
+ clientIdRef: { name: clientIdRef.name, key: clientIdRef.key },
+ clientSecretRef: { name: clientSecretRef.name, key: clientSecretRef.key },
+ scopes: Array.isArray(oauth.scopes)
+ ? oauth.scopes.filter((s): s is string => typeof s === 'string')
+ : undefined,
+ backgroundAccess: oauth.backgroundAccess === true,
+ },
+ ],
+ },
+ }
+}
+
+function resolveServerOAuth(server: McpServerResource): ResolvedServerOAuth | null {
+ const oauth = server.spec?.oauth
+ if (!oauth || typeof oauth.id !== 'string' || oauth.id.length === 0) return null
+ const grantScope: GrantScope = oauth.grantScope === 'context' ? 'context' : 'user'
+ const contextRef =
+ typeof server.spec?.contextRef === 'string' && server.spec.contextRef.length > 0
+ ? server.spec.contextRef
+ : undefined
+ return { oauthClientId: oauth.id, grantScope, contextRef }
+}
+
+// DNS-1123 subdomain, the shape a k8s resource name takes. Reject anything else
+// up front so a malformed `mcpServerName` (e.g. "Foo/Bar") becomes a 400 rather
+// than surfacing a non-404 apiserver error as a 500.
+const K8S_NAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/
+function isValidK8sName(name: string): boolean {
+ return name.length > 0 && name.length <= 253 && K8S_NAME_RE.test(name)
+}
+
+export function createMcpOauthRouter(gateway: K8sGateway): Router {
+ const router = Router()
+ const encryptionKey = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+
+ // OwnerDeclReader for McpServers: reads the CR from the mcp-servers namespace
+ // and normalizes `spec.oauth` → oauthClients shape. Used by getAccessToken on
+ // the refresh path so it stays owner-agnostic.
+ const ownerDeclReader: OwnerDeclReader = {
+ async read(name): Promise<RecipeWithOAuthClients | null> {
+ try {
+ const server = (await gateway.getResource(
+ 'mcpservers',
+ name,
+ config.mcpServersNamespace
+ )) as McpServerResource
+ return normalizeMcpServerOwnerDecl(server)
+ } catch (err) {
+ if (err instanceof K8sNotFoundError) {
+ throw new RecipeNotFoundError(`mcpserver ${config.mcpServersNamespace}/${name} not found`)
+ }
+ throw err
+ }
+ },
+ }
+
+ // Secrets (client_id / client_secret) live in the mcp-servers namespace, NOT
+ // the sandbox-recipes namespace.
+ const secretReader: SecretReader = {
+ async read(name, namespace): Promise<Record<string, string>> {
+ try {
+ const raw = (await gateway.getSecret(name, namespace)) as { data?: Record<string, string> }
+ const decoded: Record<string, string> = {}
+ for (const [k, v] of Object.entries(raw.data ?? {})) {
+ decoded[k] = Buffer.from(v, 'base64').toString('utf8')
+ }
+ return decoded
+ } catch (err) {
+ if (isSecretNotFound(err)) {
+ throw new SecretNotFoundError(`secret ${namespace}/${name} not found`)
+ }
+ throw err
+ }
+ },
+ }
+
+ // Verify the mcp-host control JWT and stash the claims so the rate limiter can
+ // key off the caller before the handler runs.
+ function requireControlCaller(req: Request, res: Response, next: NextFunction): void {
+ const bearer = extractBearerToken(req)
+ if (!bearer || bearer.length > 4096) {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
+ const claims = verifyMcpHostControlJwt(bearer)
+ if (!claims) {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
+ res.locals.mcpHostControl = claims
+ next()
+ }
+
+ router.post(
+ '/mcp-oauth/user-token',
+ requireControlCaller,
+ rateLimitMiddleware({
+ bucketType: 'mcp_oauth_broker',
+ maxPerMinute: config.oauthBrokerRlPerMin,
+ getBucketKey: req => {
+ const claims = req.res?.locals?.mcpHostControl as McpHostControlClaims | undefined
+ return claims ? `mcp-oauth:${claims.sub}` : 'mcp-oauth:unknown'
+ },
+ }),
+ async (req, res, next) => {
+ const claims = res.locals.mcpHostControl as McpHostControlClaims | undefined
+ // Scope gate: the control JWT must carry `oauth:user-token`.
+ if (!claims || !claims.scopes.includes('oauth:user-token')) {
+ return res.status(403).json({ error: 'insufficient_scope' })
+ }
+
+ try {
+ const body = (req.body ?? {}) as {
+ mcpServerName?: unknown
+ userId?: unknown
+ contextId?: unknown
+ }
+ const mcpServerName = body.mcpServerName
+ const userId = body.userId
+ const contextId = body.contextId
+ if (typeof mcpServerName !== 'string' || !isValidK8sName(mcpServerName)) {
+ return res.status(400).json({ error: 'invalid_request' })
+ }
+
+ // Read the McpServer to derive `oauthClientId` + `grantScope` from the
+ // server's declaration — never from the body.
+ let server: McpServerResource | null
+ try {
+ server = (await gateway.getResource(
+ 'mcpservers',
+ mcpServerName,
+ config.mcpServersNamespace
+ )) as McpServerResource
+ } catch (err) {
+ if (err instanceof K8sNotFoundError) {
+ return res.status(404).json({ error: 'server_not_found' })
+ }
+ throw err
+ }
+
+ const authType = server?.spec?.auth?.type
+ const resolved = resolveServerOAuth(server)
+ if (authType !== 'oauth' || !resolved) {
+ return res.status(400).json({ error: 'not_oauth_server' })
+ }
+
+ // Bifurcate by grantScope read from the server.
+ let key: OAuthGrantKey
+ if (resolved.grantScope === 'context') {
+ // AUTHORITATIVE Context = server.spec.contextRef, NEVER the body.
+ // Trusting a body contextId would let a caller with the scope request
+ // {server, contextId: <someone else's Context>} and receive that
+ // Context's shared token (cross-context token theft). The body value,
+ // if present, is only cross-checked against the authoritative one.
+ const authoritativeContextId = resolved.contextRef
+ if (!authoritativeContextId) {
+ // A context-identity server MUST carry contextRef (CRD-required).
+ // Fail closed if it somehow doesn't.
+ return res.status(400).json({ error: 'server_missing_context' })
+ }
+ if (typeof contextId === 'string' && contextId !== authoritativeContextId) {
+ return res.status(400).json({ error: 'context_mismatch' })
+ }
+ key = {
+ grantKind: 'shared',
+ ownerKind: 'mcpserver',
+ recipeNamespace: config.mcpServersNamespace,
+ recipeName: mcpServerName,
+ contextId: authoritativeContextId,
+ oauthClientId: resolved.oauthClientId,
+ }
+ } else {
+ if (typeof userId !== 'string' || userId.length === 0) {
+ return res.status(400).json({ error: 'invalid_request' })
+ }
+ key = {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: config.mcpServersNamespace,
+ recipeName: mcpServerName,
+ userId,
+ oauthClientId: resolved.oauthClientId,
+ }
+ }
+
+ // Interactive live-session path — a human session is present, so
+ // background consent is NOT required here (requireBackground: false).
+ const result = await getAccessToken(
+ { ...key, requireBackground: false },
+ {
+ db: { query: (text, values) => pool.query(text, values) },
+ recipeReader: ownerDeclReader,
+ secretReader,
+ fetchFn: (input, init) => fetch(input, init),
+ encryptionKey,
+ }
+ )
+
+ const audit = (outcome: string) =>
+ req.log?.info(
+ {
+ event: 'mcp_oauth_user_token_issued',
+ mcpServerName,
+ grantScope: resolved.grantScope,
+ oauthClientId: resolved.oauthClientId,
+ outcome,
+ },
+ 'mcp oauth user token issued'
+ )
+
+ switch (result.kind) {
+ case 'ok':
+ audit('ok')
+ return res.status(200).json({
+ token: result.accessToken,
+ expiresAt: result.expiresAt?.toISOString() ?? null,
+ })
+ case 'no_grant':
+ audit('no_grant')
+ return res.status(404).json({ error: 'no_grant' })
+ case 'recipe_not_found':
+ audit('server_not_found')
+ return res.status(404).json({ error: 'server_not_found' })
+ case 'unknown_oauth_client':
+ audit('unknown_oauth_client')
+ return res.status(400).json({ error: 'unknown_oauth_client' })
+ case 'unsupported_provider':
+ audit('unsupported_provider')
+ return res
+ .status(400)
+ .json({ error: 'unsupported_provider', provider: result.provider })
+ case 'secret_missing':
+ audit('integration_not_configured')
+ return res
+ .status(503)
+ .json(integrationNotConfigured(resolved.oauthClientId, result.secret))
+ case 'refresh_failed':
+ audit('refresh_failed')
+ return res
+ .status(502)
+ .json({ error: 'refresh_failed', status: result.status, detail: result.detail })
+ }
+ } catch (err) {
+ next(err)
+ }
+ }
+ )
+
+ return router
+}
diff --git a/control-api/src/utils/auth/mcpHostJwtToken.ts b/control-api/src/utils/auth/mcpHostJwtToken.ts
index eaa376d62..104d764a9 100644
--- a/control-api/src/utils/auth/mcpHostJwtToken.ts
+++ b/control-api/src/utils/auth/mcpHostJwtToken.ts
@@ -148,6 +148,11 @@ export const ALL_MCP_HOST_CONTROL_SCOPES = [
// (status.pluginWorkloadSdk) declares the SDK; SDK routes reject access
// tokens without it via scope_denied.
'plugin-workload-sdk',
+ // OAuth mcp-server broker (U1). Lets mcp-host exchange its control JWT for a
+ // per-connection provider access token at POST /api/v1/mcp-oauth/user-token.
+ // Provisioners request it only for hosts that front OAuth mcp-servers; the
+ // route rejects control tokens lacking it with 403 insufficient_scope.
+ 'oauth:user-token',
] as const
export type McpHostControlScope = (typeof ALL_MCP_HOST_CONTROL_SCOPES)[number]
diff --git a/control-api/test/crd.mcpServerOauth.test.ts b/control-api/test/crd.mcpServerOauth.test.ts
new file mode 100644
index 000000000..8707b53c1
--- /dev/null
+++ b/control-api/test/crd.mcpServerOauth.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { dirname, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parse } from 'yaml'
+
+// CRD-admission invariants for the OAuth mcp-server surface (U1). These are
+// K8s-apiserver rules, not control-api code paths, so we assert the CRD YAML
+// structurally. NOTE: CEL SEMANTICS (create-context passes / update-change
+// fails / none→oauth passes) are enforced by the apiserver's CEL evaluator at
+// admission time and cannot be executed here (no CEL evaluator is vendored).
+// We assert the rule STRINGS are present and shaped as transition rules
+// (has()-guarded on oldSelf). Semantic verification requires `kubectl
+// --dry-run=server` against a live cluster.
+const crdPath = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ '../../charts/clerum-crds/crds/mcpserver.yaml'
+)
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const doc: any = parse(readFileSync(crdPath, 'utf8'))
+const specSchema = doc.spec.versions[0].schema.openAPIV3Schema.properties.spec
+const specRules: Array<{ rule: string; message: string }> = specSchema['x-kubernetes-validations']
+
+describe('McpServer CRD — OAuth surface (U1)', () => {
+ it("adds 'oauth' to spec.auth.type enum", () => {
+ expect(specSchema.properties.auth.properties.type.enum).toContain('oauth')
+ })
+
+ it('defines spec.oauth with the required client fields', () => {
+ const oauth = specSchema.properties.oauth
+ expect(oauth.type).toBe('object')
+ expect(oauth.required).toEqual(
+ expect.arrayContaining(['id', 'provider', 'clientIdRef', 'clientSecretRef'])
+ )
+ for (const p of [
+ 'id',
+ 'provider',
+ 'clientIdRef',
+ 'clientSecretRef',
+ 'scopes',
+ 'backgroundAccess',
+ 'grantScope',
+ ]) {
+ expect(oauth.properties).toHaveProperty(p)
+ }
+ })
+
+ it('grantScope is enum [user, context], default user, nested under spec.oauth', () => {
+ const grantScope = specSchema.properties.oauth.properties.grantScope
+ expect(grantScope.enum).toEqual(['user', 'context'])
+ expect(grantScope.default).toBe('user')
+ })
+
+ it('provider enum lists exactly the adapters shipped today (U2 extends monday/clickup/vercel)', () => {
+ expect(specSchema.properties.oauth.properties.provider.enum).toEqual([
+ 'salesforce',
+ 'slack',
+ 'notion',
+ 'microsoft-graph',
+ 'google',
+ ])
+ })
+
+ it('couples auth.type==oauth with spec.oauth presence', () => {
+ const rule = specRules.find(
+ r => r.rule.includes("self.auth.type == 'oauth'") && r.rule.includes('has(self.oauth)')
+ )
+ expect(rule, 'oauth coupling rule present').toBeDefined()
+ })
+
+ it('forbids a static secretRef/secretKey on an oauth server', () => {
+ const rule = specRules.find(
+ r =>
+ r.rule.includes('has(self.oauth)') &&
+ r.rule.includes('secretRef') &&
+ r.rule.includes('secretKey')
+ )
+ expect(rule, 'no-static-credential rule present').toBeDefined()
+ })
+
+ it('makes grantScope/id/provider immutable via has()-guard transition rules (skipped on create, enforced on update)', () => {
+ for (const field of ['grantScope', 'id', 'provider']) {
+ const rule = specRules.find(
+ r =>
+ r.rule.includes(`oldSelf.oauth.${field}`) &&
+ r.rule.includes(`self.oauth.${field}`) &&
+ r.rule.includes('!has(oldSelf.oauth)')
+ )
+ expect(rule, `immutability rule for oauth.${field} present and oldSelf-guarded`).toBeDefined()
+ }
+ })
+})
diff --git a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
new file mode 100644
index 000000000..7b4bbbbba
--- /dev/null
+++ b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const clientQuery = vi.fn()
+const clientRelease = vi.fn()
+const mockConnect = vi.fn()
+const mockPoolCtor = vi.fn(function MockPool() {
+ return { connect: mockConnect, query: vi.fn() }
+})
+
+vi.mock('pg', () => ({ Pool: mockPoolCtor }))
+
+describe('0091 oauth_grants owner generalization migration', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ mockConnect.mockResolvedValue({ query: clientQuery, release: clientRelease })
+ clientQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ })
+
+ it('is registered last in the migration array, after 0090', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const versions = CONTROL_API_MIGRATIONS.map(m => m.version)
+ expect(versions.at(-1)).toBe('0091_oauth_grants_owner_generalization')
+ expect(versions).toContain('0090_plugin_workload_sdk_runtime_contract_reconciliation')
+ })
+
+ it('adds owner_kind/context_id/bootstrapped_by, replaces the kind CHECK to admit shared, and rebuilds uniqueness', async () => {
+ const { initDb } = await import('../src/db.js')
+ await initDb()
+ const sqls = clientQuery.mock.calls.map(([sql]) => String(sql))
+ const migration = sqls.find(
+ sql => sql.includes('ADD COLUMN IF NOT EXISTS owner_kind') && sql.includes('oauth_grants')
+ )
+ expect(migration, 'the 0091 DDL was applied').toBeDefined()
+ const ddl = migration as string
+
+ // New columns (idempotent).
+ expect(ddl).toContain("ADD COLUMN IF NOT EXISTS owner_kind TEXT NOT NULL DEFAULT 'recipe'")
+ expect(ddl).toContain('ADD COLUMN IF NOT EXISTS context_id TEXT')
+ expect(ddl).toContain('ADD COLUMN IF NOT EXISTS bootstrapped_by_user_id TEXT')
+
+ // The kind/user_id CHECK is DROP+re-ADD to admit 'shared' — without this a
+ // shared INSERT would violate the old user/service-only CHECK.
+ expect(ddl).toContain('DROP CONSTRAINT IF EXISTS oauth_grants_kind_userid_check')
+ expect(ddl).toContain("grant_kind = 'shared' AND user_id IS NULL")
+ expect(ddl).toContain('context_id IS NOT NULL')
+ expect(ddl).toContain('bootstrapped_by_user_id IS NOT NULL')
+
+ // oauth_grants_unique recreated as a superset with owner_kind.
+ expect(ddl).toContain('DROP CONSTRAINT IF EXISTS oauth_grants_unique')
+ expect(ddl).toContain(
+ 'UNIQUE (owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id)'
+ )
+
+ // Shared partial unique index keyed by context_id.
+ expect(ddl).toContain('CREATE UNIQUE INDEX IF NOT EXISTS oauth_grants_shared_unique')
+ expect(ddl).toContain(
+ 'ON oauth_grants (owner_kind, recipe_namespace, recipe_name, context_id, oauth_client_id)'
+ )
+ expect(ddl).toContain("WHERE grant_kind = 'shared'")
+
+ // Non-destructive: recipe_namespace/recipe_name are NOT renamed.
+ expect(ddl).not.toContain('RENAME COLUMN')
+ })
+})
diff --git a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts
index a8119eba7..bdc726ff4 100644
--- a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts
+++ b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts
@@ -23,7 +23,10 @@ describe('Plugin Workload SDK runtime-contract reconciliation migration', () =>
candidate => candidate.version === '0090_plugin_workload_sdk_runtime_contract_reconciliation'
)
expect(migration).toBeDefined()
- expect(CONTROL_API_MIGRATIONS.at(-2)?.version).toBe(
+ // 0089 immediately precedes 0090 (position-independent so later additions
+ // like 0091 don't break this ordering check).
+ const idx0090 = CONTROL_API_MIGRATIONS.findIndex(m => m.version === migration?.version)
+ expect(CONTROL_API_MIGRATIONS[idx0090 - 1]?.version).toBe(
'0089_plugin_workload_sdk_credential_ticket_runtime_access'
)
diff --git a/control-api/test/oauth.callback.test.ts b/control-api/test/oauth.callback.test.ts
index c077a9328..ab96fe424 100644
--- a/control-api/test/oauth.callback.test.ts
+++ b/control-api/test/oauth.callback.test.ts
@@ -147,17 +147,19 @@ describe('handleOAuthCallback (O4.1)', () => {
expect(db.query).toHaveBeenCalledTimes(1)
const [sql, params] = db.query.mock.calls[0] as [string, unknown[]]
expect(sql).toContain('INSERT INTO oauth_grants')
- expect(params[0]).toBe('sandbox-recipes')
- expect(params[1]).toBe('crm')
- expect(params[2]).toBe(USER_ID)
- expect(params[3]).toBe('salesforce')
+ // owner_kind leads the param list (recipe domain for the recipe callback).
+ expect(params[0]).toBe('recipe')
+ expect(params[1]).toBe('sandbox-recipes')
+ expect(params[2]).toBe('crm')
+ expect(params[3]).toBe(USER_ID)
expect(params[4]).toBe('salesforce')
- // params[5] is the encrypted access token; should be a non-empty string.
- expect(typeof params[5]).toBe('string')
- expect((params[5] as string).startsWith('v1.')).toBe(true)
- // params[6] is the encrypted refresh token; should also be encrypted.
+ expect(params[5]).toBe('salesforce')
+ // params[6] is the encrypted access token; should be a non-empty string.
expect(typeof params[6]).toBe('string')
expect((params[6] as string).startsWith('v1.')).toBe(true)
+ // params[7] is the encrypted refresh token; should also be encrypted.
+ expect(typeof params[7]).toBe('string')
+ expect((params[7] as string).startsWith('v1.')).toBe(true)
})
it('stores a service grant with no user_id when state.grantKind is service', async () => {
@@ -185,12 +187,13 @@ describe('handleOAuthCallback (O4.1)', () => {
expect(sql).toContain(
"ON CONFLICT (recipe_namespace, recipe_name, oauth_client_id) WHERE grant_kind = 'service'"
)
- // Service INSERT carries 7 params (no user_id): ns, name, oauthClientId,
- // provider, accessToken, refreshToken, expiresAt.
- expect(params).toHaveLength(7)
- expect(params[0]).toBe('sandbox-recipes')
- expect(params[1]).toBe('crm')
- expect(params[2]).toBe('salesforce') // oauthClientId — NOT a userId
+ // Service INSERT carries 8 params (no user_id): owner_kind, ns, name,
+ // oauthClientId, provider, accessToken, refreshToken, expiresAt.
+ expect(params).toHaveLength(8)
+ expect(params[0]).toBe('recipe')
+ expect(params[1]).toBe('sandbox-recipes')
+ expect(params[2]).toBe('crm')
+ expect(params[3]).toBe('salesforce') // oauthClientId — NOT a userId
})
it('rejects a tampered state (signature mismatch)', async () => {
diff --git a/control-api/test/oauth.helpers.test.ts b/control-api/test/oauth.helpers.test.ts
index 0bd520a2b..78f50c254 100644
--- a/control-api/test/oauth.helpers.test.ts
+++ b/control-api/test/oauth.helpers.test.ts
@@ -493,8 +493,8 @@ describe('getAccessToken (O5.1)', () => {
const [sql, params] = db.query.mock.calls[0] as unknown as [string, unknown[]]
expect(sql).toContain('user_id IS NULL')
expect(sql).toContain("grant_kind = 'service'")
- // No userId param — the service key is (ns, name, oauthClientId).
- expect(params).toEqual(['sandbox-recipes', 'crm', 'salesforce'])
+ // No userId param — the service key is (owner_kind, ns, name, oauthClientId).
+ expect(params).toEqual(['recipe', 'sandbox-recipes', 'crm', 'salesforce'])
})
it('refreshes a service grant and re-upserts via the service path (Path B)', async () => {
@@ -554,8 +554,9 @@ describe('getAccessToken (O5.1)', () => {
expect(upsertSql).toContain(
"ON CONFLICT (recipe_namespace, recipe_name, oauth_client_id) WHERE grant_kind = 'service'"
)
- // Service INSERT carries 7 params (no user_id); the user INSERT carries 8.
- expect(upsertParams).toHaveLength(7)
+ // Service INSERT carries 8 params (owner_kind, ns, name, oauthClientId,
+ // provider, accessToken, refreshToken, expiresAt) — no user_id.
+ expect(upsertParams).toHaveLength(8)
})
// Suppresses unused-import warnings for helpers we kept exported
diff --git a/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts b/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
new file mode 100644
index 000000000..263f6bf54
--- /dev/null
+++ b/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
@@ -0,0 +1,158 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import type { DbClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { bootstrapSharedOAuthGrant, getOAuthGrant, upsertOAuthGrant } from '../src/oauth/store.js'
+
+// T1/T5 — shared-identity grant semantics derived from the REAL producer
+// (real ON CONFLICT DO NOTHING + CHECK constraints), not a hand-built fixture.
+// Gated on a real Postgres, like the other *.realPostgres.integration.test.ts:
+// CONTROL_API_REAL_PG_ADMIN_URL=postgres://user:pass@host:5432 npm test -- \
+// test/oauth.store.sharedGrants.realPostgres.integration.test.ts
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+
+describeRealPostgres('oauth store — shared grants (real Postgres)', () => {
+ const database = `control_api_shared_grants_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ const sharedKey = (server: string, contextId: string) => ({
+ grantKind: 'shared' as const,
+ ownerKind: 'mcpserver' as const,
+ recipeNamespace: config.mcpServersNamespace,
+ recipeName: server,
+ contextId,
+ oauthClientId: 'google-drive',
+ })
+
+ it('bootstrap is first-wins; a token refresh preserves bootstrapped_by and updates tokens', async () => {
+ const server = 'gdrive-a'
+ const first = await bootstrapSharedOAuthGrant(db, KEY, {
+ ...sharedKey(server, 'ctx-1'),
+ bootstrappedByUserId: 'user-1',
+ provider: 'google',
+ accessToken: 'ACCESS-1',
+ refreshToken: 'REFRESH-1',
+ accessTokenExpiresInSec: 3600,
+ })
+ expect(first.inserted).toBe(true)
+
+ // A concurrent second member's callback also succeeds but no-ops (DO NOTHING):
+ // it inherits the team's grant; tokens + bootstrapper stay the first member's.
+ const second = await bootstrapSharedOAuthGrant(db, KEY, {
+ ...sharedKey(server, 'ctx-1'),
+ bootstrappedByUserId: 'user-2',
+ provider: 'google',
+ accessToken: 'ACCESS-2',
+ refreshToken: 'REFRESH-2',
+ accessTokenExpiresInSec: 3600,
+ })
+ expect(second.inserted).toBe(false)
+
+ const afterBootstrap = await getOAuthGrant(db, KEY, sharedKey(server, 'ctx-1'))
+ expect(afterBootstrap?.accessToken).toBe('ACCESS-1')
+ expect(afterBootstrap?.bootstrappedByUserId).toBe('user-1')
+
+ // Token refresh (upsert by key) rotates the tokens but MUST NOT rewrite the
+ // audit column or the shared identity.
+ await upsertOAuthGrant(db, KEY, {
+ ...sharedKey(server, 'ctx-1'),
+ provider: 'google',
+ accessToken: 'ACCESS-3',
+ refreshToken: 'REFRESH-3',
+ accessTokenExpiresInSec: 3600,
+ })
+ const afterRefresh = await getOAuthGrant(db, KEY, sharedKey(server, 'ctx-1'))
+ expect(afterRefresh?.accessToken).toBe('ACCESS-3')
+ expect(afterRefresh?.refreshToken).toBe('REFRESH-3')
+ expect(afterRefresh?.bootstrappedByUserId).toBe('user-1')
+ })
+
+ it('shared grants of distinct context_id coexist (key disjunction)', async () => {
+ const server = 'gdrive-b'
+ await bootstrapSharedOAuthGrant(db, KEY, {
+ ...sharedKey(server, 'ctx-A'),
+ bootstrappedByUserId: 'user-1',
+ provider: 'google',
+ accessToken: 'A-TOKEN',
+ })
+ await bootstrapSharedOAuthGrant(db, KEY, {
+ ...sharedKey(server, 'ctx-B'),
+ bootstrappedByUserId: 'user-9',
+ provider: 'google',
+ accessToken: 'B-TOKEN',
+ })
+ const a = await getOAuthGrant(db, KEY, sharedKey(server, 'ctx-A'))
+ const b = await getOAuthGrant(db, KEY, sharedKey(server, 'ctx-B'))
+ expect(a?.accessToken).toBe('A-TOKEN')
+ expect(a?.bootstrappedByUserId).toBe('user-1')
+ expect(b?.accessToken).toBe('B-TOKEN')
+ expect(b?.bootstrappedByUserId).toBe('user-9')
+ })
+
+ it('a user grant and a shared grant of the same server do not collide', async () => {
+ const server = 'gdrive-c'
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: config.mcpServersNamespace,
+ recipeName: server,
+ userId: 'user-1',
+ oauthClientId: 'google-drive',
+ provider: 'google',
+ accessToken: 'USER-TOKEN',
+ })
+ await bootstrapSharedOAuthGrant(db, KEY, {
+ ...sharedKey(server, 'ctx-1'),
+ bootstrappedByUserId: 'user-2',
+ provider: 'google',
+ accessToken: 'SHARED-TOKEN',
+ })
+ const userGrant = await getOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: config.mcpServersNamespace,
+ recipeName: server,
+ userId: 'user-1',
+ oauthClientId: 'google-drive',
+ })
+ const sharedGrant = await getOAuthGrant(db, KEY, sharedKey(server, 'ctx-1'))
+ expect(userGrant?.accessToken).toBe('USER-TOKEN')
+ expect(sharedGrant?.accessToken).toBe('SHARED-TOKEN')
+ })
+})
diff --git a/control-api/test/oauth.store.sharedGrants.test.ts b/control-api/test/oauth.store.sharedGrants.test.ts
new file mode 100644
index 000000000..27ec98044
--- /dev/null
+++ b/control-api/test/oauth.store.sharedGrants.test.ts
@@ -0,0 +1,184 @@
+import { describe, expect, it } from 'vitest'
+import { config } from '../src/config.js'
+import type { DbClient } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import {
+ bootstrapSharedOAuthGrant,
+ deleteOAuthGrant,
+ getOAuthGrant,
+ oauthGrantExists,
+ upsertOAuthGrant,
+} from '../src/oauth/store.js'
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+
+function fakeDb(
+ rows: unknown[] = [],
+ rowCount?: number
+): {
+ db: DbClient
+ calls: { text: string; values: unknown[] }[]
+} {
+ const calls: { text: string; values: unknown[] }[] = []
+ const db = {
+ query: async (text: string, values: unknown[] = []) => {
+ calls.push({ text, values })
+ return { rows, rowCount: rowCount ?? rows.length } as never
+ },
+ } as unknown as DbClient
+ return { db, calls }
+}
+
+const SHARED_KEY = {
+ grantKind: 'shared' as const,
+ ownerKind: 'mcpserver' as const,
+ recipeNamespace: 'mcp-server',
+ recipeName: 'gdrive',
+ contextId: 'ctx-9',
+ oauthClientId: 'google-drive',
+}
+
+describe('oauth store — shared (context-identity) grants', () => {
+ it('bootstrapSharedOAuthGrant issues INSERT … ON CONFLICT DO NOTHING with bootstrapped_by, returns inserted', async () => {
+ const { db, calls } = fakeDb([{ id: 1 }], 1)
+ const out = await bootstrapSharedOAuthGrant(db, KEY, {
+ ...SHARED_KEY,
+ bootstrappedByUserId: 'user-1',
+ provider: 'google',
+ accessToken: 'A',
+ refreshToken: 'R',
+ accessTokenExpiresInSec: 3600,
+ })
+ expect(out.inserted).toBe(true)
+ expect(calls[0].text).toContain('INSERT INTO oauth_grants')
+ expect(calls[0].text).toContain('ON CONFLICT')
+ expect(calls[0].text).toContain('DO NOTHING')
+ expect(calls[0].text).toContain('bootstrapped_by_user_id')
+ expect(calls[0].text).toContain("'shared'")
+ // owner, ns, name, contextId, clientId, bootstrappedBy are bound in order.
+ expect(calls[0].values.slice(0, 6)).toEqual([
+ 'mcpserver',
+ 'mcp-server',
+ 'gdrive',
+ 'ctx-9',
+ 'google-drive',
+ 'user-1',
+ ])
+ })
+
+ it('bootstrapSharedOAuthGrant reports inserted=false when the conflict no-ops', async () => {
+ const { db } = fakeDb([], 0)
+ const out = await bootstrapSharedOAuthGrant(db, KEY, {
+ ...SHARED_KEY,
+ bootstrappedByUserId: 'user-2',
+ provider: 'google',
+ accessToken: 'A',
+ })
+ expect(out.inserted).toBe(false)
+ })
+
+ it('upsertOAuthGrant(shared) is a plain UPDATE by key and never touches bootstrapped_by_user_id', async () => {
+ const { db, calls } = fakeDb()
+ await upsertOAuthGrant(db, KEY, {
+ ...SHARED_KEY,
+ provider: 'google',
+ accessToken: 'A2',
+ refreshToken: 'R2',
+ accessTokenExpiresInSec: 3600,
+ })
+ expect(calls[0].text).toContain('UPDATE oauth_grants')
+ expect(calls[0].text).not.toContain('INSERT INTO oauth_grants')
+ expect(calls[0].text).not.toContain('bootstrapped_by_user_id')
+ expect(calls[0].text).toContain("grant_kind = 'shared'")
+ expect(calls[0].values.slice(0, 5)).toEqual([
+ 'mcpserver',
+ 'mcp-server',
+ 'gdrive',
+ 'ctx-9',
+ 'google-drive',
+ ])
+ })
+
+ it('getOAuthGrant(shared) filters owner_kind + context_id + grant_kind=shared and maps audit columns', async () => {
+ const { db, calls } = fakeDb([
+ {
+ owner_kind: 'mcpserver',
+ recipe_namespace: 'mcp-server',
+ recipe_name: 'gdrive',
+ user_id: null,
+ context_id: 'ctx-9',
+ bootstrapped_by_user_id: 'user-1',
+ oauth_client_id: 'google-drive',
+ grant_kind: 'shared',
+ provider: 'google',
+ access_token_encrypted: (await import('../src/oauth/encryption.js')).encryptOAuthSecret(
+ KEY,
+ 'A'
+ ),
+ refresh_token_encrypted: null,
+ access_token_expires_at: null,
+ updated_at: new Date(),
+ background: false,
+ },
+ ])
+ const row = await getOAuthGrant(db, KEY, SHARED_KEY)
+ expect(row?.grantKind).toBe('shared')
+ expect(row?.ownerKind).toBe('mcpserver')
+ expect(row?.contextId).toBe('ctx-9')
+ expect(row?.bootstrappedByUserId).toBe('user-1')
+ expect(row?.accessToken).toBe('A')
+ expect(calls[0].text).toContain("grant_kind = 'shared'")
+ expect(calls[0].text).toContain('context_id = $4')
+ expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'gdrive', 'ctx-9', 'google-drive'])
+ })
+
+ it('oauthGrantExists(shared) is scoped to the context key', async () => {
+ const { db, calls } = fakeDb([{ '?column?': 1 }])
+ const exists = await oauthGrantExists(db, SHARED_KEY)
+ expect(exists).toBe(true)
+ expect(calls[0].text).toContain("grant_kind = 'shared'")
+ expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'gdrive', 'ctx-9', 'google-drive'])
+ })
+
+ it('deleteOAuthGrant(shared) deletes the single shared row by context key', async () => {
+ const { db, calls } = fakeDb()
+ await deleteOAuthGrant(db, SHARED_KEY)
+ expect(calls[0].text).toContain('DELETE FROM oauth_grants')
+ expect(calls[0].text).toContain("grant_kind = 'shared'")
+ expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'gdrive', 'ctx-9', 'google-drive'])
+ })
+})
+
+describe('oauth store — owner_kind on user/service ops (recipe domain unchanged)', () => {
+ it('upsertOAuthGrant(user) defaults owner_kind=recipe and includes it in the conflict target', async () => {
+ const { db, calls } = fakeDb()
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'leadforge',
+ userId: 'user-1',
+ oauthClientId: 'google-gmail',
+ provider: 'google',
+ accessToken: 'A',
+ })
+ expect(calls[0].text).toContain('owner_kind')
+ expect(calls[0].text).toContain(
+ 'ON CONFLICT (owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id)'
+ )
+ expect(calls[0].values[0]).toBe('recipe')
+ })
+
+ it('getOAuthGrant(user) with explicit ownerKind=mcpserver scopes the lookup', async () => {
+ const { db, calls } = fakeDb()
+ await getOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: 'mcp-server',
+ recipeName: 'gdrive',
+ userId: 'user-1',
+ oauthClientId: 'google-drive',
+ })
+ expect(calls[0].text).toContain('owner_kind = $1')
+ expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'gdrive', 'user-1', 'google-drive'])
+ })
+})
diff --git a/control-api/test/recipeOauth.userToken.test.ts b/control-api/test/recipeOauth.userToken.test.ts
index e13ba6d19..b979c9bc9 100644
--- a/control-api/test/recipeOauth.userToken.test.ts
+++ b/control-api/test/recipeOauth.userToken.test.ts
@@ -110,9 +110,10 @@ describe('routes/recipe-oauth — POST /recipe-oauth/user-token (SEC-5)', () =>
// [SEC-5] verify the grant lookup was scoped to the correct recipe and userId
const grantQuery = mockPoolQuery.mock.calls.find(
- ([sql]) => typeof sql === 'string' && sql.includes('oauth_grants') && sql.includes('background = true')
+ ([sql]) =>
+ typeof sql === 'string' && sql.includes('oauth_grants') && sql.includes('background = true')
)
- expect(grantQuery?.[1]).toEqual([SANDBOX_NS, 'leadforge', 'user-1', 'google-gmail'])
+ expect(grantQuery?.[1]).toEqual(['recipe', SANDBOX_NS, 'leadforge', 'user-1', 'google-gmail'])
})
it('404 no_grant for a non-consented (background=false) user', async () => {
@@ -175,8 +176,12 @@ describe('routes/recipe-oauth — POST /recipe-oauth/user-token (SEC-5)', () =>
const res = await request(app)
.post('/api/v1/recipe-oauth/user-token')
.set('Authorization', `Bearer ${brokerToken('leadforge')}`)
- .send({ oauthClientId: 'google-gmail', userId: 'user-1',
- recipeName: 'victim', recipeNamespace: SANDBOX_NS })
+ .send({
+ oauthClientId: 'google-gmail',
+ userId: 'user-1',
+ recipeName: 'victim',
+ recipeNamespace: SANDBOX_NS,
+ })
// Grant lookup was scoped to "leadforge" — no grant seeded → no_grant
expect(res.status).toBe(404)
@@ -184,7 +189,7 @@ describe('routes/recipe-oauth — POST /recipe-oauth/user-token (SEC-5)', () =>
const grantQuery = mockPoolQuery.mock.calls.find(
([sql]) => typeof sql === 'string' && sql.includes('oauth_grants')
)
- expect(grantQuery?.[1]).toEqual([SANDBOX_NS, 'leadforge', 'user-1', 'google-gmail'])
+ expect(grantQuery?.[1]).toEqual(['recipe', SANDBOX_NS, 'leadforge', 'user-1', 'google-gmail'])
})
it('returns 429 when the per-recipe rate limit is exceeded', async () => {
diff --git a/control-api/test/routes.adminRecipeOauth.test.ts b/control-api/test/routes.adminRecipeOauth.test.ts
index c8ebf80d5..fb2c6828a 100644
--- a/control-api/test/routes.adminRecipeOauth.test.ts
+++ b/control-api/test/routes.adminRecipeOauth.test.ts
@@ -135,7 +135,7 @@ describe('routes/admin/recipeOauth', () => {
const [sql, params] = mockPoolQuery.mock.calls[0] as [string, unknown[]]
expect(sql).toContain("grant_kind = 'service'")
expect(sql).toContain('user_id IS NULL')
- expect(params).toEqual([SANDBOX_NS, 'crm', 'salesforce'])
+ expect(params).toEqual(['recipe', SANDBOX_NS, 'crm', 'salesforce'])
})
})
@@ -145,7 +145,7 @@ describe('routes/admin/recipeOauth', () => {
const [sql, params] = mockPoolQuery.mock.calls[0] as [string, unknown[]]
expect(sql).toContain('DELETE FROM oauth_grants')
expect(sql).toContain("grant_kind = 'service'")
- expect(params).toEqual([SANDBOX_NS, 'crm', 'salesforce'])
+ expect(params).toEqual(['recipe', SANDBOX_NS, 'crm', 'salesforce'])
})
})
})
diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.ts
new file mode 100644
index 000000000..d9eebca13
--- /dev/null
+++ b/control-api/test/routes.mcpOauth.test.ts
@@ -0,0 +1,262 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import request from 'supertest'
+import { createApp } from '../src/app.js'
+import { config } from '../src/config.js'
+import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'
+import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'
+import { MockGateway } from './mockGateway.js'
+
+const mockPoolQuery = vi.fn()
+
+vi.mock('../src/db.js', () => ({
+ pool: {
+ query: (...args: unknown[]) => mockPoolQuery(...args),
+ },
+}))
+
+vi.mock('../src/services/notificationEmitter.js', () => ({
+ emitNotification: vi.fn().mockResolvedValue(undefined),
+ enqueueApprovalRequestedNotification: vi.fn().mockResolvedValue(undefined),
+ enqueueApprovalUpdatedNotification: vi.fn().mockResolvedValue(undefined),
+}))
+
+vi.mock('../src/services/rateLimiterService.js', () => ({
+ checkAndIncrement: vi.fn().mockResolvedValue({
+ allowed: true,
+ remaining: 59,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 1,
+ }),
+}))
+
+const MCP_NS = config.mcpServersNamespace
+const ENCRYPTION_KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+
+function seedOauthServer(
+ gateway: MockGateway,
+ opts: { name: string; grantScope?: 'user' | 'context'; contextRef?: string }
+): void {
+ void gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: opts.name },
+ spec: {
+ // contextRef is CRD-required + singular — the AUTHORITATIVE Context.
+ contextRef: opts.contextRef ?? 'ctx-9',
+ auth: { type: 'oauth' },
+ oauth: {
+ id: 'google-drive',
+ provider: 'google',
+ clientIdRef: { name: 'google-creds', key: 'client-id' },
+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },
+ scopes: ['https://www.googleapis.com/auth/drive.readonly'],
+ ...(opts.grantScope ? { grantScope: opts.grantScope } : {}),
+ },
+ },
+ },
+ MCP_NS
+ )
+}
+
+// Control JWT derived from the REAL minter (T1) — no hand-forged token.
+function controlToken(scopes: Array<'oauth:user-token'> = ['oauth:user-token']): string {
+ return issueMcpHostControlJwt('mcp-host', 'standalone', ['mcp-host/standalone'], { scopes }).token
+}
+
+function nonExpiredUserGrantRow(userId: string, expiresAt: Date) {
+ return {
+ owner_kind: 'mcpserver',
+ recipe_namespace: MCP_NS,
+ recipe_name: 'gdrive',
+ user_id: userId,
+ context_id: null,
+ bootstrapped_by_user_id: null,
+ oauth_client_id: 'google-drive',
+ grant_kind: 'user',
+ provider: 'google',
+ access_token_encrypted: encryptOAuthSecret(ENCRYPTION_KEY, 'GDRIVE-ACCESS'),
+ refresh_token_encrypted: encryptOAuthSecret(ENCRYPTION_KEY, 'GDRIVE-REFRESH'),
+ access_token_expires_at: expiresAt,
+ updated_at: new Date(),
+ background: false,
+ }
+}
+
+describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {
+ let gateway: MockGateway
+ let app: ReturnType<typeof createApp>
+
+ beforeEach(() => {
+ gateway = new MockGateway(MCP_NS)
+ app = createApp(gateway as never)
+ mockPoolQuery.mockReset()
+ mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ })
+
+ it('401 without a control JWT', async () => {
+ seedOauthServer(gateway, { name: 'gdrive' })
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .send({ mcpServerName: 'gdrive', userId: 'user-1' })
+ expect(res.status).toBe(401)
+ })
+
+ it('403 with a valid control JWT that lacks the oauth:user-token scope', async () => {
+ seedOauthServer(gateway, { name: 'gdrive' })
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken([])}`)
+ .send({ mcpServerName: 'gdrive', userId: 'user-1' })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('insufficient_scope')
+ })
+
+ it('200 {token,expiresAt} for a per-user grant, keyed by (mcpserver owner, userId)', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })
+ const future = new Date(Date.now() + 3600_000)
+ mockPoolQuery.mockResolvedValueOnce({
+ rows: [nonExpiredUserGrantRow('user-1', future)],
+ rowCount: 1,
+ })
+
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'gdrive', userId: 'user-1', contextId: 'ctx-9' })
+
+ expect(res.status).toBe(200)
+ expect(res.body.token).toBe('GDRIVE-ACCESS')
+ expect(res.body.expiresAt).toBe(future.toISOString())
+
+ // Grant lookup scoped to the mcpserver owner + asserted userId, oauthClientId
+ // derived from the server (never the body).
+ const grantQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) =>
+ typeof sql === 'string' &&
+ sql.includes('FROM oauth_grants') &&
+ sql.includes("grant_kind = 'user'")
+ )
+ expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'user-1', 'google-drive'])
+ })
+
+ it('404 no_grant when no row exists', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'gdrive', userId: 'nobody' })
+ expect(res.status).toBe(404)
+ expect(res.body.error).toBe('no_grant')
+ })
+
+ it('404 server_not_found for an unknown server', async () => {
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'ghost', userId: 'user-1' })
+ expect(res.status).toBe(404)
+ expect(res.body.error).toBe('server_not_found')
+ })
+
+ it('400 not_oauth_server for a non-oauth server', async () => {
+ void gateway.createResource(
+ 'mcpservers',
+ { metadata: { name: 'plain' }, spec: { auth: { type: 'none' } } },
+ MCP_NS
+ )
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'plain', userId: 'user-1' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('not_oauth_server')
+ })
+
+ it('context flavor: key uses the AUTHORITATIVE spec.contextRef, not the body; user_id NULL', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+ const future = new Date(Date.now() + 3600_000)
+ mockPoolQuery.mockResolvedValueOnce({
+ rows: [
+ {
+ ...nonExpiredUserGrantRow('', future),
+ grant_kind: 'shared',
+ user_id: null,
+ context_id: 'ctx-A',
+ bootstrapped_by_user_id: 'user-1',
+ },
+ ],
+ rowCount: 1,
+ })
+
+ // Body omits contextId entirely — the server's contextRef is authoritative.
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'gdrive', userId: 'user-2' })
+
+ expect(res.status).toBe(200)
+ const grantQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) =>
+ typeof sql === 'string' &&
+ sql.includes('FROM oauth_grants') &&
+ sql.includes("grant_kind = 'shared'")
+ )
+ // owner, ns, name, contextId(=contextRef), clientId — userId NOT a coordinate.
+ expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'ctx-A', 'google-drive'])
+ })
+
+ // Guardian (T5): a caller with the scope must NOT be able to fetch another
+ // Context's shared token by asserting a foreign contextId in the body. The
+ // server's spec.contextRef is 'ctx-A'; a request naming 'ctx-B' is rejected
+ // BEFORE any grant lookup — the ctx-B token is never observable (T4).
+ it('rejects a cross-context body contextId with 400 context_mismatch and never queries the foreign grant', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'gdrive', userId: 'user-2', contextId: 'ctx-B' })
+
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('context_mismatch')
+ expect(res.body.token).toBeUndefined()
+ // No grant lookup ran at all — the foreign coordinate never reached the DB.
+ const grantQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants')
+ )
+ expect(grantQuery).toBeUndefined()
+ })
+
+ it('accepts a body contextId that matches spec.contextRef', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+ const future = new Date(Date.now() + 3600_000)
+ mockPoolQuery.mockResolvedValueOnce({
+ rows: [
+ {
+ ...nonExpiredUserGrantRow('', future),
+ grant_kind: 'shared',
+ user_id: null,
+ context_id: 'ctx-A',
+ bootstrapped_by_user_id: 'user-1',
+ },
+ ],
+ rowCount: 1,
+ })
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'gdrive', userId: 'user-2', contextId: 'ctx-A' })
+ expect(res.status).toBe(200)
+ expect(res.body.token).toBe('GDRIVE-ACCESS')
+ })
+
+ it('400 invalid_request for a malformed (non-k8s) server name, before any getResource', async () => {
+ const res = await request(app)
+ .post('/api/v1/mcp-oauth/user-token')
+ .set('Authorization', `Bearer ${controlToken()}`)
+ .send({ mcpServerName: 'Foo/Bar', userId: 'user-1' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_request')
+ })
+})
diff --git a/control-api/test/routes.oauthDisconnect.test.ts b/control-api/test/routes.oauthDisconnect.test.ts
index e83564a78..cc4854acb 100644
--- a/control-api/test/routes.oauthDisconnect.test.ts
+++ b/control-api/test/routes.oauthDisconnect.test.ts
@@ -85,10 +85,12 @@ describe('DELETE /api/v1/internal/sandbox-ui/oauth/grant (spec §9.9 disconnect)
expect(mockPoolQuery).toHaveBeenCalledTimes(1)
const [sql, params] = mockPoolQuery.mock.calls[0] as [string, unknown[]]
expect(sql).toContain('DELETE FROM oauth_grants')
- expect(params[0]).toBe(config.sandboxNamespace)
- expect(params[1]).toBe('crm')
- expect(params[2]).toBe('user-uuid-1')
- expect(params[3]).toBe('salesforce-prod')
+ // owner_kind leads the param list (recipe domain).
+ expect(params[0]).toBe('recipe')
+ expect(params[1]).toBe(config.sandboxNamespace)
+ expect(params[2]).toBe('crm')
+ expect(params[3]).toBe('user-uuid-1')
+ expect(params[4]).toBe('salesforce-prod')
})
it('is idempotent — 204 even when no grant exists', async () => {
diff --git a/control-api/test/routes.recipeOauth.test.ts b/control-api/test/routes.recipeOauth.test.ts
index a839d669e..8c45d093f 100644
--- a/control-api/test/routes.recipeOauth.test.ts
+++ b/control-api/test/routes.recipeOauth.test.ts
@@ -195,7 +195,7 @@ describe('routes/recipe-oauth — POST /recipe-oauth/token', () => {
const grantQuery = mockPoolQuery.mock.calls.find(
([sql]) => typeof sql === 'string' && sql.includes('oauth_grants')
)
- expect(grantQuery?.[1]).toEqual([SANDBOX_NS, 'crm', 'salesforce'])
+ expect(grantQuery?.[1]).toEqual(['recipe', SANDBOX_NS, 'crm', 'salesforce'])
})
it('returns 429 when the per-recipe rate limit is exceeded', async () => {
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index c672234da..7ed85b211 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.163",
+ "version": "0.1.164",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.163",
+ "version": "0.1.164",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 85b46b7c4..9bf751897 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.163",
+ "version": "0.1.164",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.ts
index a7488dc7d..ce5b8a603 100644
--- a/host-context-controller/src/types.ts
+++ b/host-context-controller/src/types.ts
@@ -12,11 +12,37 @@ export interface McpServerTransport {
port?: number
}
+/**
+ * Reference to a key within a Kubernetes Secret.
+ */
+export interface McpServerSecretRef {
+ name: string
+ key: string
+}
+
+/**
+ * OAuth broker configuration for an mcp-server (auth.type === 'oauth').
+ *
+ * Present iff `spec.auth.type === 'oauth'`. control-api owns the OAuth flow and
+ * resolves tokens per connection just-in-time; HCC does NOT mount the token as
+ * env (invariant O4 stays intact — this type only lets the controller type the
+ * discriminator; the runtime token carril is mcp-host's, not HCC's).
+ */
+export interface McpServerOAuth {
+ id: string
+ provider: 'salesforce' | 'slack' | 'notion' | 'microsoft-graph' | 'google'
+ clientIdRef: McpServerSecretRef
+ clientSecretRef: McpServerSecretRef
+ scopes?: string[]
+ backgroundAccess?: boolean
+ grantScope?: 'user' | 'context'
+}
+
/**
* McpServer authentication configuration.
*/
export interface McpServerAuth {
- type: 'none' | 'bearer' | 'basic' | 'apiKey'
+ type: 'none' | 'bearer' | 'basic' | 'apiKey' | 'oauth'
secretRef?: string
secretKey?: string
}
@@ -121,6 +147,9 @@ export interface McpServerSpec {
args?: string[]
transport: McpServerTransport
auth?: McpServerAuth
+ // OAuth broker config; present iff auth.type === 'oauth'. Typing only — HCC
+ // does NOT mount the resolved token as env (O4 stays intact).
+ oauth?: McpServerOAuth
serverConfig?: McpServerConfig
envMapping?: McpServerEnvMapping
env?: McpServerEnvVar[]