Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

fix: add check for session in mcp oauth (#908)

Heer Ambavi8dd9bead82e0
diff --git a/.changeset/mcp-oauth-callback-session-bind.md b/.changeset/mcp-oauth-callback-session-bind.md
new file mode 100644
index 000000000..22a956331
--- /dev/null
+++ b/.changeset/mcp-oauth-callback-session-bind.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge': patch
+---
+
+Bind MCP OAuth callbacks to the TrueForge session in the browser. Completing consent now requires an authenticated session whose subject matches the pending authorization's user, so a forwarded authorize URL cannot attach another user's grant to the initiator's account.
diff --git a/packages/trueforge/src/apis/mcpOAuth.ts b/packages/trueforge/src/apis/mcpOAuth.ts
index 022687bbf..d00d82dd8 100644
--- a/packages/trueforge/src/apis/mcpOAuth.ts
+++ b/packages/trueforge/src/apis/mcpOAuth.ts
@@ -1,6 +1,8 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { extractErrorLogFields, McpConnectionError } from '@truefoundry/trueforge-core/core';
+import type { Context } from 'hono';
import type { Logger } from 'winston';
+import type { RequestContext } from '../auth/identity';
import { completeMcpAuthorization } from '../mcp/auth/mcpDcr';
import type { IOAuthClientStore, IOAuthTokenStore, OAuthPendingAuthorization } from '../mcp/auth/types';
import { mcpOAuthCallbackRoute } from '../routes/mcpOAuthRoutes';
@@ -9,6 +11,7 @@ export interface McpOAuthRouterDeps<TTransaction> {
tokenStore: IOAuthTokenStore<TTransaction>;
mcpServerStore: IOAuthClientStore<TTransaction>;
logger: Logger;
+ resolveSession: (c: Context) => Promise<RequestContext | undefined>;
}
type McpOAuthCallbackContext = Parameters<RouteHandler<typeof mcpOAuthCallbackRoute>>[0];
@@ -67,6 +70,12 @@ export function createMcpOAuthRouter<TTransaction>(deps: McpOAuthRouterDeps<TTra
const callbackHandler: RouteHandler<typeof mcpOAuthCallbackRoute> = async c => {
const { state, code, error, error_description: errorDescription } = c.req.valid('query');
+ // Bind the grant to the TrueForge session in this browser.
+ const session = await deps.resolveSession(c);
+ if (!session) {
+ return callbackFailure({ c, pending: undefined, message: 'Authentication required to complete OAuth' });
+ }
+
// Claimed up front: this row carries the FE landing path every branch below returns to, and
// claiming it atomically means a duplicate callback loses the race.
const pending = await deps.tokenStore.consumePendingAuthorization({ state });
@@ -75,6 +84,19 @@ export function createMcpOAuthRouter<TTransaction>(deps: McpOAuthRouterDeps<TTra
return callbackFailure({ c, pending, message: 'Unknown or expired OAuth state' });
}
+ if (session.subject.id !== pending.userRef) {
+ deps.logger.warn('MCP OAuth callback session does not match pending user', {
+ state,
+ sessionSubject: session.subject.id,
+ pendingUserRef: pending.userRef,
+ });
+ return callbackFailure({
+ c,
+ pending,
+ message: 'OAuth session does not match the authorizing user',
+ });
+ }
+
if (error) {
deps.logger.warn('MCP OAuth callback returned an error', { state, error, errorDescription });
return callbackFailure({ c, pending, message: error });
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index 99c47a44f..79ad8d336 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -33,6 +33,7 @@ import {
createApiKeyAuthMiddleware,
createAuthMiddleware,
truefoundryAdminMiddleware,
+ tryAuthenticate,
} from './auth/middleware';
import type { McpCatalog } from './catalog/McpCatalog';
import type { ModelCatalog } from './catalog/ModelCatalog';
@@ -308,6 +309,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
tokenStore: deps.tokenStore,
mcpServerStore: deps.resolveMcpServerStore(),
logger: deps.logger,
+ resolveSession: c => tryAuthenticate({ authenticator: deps.authenticator, context: c }),
}),
);
app.route(
diff --git a/packages/trueforge/src/auth/middleware.ts b/packages/trueforge/src/auth/middleware.ts
index ef0539346..e1c1dfcf8 100644
--- a/packages/trueforge/src/auth/middleware.ts
+++ b/packages/trueforge/src/auth/middleware.ts
@@ -13,14 +13,21 @@ export { extractRequestToken, readBearerToken };
export function createAuthMiddleware(authenticator: Authenticator): MiddlewareHandler {
return async (c, next) => {
- c.set('request_context', await authenticator.authenticate(c));
+ const requestContext = await tryAuthenticate({ authenticator, context: c });
+ if (requestContext === undefined) {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ }
+ c.set('request_context', requestContext);
return next();
};
}
export function createAdminAuthMiddleware(authenticator: Authenticator): MiddlewareHandler {
return async (c, next) => {
- const requestContext = await authenticator.authenticate(c);
+ const requestContext = await tryAuthenticate({ authenticator, context: c });
+ if (requestContext === undefined) {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ }
if (!hasAdminRole(requestContext)) {
throw new HTTPException(403, { message: 'Admin access required' });
}
@@ -99,3 +106,21 @@ export async function resolveOidcRequestContext(c: Context): Promise<RequestCont
user_credential: token,
});
}
+
+/**
+ * Soft authenticate — missing/invalid credentials (`401`) return `undefined` instead of throwing.
+ * Other failures (e.g. ServiceFoundry outage → 500) are rethrown.
+ */
+export async function tryAuthenticate(params: {
+ authenticator: Authenticator;
+ context: Context;
+}): Promise<RequestContext | undefined> {
+ try {
+ return await params.authenticator.authenticate(params.context);
+ } catch (error) {
+ if (error instanceof HTTPException && error.status === 401) {
+ return undefined;
+ }
+ throw error;
+ }
+}
diff --git a/packages/trueforge/src/mcp/auth/mcpDcr.ts b/packages/trueforge/src/mcp/auth/mcpDcr.ts
index cb4331d58..5e5b9bea8 100644
--- a/packages/trueforge/src/mcp/auth/mcpDcr.ts
+++ b/packages/trueforge/src/mcp/auth/mcpDcr.ts
@@ -209,7 +209,7 @@ export async function buildMcpAuthorizationUrl(params: {
mcpServerUrl: string;
mcpServerName: string;
returnTo?: string;
-}): Promise<URL> {
+}): Promise<{ authorizationUrl: URL; state: string }> {
const state = randomBytes(32).toString('base64url');
const redirectUri = mcpOAuthCallbackUrl();
let started: Awaited<ReturnType<typeof startAuthorization>>;
@@ -234,7 +234,7 @@ export async function buildMcpAuthorizationUrl(params: {
codeVerifier: started.codeVerifier,
returnTo: params.returnTo ?? null,
});
- return started.authorizationUrl;
+ return { authorizationUrl: started.authorizationUrl, state };
}
export async function resolveMcpAuth(params: {
@@ -279,7 +279,7 @@ export async function resolveMcpAuth(params: {
if (token) {
await params.tokenStore.deleteToken(tokenKey);
}
- const authUrl = await buildMcpAuthorizationUrl({
+ const { authorizationUrl: authUrl } = await buildMcpAuthorizationUrl({
tokenStore: params.tokenStore,
client,
serverId: params.serverId,
diff --git a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
index 7555a4a93..2a9bdfafd 100644
--- a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
@@ -6,6 +6,7 @@ import { configureOutboundUrlGuard } from '@truefoundry/trueforge-core/core';
import winston from 'winston';
import { createMcpOAuthRouter } from '../../../src/apis/mcpOAuth';
import { createMcpServersRouter, createSettingsMcpServersRouter } from '../../../src/apis/mcpServers';
+import type { RequestContext } from '../../../src/auth/identity';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import configuration from '../../../src/config';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
@@ -94,6 +95,7 @@ describe('MCP OAuth authorize + callback', () => {
let tokenStore: SqliteOAuthTokenStore;
let withTransaction: <T>(callback: (transaction: unknown) => Promise<T>) => Promise<T>;
let logger: ReturnType<typeof winston.createLogger>;
+ let callbackSession: RequestContext | undefined;
beforeAll(async () => {
configureOutboundUrlGuard({
@@ -128,11 +130,13 @@ describe('MCP OAuth authorize + callback', () => {
tokenStore,
mcpServerStore,
logger,
+ resolveSession: async () => callbackSession,
});
});
beforeEach(() => {
stubOauthFetch();
+ callbackSession = STANDALONE_REQUEST_CONTEXT;
});
afterEach(() => {
@@ -217,12 +221,36 @@ describe('MCP OAuth authorize + callback', () => {
expect(await reauthorize.json()).toEqual({ status: 'authenticated' });
});
+ it('callback rejects when the completing browser has no session', async () => {
+ const state = await pendingState('oauth-mcp-no-session', FE_RETURN_TO);
+ callbackSession = undefined;
+
+ const callback = await oauthRouter.request(`/callback?state=${encodeURIComponent(state)}&code=auth-code-1`);
+ expect(callback.status).toBe(400);
+ expect(await callback.json()).toEqual({ error: { message: 'Authentication required to complete OAuth' } });
+ });
+
+ it('callback rejects when the session subject does not match the pending user', async () => {
+ const state = await pendingState('oauth-mcp-wrong-user', FE_RETURN_TO);
+ callbackSession = {
+ tenant_id: 'default',
+ subject: { id: 'other-user', type: 'user', display_name: 'other-user' },
+ roles: [],
+ user_credential: null,
+ };
+
+ const callback = await oauthRouter.request(`/callback?state=${encodeURIComponent(state)}&code=auth-code-1`);
+ expect(callback.status).toBe(302);
+ expect(callback.headers.get('location')).toBe(
+ `${FE_RETURN_TO}?isSuccess=false&reason=OAuth+session+does+not+match+the+authorizing+user`,
+ );
+ });
+
it('callback returns 400 JSON when the pending row is gone, since its landing path went with it', async () => {
const unknown = await oauthRouter.request('/callback?state=no-such-state&code=x');
expect(unknown.status).toBe(400);
expect(await unknown.json()).toEqual({ error: { message: 'Unknown or expired OAuth state' } });
- // The missing row is the reason reported, even when the IdP also sent an `error`.
const denied = await oauthRouter.request('/callback?state=any&error=access_denied&error_description=user%20denied');
expect(denied.status).toBe(400);
expect(await denied.json()).toEqual({ error: { message: 'Unknown or expired OAuth state' } });
diff --git a/packages/trueforge/tests/unit/auth/middleware.test.ts b/packages/trueforge/tests/unit/auth/middleware.test.ts
index 5e14c50c6..9dd1764eb 100644
--- a/packages/trueforge/tests/unit/auth/middleware.test.ts
+++ b/packages/trueforge/tests/unit/auth/middleware.test.ts
@@ -66,6 +66,19 @@ function createApp(authenticator: Authenticator) {
}
describe('createAuthMiddleware / createAdminAuthMiddleware', () => {
+ it('propagates non-401 authenticate failures instead of turning them into 401', async () => {
+ const authenticator: Authenticator = {
+ authenticate: async () => {
+ throw new HTTPException(500, { message: 'TrueFoundry ServiceFoundry session request failed' });
+ },
+ };
+ const res = await createApp(authenticator).request('/api/v1/models');
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({
+ error: { message: 'TrueFoundry ServiceFoundry session request failed' },
+ });
+ });
+
it('allows settings for standalone authenticator (always admin)', async () => {
const res = await createApp(new StandaloneAuthenticator()).request('/api/v1/settings');
expect(res.status).toBe(200);
diff --git a/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts b/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts
index 1c2960846..8035deba8 100644
--- a/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts
+++ b/packages/trueforge/tests/unit/mcp/auth/mcpOAuth.test.ts
@@ -319,7 +319,7 @@ describe('buildMcpAuthorizationUrl', () => {
const { tokenStore } = newStores();
stubOauthFetch({});
- const authUrl = await buildMcpAuthorizationUrl({
+ const { authorizationUrl: authUrl, state } = await buildMcpAuthorizationUrl({
tokenStore,
client: sampleClient,
serverId: SERVER_ID,
@@ -337,9 +337,9 @@ describe('buildMcpAuthorizationUrl', () => {
expect(authUrl.searchParams.get('code_challenge')).toBeTruthy();
expect(authUrl.searchParams.get('resource')).toBe(resourceUrlFromServerUrl(SERVER_URL).href);
- const state = authUrl.searchParams.get('state');
expect(state).toBeTruthy();
- const pending = await tokenStore.consumePendingAuthorization({ state: state! });
+ expect(authUrl.searchParams.get('state')).toBe(state);
+ const pending = await tokenStore.consumePendingAuthorization({ state });
expect(pending).toMatchObject({
state,
id: SERVER_ID,
@@ -357,7 +357,7 @@ describe('buildMcpAuthorizationUrl', () => {
server: { ...sampleClient.server, codeChallengeMethodsSupported: null },
};
- const authUrl = await buildMcpAuthorizationUrl({
+ const { authorizationUrl: authUrl } = await buildMcpAuthorizationUrl({
tokenStore,
client,
serverId: SERVER_ID,
@@ -624,7 +624,7 @@ describe('completeMcpAuthorization', () => {
const stores = newStores();
await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });
- const authUrl = await buildMcpAuthorizationUrl({
+ const { authorizationUrl: authUrl, state } = await buildMcpAuthorizationUrl({
tokenStore: stores.tokenStore,
client: sampleClient,
serverId: SERVER_ID,
@@ -633,7 +633,7 @@ describe('completeMcpAuthorization', () => {
mcpServerName: SERVER_NAME,
returnTo: '/connected',
});
- const state = authUrl.searchParams.get('state')!;
+ expect(authUrl.searchParams.get('state')).toBe(state);
const { tokenBodies } = stubOauthFetch({
tokenResponse: {
@@ -701,7 +701,7 @@ describe('completeMcpAuthorization', () => {
const stores = newStores();
const deleteClient = jest.spyOn(stores.mcpServerStore, 'deleteClient');
await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });
- const authUrl = await buildMcpAuthorizationUrl({
+ const { state } = await buildMcpAuthorizationUrl({
tokenStore: stores.tokenStore,
client: sampleClient,
serverId: SERVER_ID,
@@ -710,7 +710,6 @@ describe('completeMcpAuthorization', () => {
mcpServerName: SERVER_NAME,
returnTo: '/after',
});
- const state = authUrl.searchParams.get('state')!;
globalThis.fetch = (async (input, init) => {
const url = String(input);