Skip to content

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

TypeScript

fix(control-api): gate user-scope MCP OAuth by context allowlist

Diego Zacariaseddc169d5e8c
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 092d6afee..e202849e8 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.738",
+ "version": "0.1.739",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.738",
+ "version": "0.1.739",
"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.json
index 2b01bf382..38771b118 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.738",
+ "version": "0.1.739",
"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/__tests__/callbackMcpMembership.test.ts b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
index c4c1e14e4..ab83d1d2b 100644
--- a/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
+++ b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
@@ -10,7 +10,7 @@ import {
import { signOAuthState } from '../state.js'
/**
- * Guards-before-exchange ordering for the mcp context-scoped callback (R3-L1).
+ * Guards-before-exchange ordering for the mcp callback (R3-L1).
*
* The fix moves the `server_missing_context` + `context_membership_denied`
* guards ahead of `exchangeAuthCode`, so a user removed from the Context during
@@ -18,6 +18,10 @@ import { signOAuthState } from '../state.js'
* (no token exchange, no secret read). These tests pin that: the `fetchFn` /
* `secretReader` spies must stay untouched on the denied path, while the
* happy paths (context member + per-user) still exchange and persist.
+ *
+ * The per-user flavor has its own pre-exchange guard: some Context the user
+ * belongs to must still enable the server (`userServerAccessReader`), so a user
+ * who lost that access between mint and callback cannot finish creating a grant.
*/
const STATE_SECRET = 'test-state-secret-0123456789abcdef' // ≥ 32 chars
@@ -88,6 +92,7 @@ function buildDeps(
secretReader?: CallbackDeps['secretReader']
db?: CallbackDeps['db']
userContextsReader?: CallbackDeps['userContextsReader']
+ userServerAccessReader?: CallbackDeps['userServerAccessReader']
} = {}
): CallbackDeps {
const secretReader =
@@ -108,6 +113,10 @@ function buildDeps(
secretReader,
mcpServerReader: { read: vi.fn(async () => opts.subject ?? mcpSubject()) },
userContextsReader,
+ // Absent unless a test wires it, so the unwired (fail-closed) case is real.
+ ...('userServerAccessReader' in opts
+ ? { userServerAccessReader: opts.userServerAccessReader }
+ : {}),
fetchFn: opts.fetchFn ?? okTokenFetch(),
stateSecret: STATE_SECRET,
encryptionKey: ENCRYPTION_KEY,
@@ -184,13 +193,17 @@ describe('handleOAuthCallback — mcp context membership guard (R3-L1)', () => {
expect(String(query.mock.calls[0][0])).toContain("'shared'")
})
- it('per-user grant path is intact: exchange runs and upsert persists', async () => {
+ // The per-user happy path now requires a Context of the user that enables the
+ // server (previously the per-user path ran no access check at all).
+ it('per-user grant path: an enabled user exchanges and upserts', async () => {
const fetchFn = okTokenFetch()
const userContextsReader = vi.fn(async () => ({ contextIds: [] }))
+ const userServerAccessReader = vi.fn(async () => true)
const deps = buildDeps({
subject: mcpSubject({ grantScope: 'user', contextRef: undefined }),
fetchFn,
userContextsReader,
+ userServerAccessReader,
})
const result = await handleOAuthCallback(input(), deps)
@@ -200,7 +213,9 @@ describe('handleOAuthCallback — mcp context membership guard (R3-L1)', () => {
expect(result.source).toBe('mcp')
}
expect(fetchFn).toHaveBeenCalledTimes(1)
- // The per-user path never consults the membership reader (its key IS the user).
+ // Access is checked for the SIGNED initiator and the SIGNED server name.
+ expect(userServerAccessReader).toHaveBeenCalledWith(USER_ID, MCP_SERVER_NAME)
+ // The per-user path never consults the contextRef membership reader.
expect(userContextsReader).not.toHaveBeenCalled()
const query = deps.db.query as ReturnType<typeof vi.fn>
expect(query).toHaveBeenCalledTimes(1)
@@ -208,6 +223,46 @@ describe('handleOAuthCallback — mcp context membership guard (R3-L1)', () => {
expect(String(query.mock.calls[0][0])).toContain("'user'")
})
+ it('per-user: no Context of the user enables the server → denied WITHOUT exchanging', async () => {
+ const fetchFn = okTokenFetch()
+ const secretReader = {
+ read: vi.fn(async () => ({ client_id: 'cid', client_secret: 'csec' })),
+ } as unknown as CallbackDeps['secretReader']
+ const userServerAccessReader = vi.fn(async () => false)
+ const deps = buildDeps({
+ subject: mcpSubject({ grantScope: 'user', contextRef: CONTEXT_REF }),
+ // Membership in the server's contextRef is irrelevant for this flavor.
+ contextIds: [CONTEXT_REF],
+ fetchFn,
+ secretReader,
+ userServerAccessReader,
+ })
+
+ const result = await handleOAuthCallback(input(), deps)
+
+ expect(result.kind).toBe('context_membership_denied')
+ expect(userServerAccessReader).toHaveBeenCalledWith(USER_ID, MCP_SERVER_NAME)
+ expect(fetchFn).not.toHaveBeenCalled()
+ expect(secretReader.read).not.toHaveBeenCalled()
+ expect(deps.db.query as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
+ })
+
+ it('per-user: fails closed WITHOUT exchanging when no access reader is wired', async () => {
+ const fetchFn = okTokenFetch()
+ const deps = buildDeps({
+ subject: mcpSubject({ grantScope: 'user', contextRef: CONTEXT_REF }),
+ contextIds: [CONTEXT_REF],
+ fetchFn,
+ userServerAccessReader: undefined,
+ })
+
+ const result = await handleOAuthCallback(input(), deps)
+
+ expect(result.kind).toBe('context_membership_denied')
+ expect(fetchFn).not.toHaveBeenCalled()
+ expect(deps.db.query as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
+ })
+
// R3-H5 (D-T3): the subject's CR uid seals the grant so a same-name reinstall's
// teardown never purges this installation's consent.
it('seals a shared bootstrap grant with the subject cr_uid', async () => {
@@ -231,6 +286,7 @@ describe('handleOAuthCallback — mcp context membership guard (R3-L1)', () => {
const deps = buildDeps({
subject: mcpSubject({ grantScope: 'user', contextRef: undefined, crUid: 'uid-live-cr' }),
userContextsReader: vi.fn(async () => ({ contextIds: [] })),
+ userServerAccessReader: vi.fn(async () => true),
})
const result = await handleOAuthCallback(input(), deps)
@@ -252,6 +308,7 @@ describe('handleOAuthCallback — mcp context membership guard (R3-L1)', () => {
const deps = buildDeps({
subject: mcpSubject({ grantScope: 'user', contextRef: undefined, crUid: undefined }),
userContextsReader: vi.fn(async () => ({ contextIds: [] })),
+ userServerAccessReader: vi.fn(async () => true),
})
const result = await handleOAuthCallback(input(), deps)
diff --git a/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts b/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts
index adc46424f..db1840550 100644
--- a/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts
+++ b/control-api/src/oauth/__tests__/callbackRemoteIss.test.ts
@@ -127,6 +127,8 @@ function buildDeps(
read: vi.fn(async () => ({}) as Record<string, string>),
} as unknown as CallbackDeps['secretReader'],
mcpServerReader: { read: vi.fn(async () => opts.subject ?? remoteSubject()) },
+ // Per-user remote subjects: a Context of the user enables the server.
+ userServerAccessReader: vi.fn(async () => true),
// Remote lane never touches globalThis fetch (DEC-17); a call is a regression.
fetchFn: vi.fn() as unknown as typeof fetch,
stateSecret: STATE_SECRET,
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index d30921940..6b4f08f81 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -288,9 +288,20 @@ export interface CallbackDeps {
* consenting user MUST be a member first. Injected so the pure callback stays
* testable; the route wires the real `getUserContexts`. When absent on a
* shared-context path, that path fails closed (`context_membership_denied`).
- * The per-user path never touches it (its key IS the user).
+ * The per-user path never touches it: its access check is
+ * `userServerAccessReader`.
*/
userContextsReader?: (userId: string) => Promise<{ contextIds: string[] }>
+ /**
+ * Whether some Context the user belongs to still enables the server through
+ * its `spec.mcpServers` allowlist. Required ONLY for the per-user mcp path
+ * (`grantScope='user'`), re-checked before the code exchange so a user who
+ * lost that access after the authorize URL was minted cannot finish creating
+ * a grant. The route wires the same rule the authorize-URL mint applies. When
+ * absent on a per-user path, that path fails closed
+ * (`context_membership_denied`). The shared-context path never touches it.
+ */
+ userServerAccessReader?: (userId: string, mcpServerName: string) => Promise<boolean>
/**
* Injectable for tests; defaults to globalThis.fetch in production wiring.
* BAKED lane ONLY — the remote lane (`source:'remote'`) never uses it (DEC-17):
@@ -543,13 +554,20 @@ export async function handleOAuthCallback(
* the `mcpServerName`; the server's OAuth declaration + grant-scope routing are
* recovered fresh from the CR (authoritative), NOT from the state or any body.
*
+ * Access is re-checked BEFORE the code exchange, by flavor:
+ * - `grantScope='user'` → some Context the signed user belongs to must still
+ * allowlist the server (`userServerAccessReader`); `spec.contextRef` is not
+ * consulted.
+ * - `grantScope='context'` → the signed user must be a member of the server's
+ * `spec.contextRef` (`userContextsReader`).
+ *
* Persistence connects to the U1 store primitives (no reimplementation):
* - `grantScope='user'` → `upsertOAuthGrant` `(mcpserver, ns, name, userId)`.
* - `grantScope='context'` → `bootstrapSharedOAuthGrant` `(mcpserver, ns, name,
* spec.contextRef)`, bootstrapper = the signed `userId` (first-consent wins;
* U6 governance). The Context comes from the AUTHORITATIVE `spec.contextRef`,
* never the state — so no context field is (or needs to be) bound into the
- * mcp state in v1.
+ * mcp state.
*/
async function handleMcpOAuthCallback(
claims: OAuthMcpStateClaims,
@@ -607,16 +625,15 @@ async function handleMcpOAuthCallback(
redirectUri = perServer.redirectUri
}
- // ─── Membership guards run BEFORE the token exchange (R3-L1) ──────────────
+ // ─── Access guards run BEFORE the token exchange (R3-L1) ──────────────────
// These guards depend only on the signed claims + the resolved subject
- // (`subject.contextRef`, `deps.userContextsReader`, `claims.userId`) — never
- // on the token. Running them first means a user removed from the Context
- // during the ~600s mint→callback window fails here instead of first driving
- // `exchangeAuthCode`, which burns the single-use auth-code against the
- // provider and yields a real token only to discard it at a 403. The mint is
- // still the primary gate, so this is not exploitable head-on; it just avoids
- // the pointless exchange + code burn. Persistence (below) stays after the
- // exchange, unchanged.
+ // (`subject.contextRef`, `claims.userId`, `claims.mcpServerName`) and the
+ // injected readers — never on the token. Running them first means a user who
+ // lost access during the ~600s mint→callback window fails here instead of
+ // first driving `exchangeAuthCode`, which burns the single-use auth-code
+ // against the provider and yields a real token only to discard it at a 403.
+ // The mint is still the primary gate; this re-check closes the window between
+ // the two. Persistence (below) stays after the exchange.
//
// `contextRef` is set iff this is a context-scoped grant that passed the
// membership guard; the persistence dispatch below keys off it (non-undefined
@@ -636,6 +653,13 @@ async function handleMcpOAuthCallback(
return { kind: 'context_membership_denied' }
}
contextRef = subject.contextRef
+ } else {
+ // Per-user identity — the grant serves every Context that enables the
+ // server, so access is "some Context of the user still allowlists it", the
+ // same rule the mint applied. Fail closed when the reader is unwired.
+ if (!deps.userServerAccessReader) return { kind: 'context_membership_denied' }
+ const enabled = await deps.userServerAccessReader(claims.userId, claims.mcpServerName)
+ if (!enabled) return { kind: 'context_membership_denied' }
}
const exchanged = await exchangeAuthCode(
diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.ts
index 5b33957a3..7f70aa660 100644
--- a/control-api/src/routes/external/oauthCallback.ts
+++ b/control-api/src/routes/external/oauthCallback.ts
@@ -21,6 +21,7 @@ import {
resolveServerOAuthSubject,
} from '../../oauth/mcpServerOAuthSpec.js'
import { isValidInstallNonce, isValidRemoteServerNameSegment } from '../../oauth/remoteCallback.js'
+import { userHasContextEnablingMcpServer } from '../../services/access/mcpInvocable.js'
import { getUserContexts } from '../../services/directory/index.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
@@ -128,6 +129,15 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
// Shared-identity mcp bootstrap requires the consenting user to be a
// member of the server's Context (defence in depth).
userContextsReader: getUserContexts,
+ // Per-user mcp consent requires some Context of the user to still
+ // allowlist the server — the same rule the authorize-URL mint applies.
+ userServerAccessReader: (userId, mcpServerName) =>
+ userHasContextEnablingMcpServer({
+ gateway,
+ mcpServersNamespace: config.mcpServersNamespace,
+ userId,
+ mcpServerName,
+ }),
fetchFn: (input, init) => fetch(input, init),
stateSecret: config.oauthStateHmacSecret,
encryptionKey,
diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.ts
index f6a91c959..82c7acaea 100644
--- a/control-api/src/routes/internal/oauth.ts
+++ b/control-api/src/routes/internal/oauth.ts
@@ -40,6 +40,7 @@ import {
remoteCallbackVariant,
} from '../../oauth/remoteCallback.js'
import { deleteOAuthGrant } from '../../oauth/store.js'
+import { userHasContextEnablingMcpServer } from '../../services/access/mcpInvocable.js'
import { getUserContexts } from '../../services/directory/index.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
import {
@@ -241,9 +242,10 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
// fresh per click keeps the state's 600s TTL counting from the user's click
// and binds the state to that initiator.
//
- // `oauthClientId` + `grantScope` + the Context come from the McpServer CR
- // (authoritative), never the body. A body `contextId` for a context-identity
- // server is only cross-checked against `spec.contextRef` (defence in depth).
+ // `oauthClientId` + `grantScope` come from the McpServer CR (authoritative),
+ // never the body. For a context-identity server the Context is the CR's
+ // `spec.contextRef` and a body `contextId` is only cross-checked against it
+ // (defence in depth); for a per-user server the body `contextId` is ignored.
router.post(
'/internal/mcp-oauth/authorize-url',
requireInternalService('rpc-proxy'),
@@ -298,8 +300,26 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
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).
+ // Access gate, failing EARLY (before sending the user to the provider),
+ // by flavor:
+ // - `context`: the AUTHORITATIVE Context is the CR's `spec.contextRef`;
+ // a body contextId, if present, must match it (cross-context guard),
+ // and the consenting user must be a member of it, because the
+ // resulting shared grant is planted for that whole Context.
+ // - `user`: the grant is keyed by (user, server) and serves every
+ // Context that enables the server, so the user must belong to at
+ // least one Context whose `spec.mcpServers` allowlist names it — the
+ // same rule invoke and the catalog apply. `spec.contextRef` and the
+ // body contextId play no part: gating on the former rejected users
+ // whose Context enables a server another Context declares.
+ // Either way, connect shares the `mcp:server:invoke` scope with invoke,
+ // so without this gate any user could start consent for (and enumerate)
+ // integrations none of their Contexts expose.
+ //
+ // Deliberately NOT resolveInvocableMcpServersForContexts: that applies
+ // the grant-presence gate, which filters out servers WITHOUT a grant —
+ // exactly the ones connect exists to bootstrap (chicken-and-egg). The
+ // callback re-checks the same rules before exchanging the code.
if (coord.grantScope === 'context') {
if (!coord.contextRef) {
return res.status(400).json({ error: 'server_missing_context' })
@@ -307,30 +327,20 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
if (typeof contextId === 'string' && contextId !== coord.contextRef) {
return res.status(400).json({ error: 'context_mismatch' })
}
- }
-
- // DEC-U5-1 (+ security fix): defence in depth — fail EARLY (before
- // sending the user to the provider) unless the consenting user is a
- // member of the server's Context. This runs for EVERY grantScope, not
- // just `context`: even a per-user server lives inside a Context, and
- // connect shares the `mcp:server:invoke` scope with invoke — which
- // additionally requires the server to be in the caller's per-context
- // allowlist. Without a universal gate, any user could start consent for
- // (and enumerate) another Context's integration on a `user`-scope server.
- //
- // `spec.contextRef` is CRD-required + singular, so every server has one;
- // a server that somehow lacks it cannot be membership-verified → fail
- // closed. Same rule + primitive as the callback bootstrap
- // (getUserContexts → user_contexts) so membership lives in ONE place
- // (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 (!coord.contextRef) {
- return res.status(403).json({ error: 'context_membership_denied' })
- }
- const { contextIds } = await getUserContexts(userId)
- if (!contextIds.includes(coord.contextRef)) {
- return res.status(403).json({ error: 'context_membership_denied' })
+ const { contextIds } = await getUserContexts(userId)
+ if (!contextIds.includes(coord.contextRef)) {
+ return res.status(403).json({ error: 'context_membership_denied' })
+ }
+ } else {
+ const enabled = await userHasContextEnablingMcpServer({
+ gateway,
+ mcpServersNamespace: config.mcpServersNamespace,
+ userId,
+ mcpServerName,
+ })
+ if (!enabled) {
+ return res.status(403).json({ error: 'context_membership_denied' })
+ }
}
if (incoherent) throw incoherent
const resolved = subject
@@ -350,7 +360,7 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
userId,
// mcp reactive consent mints per-user-shaped states; grant-scope
// routing (user vs shared) is resolved authoritatively on the
- // callback from spec.contextRef.
+ // callback from the CR's grantScope.
grantKind: 'user',
background: false,
redirectUri,
@@ -410,22 +420,23 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
// (invariant §1.4). The grant coordinate (oauthClientId + grantScope + the
// Context) is derived from the McpServer CR, never the body.
//
- // Authorization BY FLAVOR (spec §2.3, mini-spec 05 §7):
+ // Authorization BY FLAVOR:
// - `user` → the caller may only delete their OWN grant — the key is
// built on the forwarded `userId`. For an END-USER a cross-user delete is
// structurally impossible, because rpc-proxy derives `userId` from the
// session `auth.sub` and never from the body; control-api trusts that on
- // the service-token seam (it does not re-verify the identity itself).
- // - `context` → any MEMBER of the server's Context may revoke the single
- // shared grant → blast-radius: the WHOLE Context is disconnected.
+ // the service-token seam (it does not re-verify the identity itself). No
+ // Context membership is required: the key already confines the delete to
+ // the caller, and a user who has left every Context must still be able to
+ // revoke the token they granted.
+ // - `context` → any MEMBER of the server's Context (`getUserContexts` →
+ // user_contexts) may revoke the single shared grant → blast-radius: the
+ // WHOLE Context is disconnected. Fail-closed: a server with no
+ // `contextRef` or a caller who is not a member is rejected.
//
- // The Context-membership gate runs for EVERY grantScope. It SHARES its
- // data-reader (`getUserContexts` → user_contexts) with the authorize-URL mint
- // and the callback bootstrap (D4 for the membership LOOKUP); the membership
- // RULE itself is written inline at each of those sites (here, the mint, and
- // partially in callback.ts), not factored into one function. Fail-closed: a
- // server with no usable OAuth id, no `contextRef`, or a caller who is not a
- // Context member is rejected — the grant is NEVER deleted blindly.
+ // Existence (404) and oauth-ness (400) are answered before either branch, for
+ // every caller. A server with no usable OAuth id is rejected — the grant is
+ // NEVER deleted blindly.
//
// Idempotent: deleting a grant that does not exist returns 204 (matching the
// sandbox-ui grant delete below). We deliberately do NOT surface "no grant
@@ -480,7 +491,8 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
}
// Context-identity servers: the AUTHORITATIVE Context is spec.contextRef.
- // A body contextId, if present, must match it (cross-context guard).
+ // A body contextId, if present, must match it (cross-context guard). A
+ // per-user server ignores the body contextId.
if (resolved.grantScope === 'context') {
if (!resolved.contextRef) {
return res.status(400).json({ error: 'server_missing_context' })
@@ -488,18 +500,11 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
if (typeof contextId === 'string' && contextId !== resolved.contextRef) {
return res.status(400).json({ error: 'context_mismatch' })
}
- }
-
- // Universal Context-membership gate (every grantScope) — same rule +
- // primitive as the authorize-URL mint (D4). `spec.contextRef` is
- // CRD-required + singular; a server that somehow lacks it cannot be
- // membership-verified → fail closed.
- if (!resolved.contextRef) {
- return res.status(403).json({ error: 'context_membership_denied' })
- }
- const { contextIds } = await getUserContexts(userId)
- if (!contextIds.includes(resolved.contextRef)) {
- return res.status(403).json({ error: 'context_membership_denied' })
+ // Membership gate, `context` flavor only (see the route note).
+ const { contextIds } = await getUserContexts(userId)
+ if (!contextIds.includes(resolved.contextRef)) {
+ return res.status(403).json({ error: 'context_membership_denied' })
+ }
}
// Build the flavored delete key from the SAME source of truth the
@@ -511,12 +516,12 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
})
if (!key) {
// Unreachable: `buildMcpServerGrantKey` returns null only when a
- // context server lacks `contextRef` (already rejected above at the
- // membership gate) or a user server lacks `userId` (validated
- // non-empty above). Fail closed defensively rather than delete against
- // a malformed key — with the generic `invalid_request` (mirrors the
- // token mint's null-key guard, routes/mcpOauth.ts), since the specific
- // null cause was already handled.
+ // context server lacks `contextRef` (already rejected above) or a
+ // user server lacks `userId` (validated non-empty above). Fail closed
+ // defensively rather than delete against a malformed key — with the
+ // generic `invalid_request` (mirrors the token mint's null-key guard,
+ // routes/mcpOauth.ts), since the specific null cause was already
+ // handled.
return res.status(400).json({ error: 'invalid_request' })
}
@@ -527,7 +532,9 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
// Audit trail (sensitive: a revocation). Structured, pino-redacted; no
// tokens/secrets are read or logged here. `userId` is the acting
- // principal, `contextRef` the server's authoritative Context, and
+ // principal, `contextRef` the server's Context as declared on the CR
+ // (the grant's Context for the `context` flavor; informational and
+ // possibly absent for `user`, whose grant has no Context), and
// `deleted` records whether a row was actually removed (false on an
// idempotent no-op) so the audit trail is honest about what happened.
req.log?.info(
diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.ts
index 4eae39362..3e5f8922b 100644
--- a/control-api/src/services/access/mcpInvocable.ts
+++ b/control-api/src/services/access/mcpInvocable.ts
@@ -37,6 +37,7 @@ import {
type AgentDirectoryEntry,
buildAgentDirectoryEntry,
} from '../directory/accessReconciliation.js'
+import { getUserContexts } from '../directory/contextAccess.js'
const log = rootLogger.child({ module: 'mcpInvocable' })
const connectorsLog = rootLogger.child({ module: 'mcp-connectors' })
@@ -154,7 +155,7 @@ function asArray<T>(value: unknown): T[] {
* the caller authorizes by agent rather than by context.
*/
async function loadAllowedNamesByContext(
- gateway: K8sGateway,
+ gateway: Pick<K8sGateway, 'listResource'>,
mcpServersNamespace: string,
scopedContextIds?: ReadonlySet<string>
): Promise<Map<string, Set<string>>> {
@@ -173,6 +174,39 @@ async function loadAllowedNamesByContext(
return byContext
}
+/**
+ * Whether some Context the user belongs to enables `mcpServerName` through its
+ * `spec.mcpServers` allowlist. This is the access rule for consenting to (and
+ * completing consent for) a per-user OAuth server: the grant is keyed by
+ * (user, server) and serves every Context that enables the server, so access
+ * follows the same allowlist rule invoke and the catalog apply, never the
+ * server's own `spec.contextRef`.
+ *
+ * Membership is `getUserContexts` (direct `user_contexts` only, active users)
+ * so this gate stays aligned with the catalog, which reads the same source;
+ * counting team membership here alone would let a user connect servers the
+ * catalog never shows them. Deliberately ignores grant presence: the consent
+ * flow exists precisely for servers that have no grant yet.
+ */
+export async function userHasContextEnablingMcpServer(opts: {
+ gateway: Pick<K8sGateway, 'listResource'>
+ mcpServersNamespace: string
+ userId: string
+ mcpServerName: string
+}): Promise<boolean> {
+ const { contextIds } = await getUserContexts(opts.userId)
+ if (contextIds.length === 0) return false
+ const allowedByContext = await loadAllowedNamesByContext(
+ opts.gateway,
+ opts.mcpServersNamespace,
+ new Set(contextIds)
+ )
+ for (const names of allowedByContext.values()) {
+ if (names.has(opts.mcpServerName)) return true
+ }
+ return false
+}
+
/**
* Derive the invocation URL for an MCP server. stdio-transport servers are
* proxied by an in-namespace stdio-bridge sidecar on a well-known path, so
diff --git a/control-api/test/fixtures/contextAllowlist.ts b/control-api/test/fixtures/contextAllowlist.ts
new file mode 100644
index 000000000..08711be59
--- /dev/null
+++ b/control-api/test/fixtures/contextAllowlist.ts
@@ -0,0 +1,42 @@
+import type { Mock } from 'vitest'
+import { config } from '../../src/config.js'
+import { attachServerToContext } from '../../src/services/contextAllowlist.js'
+import type { MockGateway } from '../mockGateway.js'
+
+/**
+ * Seed a Context CR (CRD-required fields only) and write its allowlist through
+ * the real allowlist writer, so the `spec.mcpServers` shape the access gates
+ * read is the one production writes.
+ */
+export async function seedAllowlistedContext(
+ gateway: MockGateway,
+ name: string,
+ servers: string[],
+ namespace: string = config.mcpServersNamespace
+): Promise<void> {
+ await gateway.createResource(
+ 'contexts',
+ { metadata: { name }, spec: { contextId: name, mcpServers: [] } },
+ namespace
+ )
+ for (const server of servers) {
+ await attachServerToContext(gateway as never, { name, namespace }, server)
+ }
+}
+
+/**
+ * Answer `getUserContexts` (the `FROM user_contexts` read) with `contextIds` on
+ * the suite's mocked `pool.query`; every other query resolves empty.
+ */
+export function memberOf(poolQuery: Mock, contextIds: string[]): void {
+ poolQuery.mockImplementation((sql: unknown) => {
+ const text = typeof sql === 'string' ? sql : ''
+ if (text.includes('FROM user_contexts')) {
+ return Promise.resolve({
+ rows: contextIds.map(context_id => ({ context_id })),
+ rowCount: contextIds.length,
+ })
+ }
+ return Promise.resolve({ rows: [], rowCount: 0 })
+ })
+}
diff --git a/control-api/test/fixtures/legacyOAuthGrant.ts b/control-api/test/fixtures/legacyOAuthGrant.ts
index 4ed516d5d..54eed51d9 100644
--- a/control-api/test/fixtures/legacyOAuthGrant.ts
+++ b/control-api/test/fixtures/legacyOAuthGrant.ts
@@ -223,6 +223,7 @@ export async function legacyConsent(
},
},
userContextsReader: async () => ({ contextIds: [CONTEXT] }),
+ userServerAccessReader: async () => true,
fetchFn: fetchFn as unknown as typeof fetch,
stateSecret: STATE_SECRET,
encryptionKey,
@@ -267,6 +268,7 @@ export async function currentConsent(
},
},
userContextsReader: async () => ({ contextIds: [CONTEXT] }),
+ userServerAccessReader: async () => true,
fetchFn: (async () => {
throw new Error('remote/generic consent must not use fetchFn')
}) as unknown as typeof fetch,
diff --git a/control-api/test/oauth.callback.generic.test.ts b/control-api/test/oauth.callback.generic.test.ts
index e36f438d2..af6d080ac 100644
--- a/control-api/test/oauth.callback.generic.test.ts
+++ b/control-api/test/oauth.callback.generic.test.ts
@@ -118,6 +118,7 @@ function baseDeps(overrides: Partial<CallbackDeps>): CallbackDeps {
} as unknown as CallbackDeps['db'],
recipeReader: { read: vi.fn(async () => null) },
userContextsReader: vi.fn(async () => ({ contextIds: ['ctx-A'] })),
+ userServerAccessReader: vi.fn(async () => true),
fetchFn: (async () => {
throw new Error('generic lane must NOT use fetchFn (DEC-17)')
}) as unknown as typeof fetch,
diff --git a/control-api/test/oauth.callback.mcp.test.ts b/control-api/test/oauth.callback.mcp.test.ts
index 59121351b..717276c5d 100644
--- a/control-api/test/oauth.callback.mcp.test.ts
+++ b/control-api/test/oauth.callback.mcp.test.ts
@@ -126,6 +126,8 @@ function buildDeps(opts: {
recipeReader,
mcpServerReader,
userContextsReader,
+ // Per-user servers: a Context of the user enables the server.
+ userServerAccessReader: vi.fn(async () => true),
secretReader: secretReader as unknown as CallbackDeps['secretReader'],
fetchFn: fetchFn as unknown as typeof fetch,
stateSecret: STATE_SECRET,
diff --git a/control-api/test/oauth.callback.remote.test.ts b/control-api/test/oauth.callback.remote.test.ts
index 56e5d3d4f..772a2aac7 100644
--- a/control-api/test/oauth.callback.remote.test.ts
+++ b/control-api/test/oauth.callback.remote.test.ts
@@ -146,6 +146,7 @@ describe('handleOAuthCallback — remote exchange is IP-pinned (DEC-17, T3)', ()
recipeReader: { read: vi.fn(async () => null) },
mcpServerReader: remoteReader(),
userContextsReader: vi.fn(async () => ({ contextIds: ['ctx-A'] })),
+ userServerAccessReader: vi.fn(async () => true),
secretReader: { read: vi.fn(async () => ({})) } as unknown as CallbackDeps['secretReader'],
fetchFn: fetchFn as unknown as typeof fetch,
stateSecret: STATE_SECRET,
@@ -215,6 +216,7 @@ describe('baked mcp exchange stays on fetchFn (byte-identical, T5c)', () => {
recipeReader: { read: vi.fn(async () => null) },
mcpServerReader: { read: vi.fn(async () => subject) },
userContextsReader: vi.fn(async () => ({ contextIds: ['ctx-A'] })),
+ userServerAccessReader: vi.fn(async () => true),
secretReader: {
read: vi.fn(async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' })),
} as unknown as CallbackDeps['secretReader'],
diff --git a/control-api/test/oauth.callback.reservedRemoteSegment.test.ts b/control-api/test/oauth.callback.reservedRemoteSegment.test.ts
index fcc132554..151d86e7e 100644
--- a/control-api/test/oauth.callback.reservedRemoteSegment.test.ts
+++ b/control-api/test/oauth.callback.reservedRemoteSegment.test.ts
@@ -249,6 +249,7 @@ async function deliverState(lane: Lane, serverName: string, segment: string) {
secretReader,
mcpServerReader,
userContextsReader: vi.fn(async () => ({ contextIds: [CONTEXT] })),
+ userServerAccessReader: vi.fn(async () => true),
fetchFn: fetchFn as unknown as typeof fetch,
stateSecret: STATE_SECRET,
encryptionKey: ENCRYPTION_KEY,
diff --git a/control-api/test/oauth.callbackRemotePerServer.test.ts b/control-api/test/oauth.callbackRemotePerServer.test.ts
index c4f7212b1..69badd9a3 100644
--- a/control-api/test/oauth.callbackRemotePerServer.test.ts
+++ b/control-api/test/oauth.callbackRemotePerServer.test.ts
@@ -205,6 +205,7 @@ function harness() {
},
mcpServerReader: { read },
userContextsReader: async () => ({ contextIds: [CONTEXT] }),
+ userServerAccessReader: async () => true,
fetchFn: (async () => {
throw new Error('the remote lane must not use fetchFn')
}) as unknown as typeof fetch,
diff --git a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
index 034ca64eb..b8dec510f 100644
--- a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
@@ -229,6 +229,7 @@ describeRealPostgres(
recipeReader: { read: async () => null },
mcpServerReader: subjectReader(gateway),
userContextsReader: async () => ({ contextIds: ['ctx-A'] }),
+ userServerAccessReader: async () => true,
secretReader: { read: async () => ({}) },
fetchFn: (async () => {
throw new Error('remote lane must not use fetchFn')
diff --git a/control-api/test/oauth.remoteSpecCoherence.test.ts b/control-api/test/oauth.remoteSpecCoherence.test.ts
index 4db160512..152d5b83b 100644
--- a/control-api/test/oauth.remoteSpecCoherence.test.ts
+++ b/control-api/test/oauth.remoteSpecCoherence.test.ts
@@ -13,6 +13,7 @@ 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 { seedAllowlistedContext } from './fixtures/contextAllowlist.js'
import {
ATLASSIAN_V2_PILOT,
DROPBOX_PILOT,
@@ -361,6 +362,10 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
const created = (await gateway.createResource('mcpservers', crFrom(name, oauth), MCP_NS)) as {
metadata: { uid: string }
}
+ // The server is enabled in CONTEXT's allowlist (written by the real
+ // allowlist writer): a per-user server's connect gate is membership in a
+ // Context that allowlists it, so the member reaches the coherence check.
+ await seedAllowlistedContext(gateway, CONTEXT, [name], MCP_NS)
gateway.seedSecret('srv-oauth-client', MCP_NS, {
data: {
client_id: Buffer.from(PRE_REGISTERED_CLIENT_ID).toString('base64'),
diff --git a/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts
index 245de369a..16fd8be57 100644
--- a/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts
+++ b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts
@@ -4,6 +4,7 @@ import { createApp } from '../src/app.js'
import { config } from '../src/config.js'
import { verifyOAuthStateSignature } from '../src/oauth/state.js'
import { checkAndIncrement } from '../src/services/rateLimiterService.js'
+import { memberOf, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
import { MockGateway } from './mockGateway.js'
/**
@@ -11,7 +12,13 @@ import { MockGateway } from './mockGateway.js'
* mcp-server, on click. rpc-proxy is the sole authorized caller
* (requireInternalService('rpc-proxy')); the `userId` is forwarded over that
* mutually-authenticated seam (rpc-proxy derives it from the session auth.sub).
- * The `oauthClientId` + Context come from the McpServer CR, never the body.
+ * The `oauthClientId` + grantScope come from the McpServer CR, never the body.
+ *
+ * Membership gate by flavor:
+ * - `user` → the user must belong (user_contexts) to at least one Context
+ * whose `spec.mcpServers` allowlist names the server; `spec.contextRef` is
+ * irrelevant and the body `contextId` is ignored.
+ * - `context` → membership in the server's `spec.contextRef` (unchanged).
*/
const mockPoolQuery = vi.fn()
@@ -105,9 +112,9 @@ describe('POST /api/v1/internal/mcp-oauth/authorize-url (U5)', () => {
it('mints an authorize-URL whose signed state binds the forwarded userId + the SERVER oauthClientId', async () => {
seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })
- // Membership check runs for EVERY scope: user-7 is a member of the server's
- // Context (default contextRef ctx-9).
- mockPoolQuery.mockResolvedValue({ rows: [{ context_id: 'ctx-9' }], rowCount: 1 })
+ // user-7 is a member of ctx-9, whose allowlist enables gdrive.
+ await seedAllowlistedContext(gateway, 'ctx-9', ['gdrive'])
+ memberOf(mockPoolQuery, ['ctx-9'])
const res = await post(app)
.set('Authorization', 'Bearer dev-rpc-proxy-token')
.set('x-service-token', 'rpc-proxy')
@@ -210,33 +217,137 @@ describe('POST /api/v1/internal/mcp-oauth/authorize-url (U5)', () => {
expect(res.body.authorizeUrl).toBeUndefined()
})
- // Security fix: the per-user flavor ALSO runs the membership gate now — a
- // user-scope server still lives in a Context, and connect shares the invoke
- // scope. A MEMBER mints fine.
- it('user flavor: a MEMBER of the server Context mints OK', async () => {
- seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
- mockPoolQuery.mockResolvedValue({ rows: [{ context_id: 'ctx-9' }], rowCount: 1 })
+ // The `context` flavor keeps its contextRef-membership gate: an allowlist in
+ // another of the user's Contexts does not open it, and its own Context needs
+ // no allowlist entry.
+ it('context server: membership in an allowlisting Context other than contextRef → still 403', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+ await seedAllowlistedContext(gateway, 'ctx-B', ['gdrive'])
+ memberOf(mockPoolQuery, ['ctx-B'])
+ const res = await post(app)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'gdrive', userId: 'user-2' })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('context_membership_denied')
+ })
+
+ it('context server: a contextRef member mints even when no allowlist names the server', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+ memberOf(mockPoolQuery, ['ctx-A'])
+ const res = await post(app)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'gdrive', userId: 'user-2' })
+ expect(res.status).toBe(200)
+ })
+
+ // ── user flavor: membership by allowlist ────────────────────────────────
+ //
+ // These replace the earlier "member of spec.contextRef" expectations: a
+ // `user`-scope grant is keyed by (user, server) and serves every Context that
+ // enables the server, so the gate is the same rule invoke uses — the user
+ // belongs to at least one Context whose allowlist names the server. The
+ // server's own `spec.contextRef` no longer decides anything for this flavor.
+
+ // Reproduces the reported 403: the server's contextRef is a Context the user
+ // is NOT in, but a Context the user IS in allowlists the server.
+ it('user flavor: member of an allowlisting Context (not the server contextRef) mints OK', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-owner' })
+ await seedAllowlistedContext(gateway, 'ctx-owner', ['gdrive'])
+ await seedAllowlistedContext(gateway, 'ctx-business', ['gdrive'])
+ memberOf(mockPoolQuery, ['ctx-business', 'ctx-unrelated'])
const res = await post(app)
.set('Authorization', 'Bearer dev-rpc-proxy-token')
.set('x-service-token', 'rpc-proxy')
.send({ mcpServerName: 'gdrive', userId: 'user-7' })
expect(res.status).toBe(200)
expect(res.body.authorizeUrl).toContain('https://accounts.google.com/')
- // The membership lookup DID run (universal gate).
const membershipQuery = mockPoolQuery.mock.calls.find(
([sql]) => typeof sql === 'string' && sql.includes('FROM user_contexts')
)
- expect(membershipQuery).toBeDefined()
expect(membershipQuery?.[1]).toEqual(['user-7'])
})
- // Security fix (the asymmetry hole): a `user`-scope server whose Context the
- // user is NOT in must be rejected — no consent for another Context's
- // integration, no cross-context enumeration oracle.
- it('user flavor: a NON-member is rejected 403 at mint, with NO authorizeUrl', async () => {
+ it('user flavor: a server WITHOUT contextRef that an allowlist enables mints OK', async () => {
+ void gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: 'gdrive' },
+ spec: {
+ auth: { type: 'oauth' },
+ oauth: {
+ id: 'google-drive',
+ provider: 'google',
+ clientIdRef: { name: 'google-creds', key: 'client-id' },
+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },
+ grantScope: 'user',
+ },
+ },
+ },
+ MCP_NS
+ )
+ gateway.seedSecret('google-creds', MCP_NS, {
+ data: {
+ 'client-id': Buffer.from('GOOGLE_CLIENT_ID').toString('base64'),
+ 'client-secret': Buffer.from('GOOGLE_CLIENT_SECRET').toString('base64'),
+ },
+ })
+ await seedAllowlistedContext(gateway, 'ctx-business', ['gdrive'])
+ memberOf(mockPoolQuery, ['ctx-business'])
+ const res = await post(app)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'gdrive', userId: 'user-7' })
+ expect(res.status).toBe(200)
+ expect(res.body.authorizeUrl).toContain('https://accounts.google.com/')
+ })
+
+ it('user flavor: the body contextId is ignored (neither required nor cross-checked)', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-owner' })
+ await seedAllowlistedContext(gateway, 'ctx-business', ['gdrive'])
+ memberOf(mockPoolQuery, ['ctx-business'])
+ const res = await post(app)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'gdrive', userId: 'user-7', contextId: 'ctx-anything' })
+ expect(res.status).toBe(200)
+ })
+
+ it('user flavor: no Context of the user allowlists the server → 403, NO authorizeUrl', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
+ await seedAllowlistedContext(gateway, 'ctx-other', ['some-other-server'])
+ memberOf(mockPoolQuery, ['ctx-other'])
+ const res = await post(app)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'gdrive', userId: 'user-8' })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('context_membership_denied')
+ expect(res.body.authorizeUrl).toBeUndefined()
+ })
+
+ it('user flavor: a user with no Contexts at all → 403', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
+ await seedAllowlistedContext(gateway, 'ctx-9', ['gdrive'])
+ memberOf(mockPoolQuery, [])
+ const res = await post(app)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'gdrive', userId: 'user-8' })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('context_membership_denied')
+ })
+
+ // An allowlist only counts through membership: a Context that enables the
+ // server but that the user does not belong to grants nothing — including the
+ // server's own contextRef Context.
+ it('user flavor: an allowlisting Context the user is NOT a member of does not count → 403', async () => {
seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
- // user-8 is a member of other Contexts, but NOT ctx-9.
- mockPoolQuery.mockResolvedValue({ rows: [{ context_id: 'ctx-other' }], rowCount: 1 })
+ await seedAllowlistedContext(gateway, 'ctx-9', ['gdrive'])
+ await seedAllowlistedContext(gateway, 'ctx-business', ['gdrive'])
+ await seedAllowlistedContext(gateway, 'ctx-other', [])
+ memberOf(mockPoolQuery, ['ctx-other'])
const res = await post(app)
.set('Authorization', 'Bearer dev-rpc-proxy-token')
.set('x-service-token', 'rpc-proxy')
@@ -265,8 +376,10 @@ describe('POST /api/v1/internal/mcp-oauth/authorize-url (U5)', () => {
},
MCP_NS
)
- // Member of ctx-9 so we reach the Secret read (past the membership gate).
- mockPoolQuery.mockResolvedValue({ rows: [{ context_id: 'ctx-9' }], rowCount: 1 })
+ // Member of ctx-9, which enables gdrive, so we reach the Secret read (past
+ // the membership gate).
+ await seedAllowlistedContext(gateway, 'ctx-9', ['gdrive'])
+ memberOf(mockPoolQuery, ['ctx-9'])
const res = await post(app)
.set('Authorization', 'Bearer dev-rpc-proxy-token')
.set('x-service-token', 'rpc-proxy')
diff --git a/control-api/test/routes.internal.mcpOauthDisconnect.test.ts b/control-api/test/routes.internal.mcpOauthDisconnect.test.ts
index 44552a2d2..1392cfd89 100644
--- a/control-api/test/routes.internal.mcpOauthDisconnect.test.ts
+++ b/control-api/test/routes.internal.mcpOauthDisconnect.test.ts
@@ -15,7 +15,8 @@ import { MockGateway } from './mockGateway.js'
*
* Authorization BY FLAVOR (the security invariant, §2.3):
* - `user` → the key is built on the forwarded userId, so a cross-user
- * delete is structurally impossible.
+ * delete is structurally impossible. No Context membership is required: a
+ * user who has left every Context can still revoke their own token.
* - `context` → membership in the server's Context is required (getUserContexts),
* and a non-member is rejected 403 with NO delete.
*
@@ -177,10 +178,14 @@ describe('DELETE /api/v1/internal/mcp-oauth/grant (spec 11 U4)', () => {
// ── user flavor ──────────────────────────────────────────────────────────
- it('user flavor: a MEMBER revokes → 204 and deletes the (user, own-userId) grant', async () => {
+ // These replace the earlier "a NON-member is rejected 403" expectation for the
+ // user flavor: the delete key is (userId, server), so the caller can only ever
+ // remove their own grant, and requiring membership would leave a user who
+ // left every Context unable to revoke their own token.
+ it('user flavor: a user in NO Context revokes → 204 and deletes only the (user, own-userId) grant', async () => {
seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
- mockDb({ memberContexts: ['ctx-9'] })
- const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-7' })
+ mockDb({ memberContexts: [] })
+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-8' })
expect(res.status).toBe(204)
const calls = deleteCalls()
@@ -190,16 +195,61 @@ describe('DELETE /api/v1/internal/mcp-oauth/grant (spec 11 U4)', () => {
// the forwarded userId — a cross-user delete is structurally impossible.
expect(sql).toContain("grant_kind = 'user'")
// params order: [ownerKind, ns, serverName, userId, oauthClientId]
- expect(params).toEqual(['mcpserver', MCP_NS, 'gdrive', 'user-7', 'google-drive'])
+ expect(params).toEqual(['mcpserver', MCP_NS, 'gdrive', 'user-8', 'google-drive'])
})
- it('user flavor: a NON-member is rejected 403 and NOTHING is deleted', async () => {
+ it('user flavor: does not consult Context membership at all', async () => {
seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
- // user-8 belongs to other contexts, but NOT ctx-9.
mockDb({ memberContexts: ['ctx-other'] })
const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-8' })
- expect(res.status).toBe(403)
- expect(res.body.error).toBe('context_membership_denied')
+ expect(res.status).toBe(204)
+ const membershipQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) => typeof sql === 'string' && sql.includes('FROM user_contexts')
+ )
+ expect(membershipQuery).toBeUndefined()
+ })
+
+ it('user flavor: a server WITHOUT contextRef can be disconnected', async () => {
+ void gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: 'gdrive' },
+ spec: {
+ auth: { type: 'oauth' },
+ oauth: {
+ id: 'google-drive',
+ provider: 'google',
+ clientIdRef: { name: 'google-creds', key: 'client-id' },
+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },
+ grantScope: 'user',
+ },
+ },
+ },
+ MCP_NS
+ )
+ mockDb({ memberContexts: [] })
+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-7' })
+ expect(res.status).toBe(204)
+ expect(deleteCalls()).toHaveLength(1)
+ expect(deleteCalls()[0][1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'user-7', 'google-drive'])
+ })
+
+ // Existence and oauth-ness are still answered before any flavor-specific
+ // branch, for a user-flavor caller with no Contexts as for anyone else.
+ it('user flavor ordering: unknown server → 404 and non-oauth → 400, with no delete', async () => {
+ mockDb({ memberContexts: [] })
+ const missing = await del(app).send({ mcpServerName: 'ghost', userId: 'user-8' })
+ expect(missing.status).toBe(404)
+ expect(missing.body.error).toBe('server_not_found')
+
+ void gateway.createResource(
+ 'mcpservers',
+ { metadata: { name: 'plain' }, spec: { auth: { type: 'none' } } },
+ MCP_NS
+ )
+ const plain = await del(app).send({ mcpServerName: 'plain', userId: 'user-8' })
+ expect(plain.status).toBe(400)
+ expect(plain.body.error).toBe('not_oauth_server')
expect(deleteCalls()).toHaveLength(0)
})
diff --git a/control-api/test/routes.oauthCallback.remotePerServer.test.ts b/control-api/test/routes.oauthCallback.remotePerServer.test.ts
index 1bb92060c..006c5e5fa 100644
--- a/control-api/test/routes.oauthCallback.remotePerServer.test.ts
+++ b/control-api/test/routes.oauthCallback.remotePerServer.test.ts
@@ -7,6 +7,7 @@ import { claimDeleteDynamicClientForResource } from '../src/oauth/dynamicClientS
import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
import { signOAuthState } from '../src/oauth/state.js'
import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import { attachServerToContext } from '../src/services/contextAllowlist.js'
import {
discoverPilot,
installRemoteServer,
@@ -434,6 +435,9 @@ describe('POST /api/v1/internal/mcp-oauth/authorize-url — remote redirect URI'
},
NS
)
+ // Enabled in the member's Context, so the request reaches the redirect-URI
+ // check past the per-user access gate.
+ await attachServerToContext(gateway as never, { name: CONTEXT, namespace: NS }, 'atlassian.v2')
const res = await mint('atlassian.v2')
diff --git a/control-api/test/routes.oauthCallback.userAccessGate.test.ts b/control-api/test/routes.oauthCallback.userAccessGate.test.ts
new file mode 100644
index 000000000..10c55aa3a
--- /dev/null
+++ b/control-api/test/routes.oauthCallback.userAccessGate.test.ts
@@ -0,0 +1,138 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import { signOAuthState } from '../src/oauth/state.js'
+import { createOAuthCallbackRouter } from '../src/routes/external/oauthCallback.js'
+import { memberOf, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
+import { MockGateway } from './mockGateway.js'
+
+/**
+ * The per-user (`grantScope: user`) consent callback re-checks access through the
+ * PRODUCTION wiring of `userServerAccessReader` in `createOAuthCallbackRouter`:
+ * some Context the signed user belongs to must allowlist the server. The server's
+ * own `spec.contextRef` is deliberately a Context the user is NOT a member of, so
+ * only the allowlist rule can decide the outcome.
+ *
+ * Contexts are written through the real allowlist writer, membership is the
+ * `user_contexts` read on the mocked pool (the same stand-in the sibling suites
+ * use), and the state is signed by the real signer. The provider token endpoint
+ * is the only network edge: `globalThis.fetch`, which the route wires as its
+ * baked-lane transport.
+ */
+
+const mockPoolQuery = vi.fn()
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },
+}))
+
+const MCP_NS = config.mcpServersNamespace
+const SERVER = 'gdrive'
+const OAUTH_CLIENT_ID = 'google-drive'
+const OWNER_CONTEXT = 'ctx-owner'
+const USER_ID = 'user-7'
+
+async function seedUserScopedOauthServer(gateway: MockGateway): Promise<void> {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: SERVER },
+ spec: {
+ contextRef: OWNER_CONTEXT,
+ auth: { type: 'oauth' },
+ oauth: {
+ id: OAUTH_CLIENT_ID,
+ provider: 'google',
+ clientIdRef: { name: 'google-creds', key: 'client-id' },
+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },
+ scopes: ['https://www.googleapis.com/auth/drive.readonly'],
+ grantScope: 'user',
+ },
+ },
+ },
+ MCP_NS
+ )
+ gateway.seedSecret('google-creds', MCP_NS, {
+ data: {
+ 'client-id': Buffer.from('GOOGLE_CLIENT_ID').toString('base64'),
+ 'client-secret': Buffer.from('GOOGLE_CLIENT_SECRET').toString('base64'),
+ },
+ })
+}
+
+function signedState(): string {
+ return signOAuthState(config.oauthStateHmacSecret, {
+ subjectKind: 'mcp',
+ mcpServerName: SERVER,
+ userId: USER_ID,
+ oauthClientId: OAUTH_CLIENT_ID,
+ grantKind: 'user',
+ background: false,
+ })
+}
+
+function grantWrites(): unknown[][] {
+ return mockPoolQuery.mock.calls.filter(
+ ([sql]) => typeof sql === 'string' && sql.includes('oauth_grants')
+ )
+}
+
+describe('GET /api/v1/oauth-callback/:oauthClientId — per-user access re-check (production wiring)', () => {
+ let gateway: MockGateway
+ let app: express.Express
+ let fetchSpy: ReturnType<typeof vi.spyOn>
+
+ beforeEach(async () => {
+ gateway = new MockGateway(MCP_NS)
+ app = express()
+ app.use('/api/v1', createOAuthCallbackRouter(gateway as never))
+ mockPoolQuery.mockReset()
+ fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation(async () =>
+ Response.json({ access_token: 'AT', refresh_token: 'RT', expires_in: 3600 })
+ )
+ await seedUserScopedOauthServer(gateway)
+ // The server's own Context allowlists it — the user is never a member of it.
+ await seedAllowlistedContext(gateway, OWNER_CONTEXT, [SERVER])
+ })
+
+ afterEach(() => {
+ fetchSpy.mockRestore()
+ })
+
+ function callback() {
+ return request(app)
+ .get(`/api/v1/oauth-callback/${OAUTH_CLIENT_ID}`)
+ .query({ code: 'CODE', state: signedState() })
+ }
+
+ it('403 context_membership_denied when no Context of the user enables the server; no exchange, no grant', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-mine', ['some-other-server'])
+ memberOf(mockPoolQuery, ['ctx-mine'])
+
+ const res = await callback()
+
+ expect(res.status).toBe(403)
+ expect(res.body).toEqual({ error: 'context_membership_denied' })
+ expect(fetchSpy).not.toHaveBeenCalled()
+ expect(grantWrites()).toHaveLength(0)
+ })
+
+ it('200 when a Context of the user enables the server, though not its contextRef; exchanges and writes the user grant', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-business', [SERVER])
+ memberOf(mockPoolQuery, ['ctx-business'])
+
+ const res = await callback()
+
+ expect(res.status).toBe(200)
+ expect(res.text).toContain('source=mcp')
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
+ expect(String(fetchSpy.mock.calls[0][0])).toBe('https://oauth2.googleapis.com/token')
+ const writes = grantWrites()
+ expect(writes).toHaveLength(1)
+ const [sql, params] = writes[0] as [string, unknown[]]
+ expect(sql).toContain('INSERT INTO oauth_grants')
+ expect(params.slice(0, 5)).toEqual(['mcpserver', MCP_NS, SERVER, USER_ID, OAUTH_CLIENT_ID])
+ })
+})
diff --git a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts b/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts
index bb4742908..73da4a66a 100644
--- a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts
+++ b/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts
@@ -58,6 +58,13 @@ vi.mock('../src/db.js', async importActual => {
...actual,
pool: {
query: async (text: string, values?: unknown[]) => {
+ // The consenting user belongs to the Context the install enables the
+ // server in: the per-user callback re-checks that access before the
+ // code exchange. Same membership stand-in as the per-server callback
+ // suite.
+ if (text.includes('FROM user_contexts')) {
+ return { rows: [{ context_id: 'default-context' }], rowCount: 1 }
+ }
if (!dbHolder.target) throw new Error('test database not ready')
return dbHolder.target.query(text, values)
},
diff --git a/control-api/test/services.access.userMcpServerAccess.test.ts b/control-api/test/services.access.userMcpServerAccess.test.ts
new file mode 100644
index 000000000..420beb6e5
--- /dev/null
+++ b/control-api/test/services.access.userMcpServerAccess.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { config } from '../src/config.js'
+import { userHasContextEnablingMcpServer } from '../src/services/access/mcpInvocable.js'
+import { memberOf, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
+import { MockGateway } from './mockGateway.js'
+
+/**
+ * The access rule shared by the per-user OAuth connect gate and its callback:
+ * a user may connect a server iff they belong (user_contexts) to at least one
+ * Context whose `spec.mcpServers` allowlist names it — the same rule invoke and
+ * the catalog apply. Membership comes from `getUserContexts` (mocked at the
+ * pool, so the real SQL runs through it); allowlists are written through the
+ * real allowlist writer onto the gateway fake.
+ */
+
+const mockPoolQuery = vi.fn()
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },
+}))
+
+const MCP_NS = config.mcpServersNamespace
+
+function check(gateway: MockGateway, userId: string, mcpServerName: string): Promise<boolean> {
+ return userHasContextEnablingMcpServer({
+ gateway: gateway as never,
+ mcpServersNamespace: MCP_NS,
+ userId,
+ mcpServerName,
+ })
+}
+
+describe('userHasContextEnablingMcpServer', () => {
+ let gateway: MockGateway
+
+ beforeEach(() => {
+ gateway = new MockGateway(MCP_NS)
+ mockPoolQuery.mockReset()
+ })
+
+ it('true when one of the user Contexts allowlists the server', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-owner', ['notion'])
+ await seedAllowlistedContext(gateway, 'ctx-business', ['notion', 'gdrive'])
+ memberOf(mockPoolQuery, ['ctx-business', 'ctx-unrelated'])
+ expect(await check(gateway, 'user-1', 'notion')).toBe(true)
+ const [, params] = mockPoolQuery.mock.calls[0]
+ expect(params).toEqual(['user-1'])
+ })
+
+ it('false when none of the user Contexts allowlists the server', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-a', ['gdrive'])
+ await seedAllowlistedContext(gateway, 'ctx-b', [])
+ memberOf(mockPoolQuery, ['ctx-a', 'ctx-b'])
+ expect(await check(gateway, 'user-1', 'notion')).toBe(false)
+ })
+
+ it('false when the allowlisting Context is one the user is NOT a member of', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-owner', ['notion'])
+ await seedAllowlistedContext(gateway, 'ctx-mine', [])
+ memberOf(mockPoolQuery, ['ctx-mine'])
+ expect(await check(gateway, 'user-1', 'notion')).toBe(false)
+ })
+
+ it('false without listing Contexts when the user belongs to none', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-owner', ['notion'])
+ memberOf(mockPoolQuery, [])
+ const listSpy = vi.spyOn(gateway, 'listResource')
+ expect(await check(gateway, 'user-1', 'notion')).toBe(false)
+ expect(listSpy).not.toHaveBeenCalled()
+ })
+
+ it('membership is read from user_contexts only (team membership does not count)', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-team', ['notion'])
+ memberOf(mockPoolQuery, [])
+ expect(await check(gateway, 'user-1', 'notion')).toBe(false)
+ const sqls = mockPoolQuery.mock.calls.map(([sql]) => String(sql))
+ expect(sqls.some(sql => sql.includes('FROM user_contexts'))).toBe(true)
+ expect(sqls.some(sql => sql.includes('team_contexts'))).toBe(false)
+ })
+
+ it('propagates a Context list failure instead of answering false', async () => {
+ memberOf(mockPoolQuery, ['ctx-a'])
+ vi.spyOn(gateway, 'listResource').mockRejectedValueOnce(new Error('apiserver down'))
+ await expect(check(gateway, 'user-1', 'notion')).rejects.toThrow('apiserver down')
+ })
+})