Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(oauth): fence unsealed legacy grants to the same baked provider (R6-H1)
Diego Zacarias0ee199975746
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 857697a4b..15077dae6 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.678",+ "version": "0.1.679","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.678",+ "version": "0.1.679","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 9350318bb..bdd4a7744 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.678",+ "version": "0.1.679","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/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.tsindex 16c7f7f1e..07727e1ba 100644--- a/control-api/src/oauth/mcpServerOAuthSpec.ts+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts@@ -77,6 +77,31 @@ export interface ResolvedServerOAuth {* identity grant reads are fenced by. Undefined when the object carried none.*/crUid?: string+ /**+ * The CR's `spec.oauth.provider`, present only on the baked lane. It lets the+ * store serve an unsealed (legacy) grant written by a pod without install+ * identity, and only one of this same provider.+ */+ legacyProvider?: string+}++/**+ * OAuth lane of a McpServer. `unknown` is a `source` value no reader recognises;+ * callers that need a decl keep treating it as baked, but it never qualifies for+ * legacy (unsealed) grants.+ */+export type McpServerOAuthLane = 'baked' | 'remote' | 'generic' | 'unknown'++/**+ * The single lane classifier for `spec.oauth.source`: absent (undefined/null) ⇒+ * baked; the literals `'remote'`/`'generic'`; any other value (including `''`) ⇒+ * unknown.+ */+export function readOAuthLane(oauth: McpServerOAuthDecl): McpServerOAuthLane {+ const source = oauth.source+ if (source === undefined || source === null) return 'baked'+ if (source === 'remote' || source === 'generic') return source+ return 'unknown'}/**@@ -103,7 +128,19 @@ export function resolveServerOAuth(server: McpServerOAuthSpecInput): ResolvedSertypeof server.spec?.contextRef === 'string' && server.spec.contextRef.length > 0? server.spec.contextRef: undefined- return { oauthClientId: oauth.id, grantScope, contextRef, crUid: readCrUid(server) }+ const legacyProvider =+ readOAuthLane(oauth) === 'baked' &&+ typeof oauth.provider === 'string' &&+ oauth.provider.length > 0+ ? oauth.provider+ : undefined+ return {+ oauthClientId: oauth.id,+ grantScope,+ contextRef,+ crUid: readCrUid(server),+ ...(legacyProvider ? { legacyProvider } : {}),+ }}/** The coordinates the caller supplies to derive an mcp-server grant key. */@@ -155,6 +192,7 @@ export function buildMcpServerGrantKey(contextId: resolved.contextRef,oauthClientId: resolved.oauthClientId,crUid: resolved.crUid,+ ...(resolved.legacyProvider ? { legacyProvider: resolved.legacyProvider } : {}),}}if (typeof coords.userId !== 'string' || coords.userId.length === 0) return null@@ -166,6 +204,7 @@ export function buildMcpServerGrantKey(userId: coords.userId,oauthClientId: resolved.oauthClientId,crUid: resolved.crUid,+ ...(resolved.legacyProvider ? { legacyProvider: resolved.legacyProvider } : {}),}}@@ -230,7 +269,7 @@ function remoteOAuthSpecIncoherence(oauth: McpServerOAuthDecl): RemoteOAuthSpecI*/export function assertRemoteOAuthSpecCoherent(server: McpServerOAuthSpecInput): void {const oauth = server.spec?.oauth- if (!oauth || oauth.source !== 'remote') return+ if (!oauth || readOAuthLane(oauth) !== 'remote') returnconst reason = remoteOAuthSpecIncoherence(oauth)if (!reason) returnconst name = server.metadata?.name@@ -406,9 +445,10 @@ export function resolveServerOAuthSubject(? server.spec.contextRef: undefinedconst crUid = readCrUid(server)+ const lane = readOAuthLane(oauth)// ─── Remote lane (`source:'remote'`) ─────────────────────────────────────- if (oauth.source === 'remote') {+ if (lane === 'remote') {assertRemoteOAuthSpecCoherent(server)const remote = extractRemoteRouting(oauth)if (!remote) return null@@ -432,7 +472,7 @@ export function resolveServerOAuthSubject(}// ─── Generic self-hosted lane (`source:'generic'`, DEC-28) ────────────────- if (oauth.source === 'generic') {+ if (lane === 'generic') {const generic = extractGenericRouting(oauth)if (!generic) return nullconst secretSource = resolveGenericSecretSource(oauth)diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.tsindex d9254b579..7db0cd972 100644--- a/control-api/src/oauth/store.ts+++ b/control-api/src/oauth/store.ts@@ -38,11 +38,22 @@ export type OAuthOwnerKind = 'recipe' | 'mcpserver'** `crUid` is the installation identity of an mcp-server owner (the live CR's* `metadata.uid`). The row readers ({@link getOAuthGrant}, {@link oauthGrantExists})- * only return an mcp-server row sealed with that uid or unsealed (legacy), and an- * mcp-server key WITHOUT a uid matches nothing: a same-name reinstall gets a new- * uid, so a grant consented against the previous installation stays inert even if- * its teardown never ran. Ignored for the recipe domain. Locks, deletes and- * listings do not apply it (see {@link lockOAuthGrantForRefresh}).+ * apply an installation fence to mcp-server keys:+ * - a key WITHOUT a uid matches nothing;+ * - a row sealed with another uid is invisible: a same-name reinstall gets a new+ * uid, so a SEALED grant consented against the previous installation stays+ * inert even if its teardown never ran;+ * - an unsealed (legacy, `cr_uid IS NULL`) row is visible only when the key+ * carries `legacyProvider` and the row's `provider` equals it. Only pods that+ * predate install identity wrote such rows, and they only spoke the baked+ * lane, so a remote/generic key, a key for another baked provider, or a key+ * built by hand without `legacyProvider` never sees one.+ * Ignored for the recipe domain. Locks, deletes and listings do not apply it (see+ * {@link lockOAuthGrantForRefresh}).+ *+ * `legacyProvider` is the baked `spec.oauth.provider` of the CR the key was built+ * from; absent for every other lane. It is a separate name from the `provider`+ * that refresh inputs carry (the value to WRITE) so a spread never conflates them.*/export type OAuthGrantKey =| {@@ -54,6 +65,7 @@ export type OAuthGrantKey =userId: stringoauthClientId: stringcrUid?: string+ legacyProvider?: string}| {grantKind: 'service'@@ -63,6 +75,7 @@ export type OAuthGrantKey =recipeName: stringoauthClientId: stringcrUid?: string+ legacyProvider?: string}| {grantKind: 'shared'@@ -73,6 +86,7 @@ export type OAuthGrantKey =contextId: stringoauthClientId: stringcrUid?: string+ legacyProvider?: string}/** Resolve the owner domain of a key, defaulting to the recipe domain. */@@ -457,9 +471,13 @@ interface OAuthGrantDbRow {/*** Installation-identity predicate for the row readers, appended to each flavor's- * WHERE with `nextParam` as its placeholder index. Returns null when the key can- * match no row (an mcp-server key without a uid). Unsealed rows (`cr_uid IS NULL`)- * stay visible: a pod that predates install identity writes them during a rollout.+ * WHERE with `nextParam` (and `nextParam + 1`) as its placeholder indexes. Returns+ * null when the key can match no row (an mcp-server key without a uid). A row+ * sealed with the key's uid is always visible. An unsealed (`cr_uid IS NULL`) row+ * is visible only to a key carrying `legacyProvider`, and only when its `provider`+ * matches: pods that predate install identity wrote it, always on the baked lane,+ * so serving it to another lane or provider would hand its tokens to an endpoint+ * that was never consented to.*/function installIdentityFence(input: OAuthGrantKey,@@ -467,7 +485,13 @@ function installIdentityFence(): { sql: string; params: string[] } | null {if (resolveOwnerKind(input) !== 'mcpserver') return { sql: '', params: [] }if (typeof input.crUid !== 'string' || input.crUid.length === 0) return null- return { sql: ` AND (cr_uid = $${nextParam} OR cr_uid IS NULL)`, params: [input.crUid] }+ if (typeof input.legacyProvider === 'string' && input.legacyProvider.length > 0) {+ return {+ sql: ` AND (cr_uid = $${nextParam} OR (cr_uid IS NULL AND provider = $${nextParam + 1}))`,+ params: [input.crUid, input.legacyProvider],+ }+ }+ return { sql: ` AND cr_uid = $${nextParam}`, params: [input.crUid] }}/**@@ -941,7 +965,9 @@ export async function listRemoteGrantsInProactiveWindow(AND (grant_kind = 'shared' OR (grant_kind = 'user' AND background = true))-- An unsealed (legacy) row has no installation the sweep could check it-- against: the key built from it would match nothing in the fenced reader.- -- It is refreshed only on the reactive path, whose key carries the live uid.+ -- The fenced reader serves an unsealed row only to a baked key of the same+ -- provider, so an unsealed remote/generic row is never refreshed on any+ -- path; reconnecting replaces and seals it.AND cr_uid IS NOT NULLORDER BY recipe_namespace, recipe_name, oauth_client_id, grant_kind,user_id NULLS FIRST, context_id NULLS FIRST`,diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.tsindex 604f19c2d..31c9710cb 100644--- a/control-api/src/oauth/tokenHelper.ts+++ b/control-api/src/oauth/tokenHelper.ts@@ -19,7 +19,12 @@ import {isKnownOAuthProvider,parseRemoteTokenResponse,} from './providers.js'-import { type OAuthGrantKey, getOAuthGrant, refreshOAuthGrantTokens } from './store.js'+import {+ type OAuthGrantKey,+ getOAuthGrant,+ refreshOAuthGrantTokens,+ resolveOwnerKind,+} from './store.js'/*** Fetch the current access token for a grant (user or service), refreshing on@@ -140,6 +145,17 @@ export async function getAccessToken(const decl = recipe.spec?.oauthClients?.find(c => c.id === input.oauthClientId)if (!decl) return { kind: 'unknown_oauth_client' }+ // Only pods without install identity wrote unsealed rows, and those only spoke+ // the baked lane. The owner CR is re-read here, after the caller built the key,+ // so it may now be another lane or provider; refreshing would send the legacy+ // refresh token to an endpoint nobody consented to. Same rule as the store's+ // reader fence, applied to the CR as it is now.+ if (resolveOwnerKind(input) === 'mcpserver' && grant.crUid === undefined) {+ if (decl.remote || decl.generic || decl.provider !== grant.provider) {+ return { kind: 'no_grant' }+ }+ }+// Remote lane (`source:'remote'`): discovery-derived refresh over the IP-pinned// transport (DEC-17), public token client, credentials per `secretSource`. The// baked provider-adapter path is below (unchanged).diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex f4d9b4653..16115e619 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -19,6 +19,7 @@ import {assertRemoteOAuthSpecCoherent,buildMcpServerGrantKey,readCrUid,+ readOAuthLane,resolveServerOAuth,resolveServerOAuthSubject,} from '../oauth/mcpServerOAuthSpec.js'@@ -98,11 +99,12 @@ export function normalizeMcpServerOwnerDecl(): RecipeWithOAuthClients | null {const oauth = server.spec?.oauthif (!oauth) return null+ const lane = readOAuthLane(oauth)// Remote lane (`source:'remote'`): delegate to the SHARED subject resolver so the// refresh reader reads the remote client (public / DCR / pre-registered)// IDENTICALLY to the mint + callback (D4 — no drift). The remote decl carries the// pinned routing + secretSource that `getAccessToken` branches on.- if (oauth.source === 'remote') {+ if (lane === 'remote') {const resolved = resolveServerOAuthSubject(server)if (!resolved) return nullreturn { metadata: ownerMetadata(server), spec: { oauthClients: [resolved.decl] } }@@ -111,7 +113,7 @@ export function normalizeMcpServerOwnerDecl(// subject resolver (D4 — no drift with mint + callback) so the refresh reader// gets the pinned `generic` routing + secretSource that `getAccessToken`// branches on.- if (oauth.source === 'generic') {+ if (lane === 'generic') {const resolved = resolveServerOAuthSubject(server)if (!resolved) return nullreturn { metadata: ownerMetadata(server), spec: { oauthClients: [resolved.decl] } }diff --git a/control-api/test/fixtures/legacyOAuthGrant.ts b/control-api/test/fixtures/legacyOAuthGrant.tsnew file mode 100644index 000000000..738ab0eff--- /dev/null+++ b/control-api/test/fixtures/legacyOAuthGrant.ts@@ -0,0 +1,297 @@+/**+ * Fixtures for unsealed (legacy, `cr_uid IS NULL`) mcp-server grants and for the+ * same-name reinstalls that meet them.+ *+ * Every artefact comes from its real producer (T1):+ * - CRs are created in the `MockGateway` (which assigns each installation its+ * uid, as the apiserver does). Their `spec.oauth` comes from the install+ * builders (`buildGenericOAuthSpec`, `buildRemoteOAuthSpec` over a real+ * `discoverRemoteOAuth` result); baked specs are the CRD shape the registry+ * writes (`id` + `provider` + both refs).+ * - Legacy rows are written by the real consent callback (`handleOAuthCallback`),+ * so `provider` is whatever `exchangeAuthCode` persists. The only thing+ * simulated is the pod that predates install identity: its subject reader+ * never read `metadata.uid`, so the callback persists `cr_uid` NULL.+ * - Reader keys come from `resolveServerOAuth` + `buildMcpServerGrantKey` over+ * the CR the gateway returns.+ */+import { vi } from 'vitest'+import { config } from '../../src/config.js'+import type { DbClient } from '../../src/db.js'+import type { PinnedTransport } from '../../src/http/pinnedFetch.js'+import { type McpServerOAuthSubject, handleOAuthCallback } from '../../src/oauth/callback.js'+import { type DiscoveryResult, discoverRemoteOAuth } from '../../src/oauth/discovery.js'+import {+ type McpServerOAuthSpecInput,+ buildMcpServerGrantKey,+ resolveServerOAuth,+ resolveServerOAuthSubject,+} from '../../src/oauth/mcpServerOAuthSpec.js'+import { signOAuthState } from '../../src/oauth/state.js'+import type { OAuthGrantKey } from '../../src/oauth/store.js'+import { buildGenericOAuthSpec } from '../../src/routes/admin/registryGenericOauth.js'+import { buildRemoteOAuthSpec } from '../../src/routes/admin/remoteMcp.js'+import type { MockGateway } from '../mockGateway.js'+import { PILOTS, makeDiscoveryTransport } from './remoteOAuthDiscovery.js'++export const NS = config.mcpServersNamespace+export const CONTEXT = 'ctx-legacy'+/** The `oauth.id` every installation of the colliding server declares. */+export const OAUTH_ID = 'shared-client'+export const VALIDATED_IP = '93.184.216.34'+export const GENERIC_TOKEN_ENDPOINT = 'https://idp.example.com/token'++const STATE_SECRET = 'legacy-grant-fixture-state-secret-0123456789'++export type ServerCR = McpServerOAuthSpecInput & { metadata: { uid: string; name: string } }+export type OAuthSpec = Record<string, unknown>++/** Baked `spec.oauth`: a platform provider adapter with K8s client credentials. */+export function bakedOAuth(provider: string, grantScope: 'user' | 'context'): OAuthSpec {+ return {+ id: OAUTH_ID,+ provider,+ clientIdRef: { name: `${provider}-creds`, key: 'client-id' },+ clientSecretRef: { name: `${provider}-creds`, key: 'client-secret' },+ scopes: ['read'],+ grantScope,+ }+}++/** Generic self-hosted `spec.oauth`, public client, exactly as the install writes it. */+export function genericOAuth(grantScope: 'user' | 'context'): OAuthSpec {+ return buildGenericOAuthSpec({+ id: OAUTH_ID,+ knobs: {+ authorizationEndpoint: 'https://idp.example.com/authorize',+ tokenEndpoint: GENERIC_TOKEN_ENDPOINT,+ tokenRequestFormat: 'form',+ tokenAuthMethod: 'body',+ scopeSeparator: 'space',+ sendScope: true,+ usePkce: true,+ includeResponseType: true,+ supportsRefresh: true,+ },+ scopes: ['read'],+ grantScope,+ })+}++/**+ * A real discovery result for a remote MCP server. The sentry pilot advertises+ * RFC 9207 `iss`, which remote consent requires.+ */+export async function remoteDiscovery(): Promise<DiscoveryResult> {+ const outcome = await discoverRemoteOAuth(PILOTS.sentry.mcpUrl, {+ transport: makeDiscoveryTransport(PILOTS.sentry),+ resolveDns: async () => [VALIDATED_IP],+ })+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)+ return outcome.result+}++/** Remote public `spec.oauth` whose client id collides with the legacy one. */+export function remoteOAuth(discovery: DiscoveryResult, grantScope: 'user' | 'context'): OAuthSpec {+ const oauth = buildRemoteOAuthSpec(discovery, {+ clientMode: 'public',+ grantScope,+ cimdClientId: OAUTH_ID,+ })+ if (oauth.supportsRefresh !== true) throw new Error('fixture: remote pilot must support refresh')+ return oauth as unknown as OAuthSpec+}++/** Install `name` with `oauth` and return the CR as the gateway stores it. */+export async function installServer(+ gateway: MockGateway,+ name: string,+ oauth: OAuthSpec+): Promise<ServerCR> {+ await gateway.createResource(+ 'mcpservers',+ {+ metadata: { name },+ spec: {+ enabled: true,+ contextRef: CONTEXT,+ auth: { type: 'oauth' },+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },+ oauth,+ },+ },+ NS+ )+ return (await gateway.getResource('mcpservers', name, NS)) as ServerCR+}++/** Uninstall `name` (without purging grants) and install it again with `oauth`. */+export async function reinstallServer(+ gateway: MockGateway,+ name: string,+ oauth: OAuthSpec+): Promise<ServerCR> {+ await gateway.deleteResource('mcpservers', name, NS)+ return installServer(gateway, name, oauth)+}++/** The reader key exactly as the token broker / grant gate / sweep derive it. */+export function readerKey(server: ServerCR, userId?: string): OAuthGrantKey {+ const resolved = resolveServerOAuth(server)+ if (!resolved) throw new Error('fixture: server did not resolve as OAuth')+ const key = buildMcpServerGrantKey(resolved, {+ mcpServerName: server.metadata.name,+ mcpServersNamespace: NS,+ userId,+ })+ if (!key) throw new Error('fixture: no grant key')+ return key+}++export interface ConsentTokens {+ accessToken: string+ refreshToken: string+ /** Seconds; anything under the 60s reactive buffer is already due for refresh. */+ expiresIn: number+}++function tokenResponse(tokens: ConsentTokens) {+ return {+ access_token: tokens.accessToken,+ refresh_token: tokens.refreshToken,+ expires_in: tokens.expiresIn,+ token_type: 'Bearer',+ }+}++function consentInput(name: string, userId: string) {+ return {+ oauthClientId: OAUTH_ID,+ code: `code-${name}-${userId}`,+ state: signOAuthState(STATE_SECRET, {+ subjectKind: 'mcp',+ mcpServerName: name,+ userId,+ oauthClientId: OAUTH_ID,+ grantKind: 'user',+ background: false,+ }),+ redirectUri: `https://control.example.com/api/v1/oauth-callback/${OAUTH_ID}`,+ }+}++/**+ * Consent through the real callback as a pod WITHOUT install identity did: the CR+ * currently in the gateway (baked) is read as that pod read it, without its uid.+ * The flavor follows the CR's `grantScope` (user → `upsertOAuthGrant`, context →+ * `bootstrapSharedOAuthGrant` with `userId` as bootstrapper).+ */+export async function legacyConsent(+ db: DbClient,+ encryptionKey: Buffer,+ gateway: MockGateway,+ name: string,+ userId: string,+ tokens: ConsentTokens+): Promise<void> {+ const fetchFn = vi.fn(+ async () =>+ ({+ ok: true,+ status: 200,+ json: async () => tokenResponse(tokens),+ text: async () => JSON.stringify(tokenResponse(tokens)),+ }) as Response+ )+ const result = await handleOAuthCallback(consentInput(name, userId), {+ db,+ recipeReader: { read: async () => null },+ secretReader: { read: async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' }) },+ mcpServerReader: {+ async read(serverName): Promise<McpServerOAuthSubject | null> {+ const cr = (await gateway.getResource('mcpservers', serverName, NS)) as ServerCR+ const { uid: _preIdentityPodNeverReadIt, ...metadata } = cr.metadata+ const resolved = resolveServerOAuthSubject({ ...cr, metadata })+ return resolved ? { namespace: NS, ...resolved } : null+ },+ },+ userContextsReader: async () => ({ contextIds: [CONTEXT] }),+ fetchFn: fetchFn as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey,+ })+ if (result.kind !== 'ok') throw new Error(`fixture: legacy consent failed: ${result.kind}`)+ if (fetchFn.mock.calls.length !== 1) throw new Error('fixture: baked exchange did not run')+}++/**+ * Consent through the real callback as this build does (the production subject+ * reader, uid included) on the CR currently in the gateway. Remote/generic+ * exchanges go through `transport`; a baked exchange would use no transport.+ */+export async function currentConsent(+ db: DbClient,+ encryptionKey: Buffer,+ gateway: MockGateway,+ name: string,+ userId: string,+ transport: PinnedTransport,+ /** RFC 9207 `iss` of the authorization response; the remote lane requires it. */+ iss?: string+): Promise<void> {+ const result = await handleOAuthCallback(+ { ...consentInput(name, userId), iss },+ {+ db,+ recipeReader: { read: async () => null },+ secretReader: { read: async () => ({}) },+ mcpServerReader: {+ async read(serverName): Promise<McpServerOAuthSubject | null> {+ const cr = (await gateway.getResource('mcpservers', serverName, NS)) as ServerCR+ const resolved = resolveServerOAuthSubject(cr)+ return resolved ? { namespace: NS, ...resolved } : null+ },+ },+ userContextsReader: async () => ({ contextIds: [CONTEXT] }),+ fetchFn: (async () => {+ throw new Error('remote/generic consent must not use fetchFn')+ }) as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey,+ resolveDns: async () => [VALIDATED_IP],+ pinnedTransport: transport,+ }+ )+ if (result.kind !== 'ok') throw new Error(`fixture: consent failed: ${result.kind}`)+}++export interface RecordedPost {+ url: string+ body: string+}++/**+ * The network edge of `pinnedFetch` for remote/generic token endpoints: records+ * every POST and answers with fresh tokens, the way an AS that still accepts the+ * presented refresh token would.+ */+export function recordingTokenTransport(response: { accessToken: string; refreshToken: string }): {+ transport: PinnedTransport+ posts: RecordedPost[]+} {+ const posts: RecordedPost[] = []+ const transport: PinnedTransport = async input => {+ posts.push({ url: input.url, body: input.body ?? '' })+ return {+ status: 200,+ headers: { 'content-type': 'application/json' },+ bodyText: JSON.stringify({+ access_token: response.accessToken,+ refresh_token: response.refreshToken,+ expires_in: 3600,+ token_type: 'Bearer',+ }),+ }+ }+ return { transport, posts }+}diff --git a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.tsindex 5b37eae8f..9f44ae575 100644--- a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts+++ b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts@@ -169,17 +169,15 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (recrUid: U,})).toBe(false)- expect(- await oauthGrantExists(db, {- grantKind: 'user',- ownerKind: 'mcpserver',- recipeNamespace: NS,- recipeName: 'gdrive',- userId: 'user-legacy',- oauthClientId: 'google-drive',- crUid: U,- })- ).toBe(false)+ // The unsealed row is checked on the table itself: a fenced read without the+ // row's provider would be `false` whether or not the purge ran.+ const legacyRows = await db.query(+ `SELECT 1 FROM oauth_grants+ WHERE owner_kind = 'mcpserver' AND recipe_namespace = $1 AND recipe_name = 'gdrive'+ AND user_id = 'user-legacy'`,+ [NS]+ )+ expect(legacyRows.rows).toHaveLength(0)// … the DIFFERENT-uid gdrive grant (the reinstall's) SURVIVES (R3-H5 fence) …expect(await oauthGrantExists(db, {diff --git a/control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts b/control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.tsnew file mode 100644index 000000000..2796e439d--- /dev/null+++ b/control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts@@ -0,0 +1,392 @@+/**+ * An unsealed (legacy, `cr_uid IS NULL`) mcp-server grant was written by a pod+ * without install identity, and such pods only spoke the baked lane. A same-name+ * reinstall that keeps the `oauth.id` but changes lane (remote / generic) or+ * baked provider must never be served that row — neither its still-valid access+ * token nor a refresh that sends its refresh token to the new installation's+ * endpoint. A baked reinstall of the SAME provider keeps being served (the rollout+ * path the unsealed rows exist for).+ *+ * Two control points, both covered here:+ * - the store reader fence (`getOAuthGrant` / `oauthGrantExists`), keyed by the+ * CR the caller read;+ * - the refresh engine, which re-reads the CR right before refreshing, so a CR+ * replaced after the key was built is judged as it is now.+ *+ * Observable (T4): reader results, the `getAccessTokenReactive` result, every POST+ * reaching a token endpoint (the pinned transport for remote/generic, `fetchFn`+ * for baked adapters), and the persisted rows.+ *+ * Real producers (T1): see `fixtures/legacyOAuthGrant.ts`.+ *+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \+ * test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts+ */+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { randomUUID } from 'node:crypto'+import { Pool } from 'pg'+import { config } from '../src/config.js'+import type { DbClient, DbTransactionClient } from '../src/db.js'+import { initDb } from '../src/db.js'+import type { DiscoveryResult } from '../src/oauth/discovery.js'+import { decryptOAuthSecret, deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { getAccessTokenReactive } from '../src/oauth/reactiveTokenHelper.js'+import {+ type OAuthGrantKey,+ getOAuthGrant,+ listRemoteGrantsInProactiveWindow,+ oauthGrantExists,+} from '../src/oauth/store.js'+import { type McpServerResource, normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'+import {+ NS,+ type OAuthSpec,+ VALIDATED_IP,+ bakedOAuth,+ currentConsent,+ genericOAuth,+ installServer,+ legacyConsent,+ readerKey,+ recordingTokenTransport,+ reinstallServer,+ remoteDiscovery,+ remoteOAuth,+} from './fixtures/legacyOAuthGrant.js'+import { MockGateway } from './mockGateway.js'++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)+const LEGACY_PROVIDER = 'google'+const LEGACY_AT = 'LEGACY-AT-google'+const LEGACY_RT = 'LEGACY-RT-google'+const USER = 'alice'+type Flavor = 'user' | 'context'+const FLAVORS: Flavor[] = ['user', 'context']++describeRealPostgres(+ 'unsealed legacy grants fenced to the same baked provider (real Postgres)',+ () => {+ const database = `control_api_legacy_lane_${randomUUID().replace(/-/g, '')}`+ let adminPool: Pool+ let dbPool: Pool+ let db: DbClient+ let discovery: DiscoveryResult++ 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) }+ discovery = await remoteDiscovery()+ })++ 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()+ }+ })++ beforeEach(async () => {+ await dbPool.query('DELETE FROM oauth_grants')+ })++ const lanes: Record<string, (flavor: Flavor) => OAuthSpec> = {+ generic: flavor => genericOAuth(flavor),+ remote: flavor => remoteOAuth(discovery, flavor),+ 'baked slack': flavor => bakedOAuth('slack', flavor),+ }++ const serverName = (label: string) =>+ `legacy-${label.replace(/[^a-z]/g, '')}-${randomUUID().slice(0, 8)}`++ /** Baked `google` installation consented by a pre-identity pod. */+ async function seedLegacyGrant(+ name: string,+ flavor: Flavor,+ expiresIn: number+ ): Promise<MockGateway> {+ const gateway = new MockGateway(NS)+ await installServer(gateway, name, bakedOAuth(LEGACY_PROVIDER, flavor))+ await legacyConsent(db, KEY, gateway, name, USER, {+ accessToken: LEGACY_AT,+ refreshToken: LEGACY_RT,+ expiresIn,+ })+ const rows = await rowsOf(name)+ expect(rows).toEqual([{ provider: LEGACY_PROVIDER, crUid: null, refreshToken: LEGACY_RT }])+ return gateway+ }++ /** The table as it is, bypassing every reader fence. */+ async function rowsOf(name: string) {+ const { rows } = await dbPool.query(+ `SELECT provider, cr_uid, refresh_token_encrypted FROM oauth_grants+ WHERE owner_kind = 'mcpserver' AND recipe_name = $1`,+ [name]+ )+ return rows.map(r => ({+ provider: r.provider as string,+ crUid: r.cr_uid as string | null,+ refreshToken: r.refresh_token_encrypted+ ? decryptOAuthSecret(KEY, r.refresh_token_encrypted as string)+ : null,+ }))+ }++ /**+ * The broker's refresh wiring (`routes/mcpOauth.ts`): the owner re-read from the+ * gateway at refresh time, a real row-locking transaction, and both token-endpoint+ * edges recorded. `beforeEngine` runs after the fast-path read and before the+ * locked engine — where a concurrent reinstall would land.+ */+ function reactive(+ gateway: MockGateway,+ key: OAuthGrantKey,+ beforeEngine?: () => Promise<void>+ ) {+ const { transport, posts } = recordingTokenTransport({+ accessToken: 'NEW-AT',+ refreshToken: 'NEW-RT',+ })+ const fetchFn = vi.fn(+ async () =>+ ({+ ok: true,+ status: 200,+ json: async () => ({ access_token: 'NEW-AT', expires_in: 3600 }),+ text: async () => '{"access_token":"NEW-AT","expires_in":3600}',+ }) as Response+ )+ const run = () =>+ getAccessTokenReactive(+ { ...key, requireBackground: false },+ {+ db,+ recipeReader: {+ read: async name =>+ normalizeMcpServerOwnerDecl(+ (await gateway.getResource('mcpservers', name, NS)) as McpServerResource+ ),+ },+ secretReader: { read: async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' }) },+ fetchFn: fetchFn as unknown as typeof fetch,+ encryptionKey: KEY,+ resolveDns: async () => [VALIDATED_IP],+ pinnedTransport: transport,+ runInTransaction: async <T>(+ work: (txDb: DbTransactionClient) => Promise<T>+ ): Promise<T> => {+ await beforeEngine?.()+ const client = await dbPool.connect()+ try {+ await client.query('BEGIN')+ const txDb = {+ query: (t: string, v?: unknown[]) => client.query(t, v),+ } as unknown as DbTransactionClient+ const out = await work(txDb)+ await client.query('COMMIT')+ return out+ } catch (err) {+ await client.query('ROLLBACK')+ throw err+ } finally {+ client.release()+ }+ },+ }+ )+ return { run, posts, fetchFn }+ }++ /** Every refresh-token exchange that left the process, on either edge. */+ function spentRefreshTokens(+ posts: { body: string }[],+ fetchFn: ReturnType<typeof vi.fn>+ ): string[] {+ const fromTransport = posts.map(p => new URLSearchParams(p.body).get('refresh_token') ?? '')+ const fromFetch = fetchFn.mock.calls.map(call => {+ const init = call[1] as { body?: unknown } | undefined+ return new URLSearchParams(String(init?.body ?? '')).get('refresh_token') ?? ''+ })+ return [...fromTransport, ...fromFetch]+ }++ describe.each(FLAVORS)('store reader fence (%s flavor)', flavor => {+ it.each(Object.keys(lanes))(+ 'a %s reinstall with the same oauth.id does not see the legacy row',+ async lane => {+ const name = serverName(lane)+ const gateway = await seedLegacyGrant(name, flavor, 3600)+ const live = await reinstallServer(gateway, name, lanes[lane](flavor))+ const key = readerKey(live, flavor === 'user' ? USER : undefined)++ expect(await getOAuthGrant(db, KEY, key)).toBeNull()+ expect(await oauthGrantExists(db, key)).toBe(false)+ // The row is still there: invisible, not destroyed.+ expect(await rowsOf(name)).toHaveLength(1)+ }+ )++ it('a baked reinstall of the same provider keeps seeing the legacy row', async () => {+ const name = serverName('same')+ const gateway = await seedLegacyGrant(name, flavor, 3600)+ const live = await reinstallServer(gateway, name, bakedOAuth(LEGACY_PROVIDER, flavor))+ const key = readerKey(live, flavor === 'user' ? USER : undefined)++ const row = await getOAuthGrant(db, KEY, key)+ expect(row?.accessToken).toBe(LEGACY_AT)+ expect(row?.crUid).toBeUndefined()+ expect(await oauthGrantExists(db, key)).toBe(true)+ })+ })++ describe.each(FLAVORS)('reactive refresh of a legacy row (%s flavor)', flavor => {+ it.each(['generic', 'remote'])(+ 'a %s reinstall gets no_grant and the legacy refresh token never leaves',+ async lane => {+ const name = serverName(lane)+ // Access token already due: the broker would go straight to a refresh.+ const gateway = await seedLegacyGrant(name, flavor, 1)+ const live = await reinstallServer(gateway, name, lanes[lane](flavor))+ const { run, posts, fetchFn } = reactive(+ gateway,+ readerKey(live, flavor === 'user' ? USER : undefined)+ )++ const result = await run()+ expect(spentRefreshTokens(posts, fetchFn)).toEqual([])+ expect(result).toEqual({ kind: 'no_grant' })+ expect(await rowsOf(name)).toEqual([+ { provider: LEGACY_PROVIDER, crUid: null, refreshToken: LEGACY_RT },+ ])+ }+ )+ })++ describe('CR replaced after the key was built (engine re-read)', () => {+ it.each(['generic', 'remote', 'baked slack'])(+ 'a key from a baked google CR, refreshed after the CR became %s: no_grant, nothing POSTed',+ async lane => {+ const name = serverName(lane)+ const gateway = await seedLegacyGrant(name, 'user', 1)+ // The caller read a baked google CR (a same-provider reinstall), so its key+ // legitimately sees the legacy row …+ const read = await reinstallServer(gateway, name, bakedOAuth(LEGACY_PROVIDER, 'user'))+ const key = readerKey(read, USER)+ expect(await oauthGrantExists(db, key)).toBe(true)+ // … and the server is reinstalled in another lane before the refresh runs.+ const { run, posts, fetchFn } = reactive(gateway, key, async () => {+ await reinstallServer(gateway, name, lanes[lane]('user'))+ })++ const result = await run()+ expect(spentRefreshTokens(posts, fetchFn)).toEqual([])+ expect(result).toEqual({ kind: 'no_grant' })+ expect(await rowsOf(name)).toEqual([+ { provider: LEGACY_PROVIDER, crUid: null, refreshToken: LEGACY_RT },+ ])+ }+ )++ it('a same-provider baked CR still refreshes the legacy row (rollout path intact)', async () => {+ const name = serverName('rollout')+ const gateway = await seedLegacyGrant(name, 'user', 1)+ const live = await reinstallServer(gateway, name, bakedOAuth(LEGACY_PROVIDER, 'user'))+ const { run, posts, fetchFn } = reactive(gateway, readerKey(live, USER))++ expect(await run()).toMatchObject({ kind: 'ok', accessToken: 'NEW-AT' })+ expect(spentRefreshTokens(posts, fetchFn)).toEqual([LEGACY_RT])+ expect(posts).toEqual([])+ const rows = await rowsOf(name)+ expect(rows).toEqual([{ provider: LEGACY_PROVIDER, crUid: null, refreshToken: LEGACY_RT }])+ })+ })++ describe('unrecognised spec.oauth.source', () => {+ it.each(['foo', ''])(+ "source=%j never sees nor refreshes a legacy row, even carrying the row's provider",+ async source => {+ const name = serverName(`unknown${source}`)+ const gateway = await seedLegacyGrant(name, 'user', 1)+ const live = await reinstallServer(gateway, name, {+ ...bakedOAuth(LEGACY_PROVIDER, 'user'),+ source,+ })+ const key = readerKey(live, USER)++ expect(await getOAuthGrant(db, KEY, key)).toBeNull()+ expect(await oauthGrantExists(db, key)).toBe(false)+ const { run, posts, fetchFn } = reactive(gateway, key)+ const result = await run()+ expect(spentRefreshTokens(posts, fetchFn)).toEqual([])+ expect(result).toEqual({ kind: 'no_grant' })+ }+ )+ })++ it('reconnecting on the new lane replaces the legacy row and seals it', async () => {+ const name = serverName('reconnect')+ const gateway = await seedLegacyGrant(name, 'user', 3600)+ const live = await reinstallServer(gateway, name, genericOAuth('user'))+ const { transport, posts } = recordingTokenTransport({+ accessToken: 'GENERIC-AT',+ refreshToken: 'GENERIC-RT',+ })++ await currentConsent(db, KEY, gateway, name, USER, transport)++ expect(posts).toHaveLength(1)+ expect(await rowsOf(name)).toEqual([+ { provider: 'generic', crUid: live.metadata.uid, refreshToken: 'GENERIC-RT' },+ ])+ const row = await getOAuthGrant(db, KEY, readerKey(live, USER))+ expect(row?.accessToken).toBe('GENERIC-AT')+ expect(row?.refreshToken).toBe('GENERIC-RT')+ expect(row?.crUid).toBe(live.metadata.uid)+ })++ it('the proactive sweep keys (no legacyProvider) still read sealed remote/generic rows', async () => {+ const gateway = new MockGateway(NS)+ const genericName = serverName('sealedgeneric')+ const remoteName = serverName('sealedremote')+ const genericCr = await installServer(gateway, genericName, genericOAuth('context'))+ const remoteCr = await installServer(gateway, remoteName, remoteOAuth(discovery, 'context'))+ const { transport } = recordingTokenTransport({ accessToken: 'AT', refreshToken: 'RT' })+ await currentConsent(db, KEY, gateway, genericName, USER, transport)+ await currentConsent(db, KEY, gateway, remoteName, USER, transport, discovery.issForCallback)++ const keys = await listRemoteGrantsInProactiveWindow(db, {+ reactiveBufferMs: 0,+ proactiveBufferMs: 7_200_000,+ })+ expect(keys.map(k => [k.recipeName, k.crUid]).sort()).toEqual(+ [+ [genericName, genericCr.metadata.uid],+ [remoteName, remoteCr.metadata.uid],+ ].sort()+ )+ for (const key of keys) {+ expect(key).not.toHaveProperty('legacyProvider')+ expect((await getOAuthGrant(db, KEY, key))?.accessToken).toBe('AT')+ }+ })+ }+)diff --git a/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.generic.test.tsindex ad960946a..d63c3ae2b 100644--- a/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts+++ b/control-api/test/oauth.mcpServerOAuthSpec.generic.test.ts@@ -151,6 +151,8 @@ describe('resolveServerOAuthSubject — generic lane (DEC-28)', () => {grantScope: 'context',contextRef: 'ctx-a',})+ // Only a baked CR may see unsealed legacy grants.+ expect(r).not.toHaveProperty('legacyProvider')})})diff --git a/control-api/test/oauth.mcpServerOAuthSpec.lane.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.lane.test.tsnew file mode 100644index 000000000..1f5616dcf--- /dev/null+++ b/control-api/test/oauth.mcpServerOAuthSpec.lane.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest'+import {+ type McpServerOAuthDecl,+ readOAuthLane,+ resolveServerOAuth,+ resolveServerOAuthSubject,+} from '../src/oauth/mcpServerOAuthSpec.js'+import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'+import { bakedOAuth, genericOAuth } from './fixtures/legacyOAuthGrant.js'++/**+ * One classifier decides the OAuth lane of a McpServer for every reader. Only a+ * baked CR (no `source`) carries `legacyProvider`, the only thing that lets a key+ * see unsealed legacy grants. An unrecognised `source` keeps the baked decl shape+ * for the consent/refresh readers (unchanged behaviour) but never qualifies.+ */++const server = (oauth: Record<string, unknown>) => ({+ metadata: { uid: 'uid-1', name: 'srv' },+ spec: { contextRef: 'ctx-1', oauth },+})++describe('readOAuthLane', () => {+ it.each<[unknown, string]>([+ [undefined, 'baked'],+ [null, 'baked'],+ ['remote', 'remote'],+ ['generic', 'generic'],+ ['', 'unknown'],+ ['foo', 'unknown'],+ ['Remote', 'unknown'],+ [42, 'unknown'],+ ])('source=%j → %s', (source, lane) => {+ expect(readOAuthLane({ source } as McpServerOAuthDecl)).toBe(lane)+ })+})++describe('legacyProvider on the resolved coordinate', () => {+ it('a baked CR carries its provider', () => {+ expect(resolveServerOAuth(server(bakedOAuth('google', 'user')))?.legacyProvider).toBe('google')+ })++ it('a generic CR carries none', () => {+ expect(resolveServerOAuth(server(genericOAuth('user')))).not.toHaveProperty('legacyProvider')+ })++ it.each(['', 'foo'])('source=%j carries none, even with a provider on the CR', source => {+ const resolved = resolveServerOAuth(server({ ...bakedOAuth('google', 'user'), source }))+ expect(resolved).not.toBeNull()+ expect(resolved).not.toHaveProperty('legacyProvider')+ })++ it.each(['', 'foo'])(+ 'source=%j keeps the baked decl in the consent and refresh readers',+ source => {+ const oauth = { ...bakedOAuth('google', 'user'), source }+ const baked = bakedOAuth('google', 'user')+ expect(resolveServerOAuthSubject(server(oauth))?.decl).toEqual(+ resolveServerOAuthSubject(server(baked))?.decl+ )+ expect(normalizeMcpServerOwnerDecl(server(oauth))?.spec?.oauthClients).toEqual(+ normalizeMcpServerOwnerDecl(server(baked))?.spec?.oauthClients+ )+ }+ )+})diff --git a/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.tsindex 758451ed9..0cfe8873b 100644--- a/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts+++ b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts@@ -135,6 +135,8 @@ describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)})const r = resolveServerOAuth(serverFrom(oauth as unknown as Record<string, unknown>))expect(r).toEqual({ oauthClientId: CIMD_SELF, grantScope: 'context', contextRef: 'ctx-a' })+ // Only a baked CR may see unsealed legacy grants.+ expect(r).not.toHaveProperty('legacyProvider')})})diff --git a/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.tsindex 71c701caa..28262eb4e 100644--- a/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts+++ b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts@@ -228,7 +228,16 @@ describeRealPostgres('teardownMcpServerOAuthState — fenced by cr_uid (real PoscrUid,})expect(await exists('user-u', U)).toBe(false)- expect(await exists('user-legacy', U)).toBe(false)+ // No reader key sees an unsealed row unless it names the row's provider, so the+ // legacy row is checked on the table itself: a fenced read would be `false`+ // whether or not the purge ran.+ const legacyRows = await db.query(+ `SELECT 1 FROM oauth_grants+ WHERE owner_kind = 'mcpserver' AND recipe_namespace = $1 AND recipe_name = $2+ AND user_id = 'user-legacy'`,+ [NS, name]+ )+ expect(legacyRows.rows).toHaveLength(0)// The reinstall's grant (uid U′) survives (R3-H5).expect(await exists('user-reinstall', Uprime)).toBe(true)})diff --git a/control-api/test/oauth.store.sharedGrants.test.ts b/control-api/test/oauth.store.sharedGrants.test.tsindex 3de700bb6..fc7922a9a 100644--- a/control-api/test/oauth.store.sharedGrants.test.ts+++ b/control-api/test/oauth.store.sharedGrants.test.ts@@ -2,6 +2,7 @@ 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 { buildMcpServerGrantKey, resolveServerOAuth } from '../src/oauth/mcpServerOAuthSpec.js'import {bootstrapSharedOAuthGrant,deleteOAuthGrant,@@ -39,9 +40,28 @@ const SHARED_KEY = {oauthClientId: 'google-drive',}-// A reader key as `buildMcpServerGrantKey` produces it: it carries the live CR uid.+// A reader key of a non-baked lane: it carries the live CR uid but no legacyProvider.const SHARED_READ_KEY = { ...SHARED_KEY, crUid: 'uid-1' }+/** Reader key derived from a baked CR, exactly as the broker/gate/sweep build it. */+function bakedReaderKey(grantScope: 'user' | 'context', userId?: string) {+ const resolved = resolveServerOAuth({+ metadata: { uid: 'uid-1', name: 'gdrive' },+ spec: {+ contextRef: 'ctx-9',+ oauth: { id: 'google-drive', provider: 'google', grantScope },+ },+ })+ if (!resolved) throw new Error('fixture: server did not resolve as OAuth')+ const key = buildMcpServerGrantKey(resolved, {+ mcpServerName: 'gdrive',+ mcpServersNamespace: 'mcp-server',+ userId,+ })+ if (!key) throw new Error('fixture: no grant key')+ return key+}+describe('oauth store — shared (context-identity) grants', () => {it('bootstrapSharedOAuthGrant issues INSERT … ON CONFLICT DO UPDATE fenced by cr_uid, returns inserted', async () => {const { db, calls } = fakeDb([{ id: 1 }], 1)@@ -163,7 +183,8 @@ describe('oauth store — shared (context-identity) grants', () => {expect(row?.crUid).toBe('uid-1')expect(calls[0].text).toContain("grant_kind = 'shared'")expect(calls[0].text).toContain('context_id = $4')- expect(calls[0].text).toContain('AND (cr_uid = $6 OR cr_uid IS NULL)')+ expect(calls[0].text).toContain('AND cr_uid = $6')+ expect(calls[0].text).not.toContain('cr_uid IS NULL')expect(calls[0].values).toEqual(['mcpserver','mcp-server',@@ -179,7 +200,8 @@ describe('oauth store — shared (context-identity) grants', () => {const exists = await oauthGrantExists(db, SHARED_READ_KEY)expect(exists).toBe(true)expect(calls[0].text).toContain("grant_kind = 'shared'")- expect(calls[0].text).toContain('AND (cr_uid = $6 OR cr_uid IS NULL)')+ expect(calls[0].text).toContain('AND cr_uid = $6')+ expect(calls[0].text).not.toContain('cr_uid IS NULL')expect(calls[0].values).toEqual(['mcpserver','mcp-server',@@ -190,6 +212,27 @@ describe('oauth store — shared (context-identity) grants', () => {])})+ it('a baked reader key also admits unsealed rows of its own provider only (shared)', async () => {+ const key = bakedReaderKey('context')+ for (const read of [+ (db: DbClient) => getOAuthGrant(db, KEY, key),+ (db: DbClient) => oauthGrantExists(db, key),+ ]) {+ const { db, calls } = fakeDb()+ await read(db)+ expect(calls[0].text).toContain('AND (cr_uid = $6 OR (cr_uid IS NULL AND provider = $7))')+ expect(calls[0].values).toEqual([+ 'mcpserver',+ 'mcp-server',+ 'gdrive',+ 'ctx-9',+ 'google-drive',+ 'uid-1',+ 'google',+ ])+ }+ })+it('an mcp-server reader key without a uid matches nothing and issues no query', async () => {const { db, calls } = fakeDb([{ '?column?': 1 }])expect(await oauthGrantExists(db, SHARED_KEY)).toBe(false)@@ -237,7 +280,22 @@ describe('oauth store — owner_kind on user/service ops (recipe domain unchangecrUid: 'uid-1',})expect(calls[0].text).toContain('owner_kind = $1')- expect(calls[0].text).toContain('AND (cr_uid = $6 OR cr_uid IS NULL)')+ expect(calls[0].text).toContain('AND cr_uid = $6')+ expect(calls[0].text).not.toContain('cr_uid IS NULL')+ expect(calls[0].values).toEqual([+ 'mcpserver',+ 'mcp-server',+ 'gdrive',+ 'user-1',+ 'google-drive',+ 'uid-1',+ ])+ })++ it('getOAuthGrant(user) with a baked reader key admits unsealed rows of its provider', async () => {+ const { db, calls } = fakeDb()+ await getOAuthGrant(db, KEY, bakedReaderKey('user', 'user-1'))+ expect(calls[0].text).toContain('AND (cr_uid = $6 OR (cr_uid IS NULL AND provider = $7))')expect(calls[0].values).toEqual(['mcpserver','mcp-server',@@ -245,6 +303,7 @@ describe('oauth store — owner_kind on user/service ops (recipe domain unchange'user-1','google-drive','uid-1',+ 'google',])})diff --git a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.tsnew file mode 100644index 000000000..815764a15--- /dev/null+++ b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts@@ -0,0 +1,212 @@+/**+ * The token broker's fast path, the rpc-proxy grant gate and the grant-existence+ * sweep all read grants through the store reader fence with a key built from the+ * CR they just read. An unsealed (legacy) grant — written by a baked-lane pod+ * without install identity — must not count for a same-name reinstall on another+ * lane that kept the `oauth.id`: no still-valid access token handed to mcp-host+ * for the new server's URL, no "connected" verdict from the gate or the sweep.+ * A baked reinstall of the same provider keeps being served.+ *+ * `POST /mcp-oauth/user-token` runs through the real app against a real Postgres+ * (the store fence is SQL, so it cannot be asserted on a mocked pool).+ *+ * Real producers (T1): see `fixtures/legacyOAuthGrant.ts`.+ *+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \+ * test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { randomUUID } from 'node:crypto'+import { Pool } from 'pg'+import request from 'supertest'+import { createApp } from '../src/app.js'+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 { resolveBatchGrantExistence } from '../src/routes/mcpOauth.js'+import { resolveInvocableMcpServersForContexts } from '../src/services/access/mcpInvocable.js'+import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'+import {+ CONTEXT,+ NS,+ type OAuthSpec,+ bakedOAuth,+ genericOAuth,+ installServer,+ legacyConsent,+ reinstallServer,+} from './fixtures/legacyOAuthGrant.js'+import { MockGateway } from './mockGateway.js'++// The broker reads grants through the app's shared pool; point it at this suite's+// database.+const testDb = vi.hoisted(() => ({ pool: undefined as import('pg').Pool | undefined }))++vi.mock('../src/db.js', async () => {+ const actual = await vi.importActual<typeof import('../src/db.js')>('../src/db.js')+ const current = () => {+ if (!testDb.pool) throw new Error('test pool not initialised')+ return testDb.pool+ }+ return {+ ...actual,+ pool: {+ query: (text: string, values?: unknown[]) => current().query(text, values),+ connect: () => current().connect(),+ },+ }+})++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,+ backendAvailable: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))++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)+const LEGACY_AT = 'LEGACY-AT-google'+const USER = 'alice'+type Flavor = 'user' | 'context'++function controlToken(): string {+ return issueMcpHostControlJwt('mcp-host', 'standalone', ['mcp-host/standalone'], {+ scopes: ['oauth:user-token'],+ }).token+}++describeRealPostgres('legacy grants seen by the broker, gate and sweep (real Postgres)', () => {+ const database = `control_api_legacy_lane_routes_${randomUUID().replace(/-/g, '')}`+ let adminPool: Pool+ let dbPool: Pool+ let db: DbClient+ const originalBrokerEnabled = config.mcpOauthBrokerEnabled++ 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) }+ testDb.pool = dbPool+ })++ afterAll(async () => {+ testDb.pool = undefined+ 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()+ }+ })++ beforeEach(async () => {+ await dbPool.query('DELETE FROM oauth_grants')+ config.mcpOauthBrokerEnabled = true+ })++ afterEach(() => {+ config.mcpOauthBrokerEnabled = originalBrokerEnabled+ })++ /**+ * A baked google server consented by a pre-identity pod (access token still+ * valid), then reinstalled under the same name with `oauth`.+ */+ async function legacyThenReinstall(flavor: Flavor, oauth: OAuthSpec) {+ const name = `legacy-route-${randomUUID().slice(0, 8)}`+ const gateway = new MockGateway(NS)+ await installServer(gateway, name, bakedOAuth('google', flavor))+ await legacyConsent(db, KEY, gateway, name, USER, {+ accessToken: LEGACY_AT,+ refreshToken: 'LEGACY-RT-google',+ expiresIn: 3600,+ })+ await reinstallServer(gateway, name, oauth)+ await gateway.createResource(+ 'contexts',+ { metadata: { name: CONTEXT }, spec: { contextId: CONTEXT, mcpServers: [name] } },+ NS+ )+ return { name, gateway }+ }++ const userToken = (gateway: MockGateway, name: string) =>+ request(createApp(gateway as never))+ .post('/api/v1/mcp-oauth/user-token')+ .set('Authorization', `Bearer ${controlToken()}`)+ .send({ mcpServerName: name, userId: USER })++ const invocable = async (gateway: MockGateway) =>+ (await resolveInvocableMcpServersForContexts(gateway, NS, [CONTEXT], USER, db)).map(s => s.name)++ const sweep = (gateway: MockGateway, name: string) =>+ resolveBatchGrantExistence({ db, gateway, mcpServersNamespace: NS }, [+ { mcpServerName: name, userId: USER },+ ])++ describe.each<Flavor>(['user', 'context'])('%s flavor', flavor => {+ it('user-token: a generic reinstall gets 404 no_grant, not the legacy access token', async () => {+ const { name, gateway } = await legacyThenReinstall(flavor, genericOAuth(flavor))++ const res = await userToken(gateway, name)++ expect(res.status).toBe(404)+ expect(res.body).toEqual({ error: 'no_grant' })+ expect(JSON.stringify(res.body)).not.toContain(LEGACY_AT)+ })++ it('user-token: a same-provider baked reinstall is still served the legacy token', async () => {+ const { name, gateway } = await legacyThenReinstall(flavor, bakedOAuth('google', flavor))++ const res = await userToken(gateway, name)++ expect(res.status).toBe(200)+ expect(res.body.token).toBe(LEGACY_AT)+ })++ it('gate and sweep: a generic reinstall is not connected by the legacy row', async () => {+ const { name, gateway } = await legacyThenReinstall(flavor, genericOAuth(flavor))++ expect(await invocable(gateway)).toEqual([])+ expect(await sweep(gateway, name)).toEqual([+ { mcpServerName: name, userId: USER, exists: false },+ ])+ })++ it('gate and sweep: a same-provider baked reinstall stays connected', async () => {+ const { name, gateway } = await legacyThenReinstall(flavor, bakedOAuth('google', flavor))++ expect(await invocable(gateway)).toEqual([name])+ expect(await sweep(gateway, name)).toEqual([+ { mcpServerName: name, userId: USER, exists: true },+ ])+ })+ })+})diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.tsindex 29bfd1033..696caeded 100644--- a/control-api/test/routes.mcpOauth.test.ts+++ b/control-api/test/routes.mcpOauth.test.ts@@ -194,6 +194,8 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {'user-1','google-drive',await liveUid(gateway, 'gdrive'),+ // Baked CR: the reader key carries its provider for unsealed legacy rows.+ 'google',])})@@ -267,6 +269,8 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {'ctx-A','google-drive',await liveUid(gateway, 'gdrive'),+ // Baked CR: the reader key carries its provider for unsealed legacy rows.+ 'google',])})@@ -321,6 +325,8 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {'ctx-A','google-drive',await liveUid(gateway, 'gdrive'),+ // Baked CR: the reader key carries its provider for unsealed legacy rows.+ 'google',])})@@ -556,6 +562,8 @@ describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (mini-spec 13)', ()'nobody','google-drive',await liveUid(gateway, 'gdrive'),+ // Baked CR: the reader key carries its provider for unsealed legacy rows.+ 'google',])})@@ -654,6 +662,8 @@ describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (mini-spec 13)', ()'ctx-real','google-drive',await liveUid(gateway, 'team'),+ // Baked CR: the reader key carries its provider for unsealed legacy rows.+ 'google',])})diff --git a/control-api/test/services.access.mcpInvocable.grantGate.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.test.tsindex 351784421..f65a66529 100644--- a/control-api/test/services.access.mcpInvocable.grantGate.test.ts+++ b/control-api/test/services.access.mcpInvocable.grantGate.test.ts@@ -145,6 +145,8 @@ describe('resolveInvocableMcpServersForContexts — rpc-proxy grant-presence gat// The installation identity comes from the listed CR (gateway-assigned uid).crUid: ((await g.getResource('mcpservers', 'gdrive', NS)) as { metadata: { uid: string } }).metadata.uid,+ // Baked CR: its provider lets the store serve that provider's unsealed rows.+ legacyProvider: 'google',})})@@ -185,6 +187,7 @@ describe('resolveInvocableMcpServersForContexts — context (shared) flavor', ()crUid: ((await g.getResource('mcpservers', 'gdrive-shared', NS)) as { metadata: { uid: string } }).metadata.uid,+ legacyProvider: 'google',})// Shared key must not carry a userId — invocability is team-wide.expect(key).not.toHaveProperty('userId')