π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(connector): authenticate MCP OAuth token requests with the registered client auth method (#20404)
Rdmclin2207302a113fa
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 3d86505a673..750b9de07e1 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -30,6 +30,8 @@ import {discoverConnectorOAuth,getConnectorRedirectUri,registerDynamicClient,+ registeredAuthMethod,+ toClientInformation,} from '@/server/services/connector/oauth';import {generateConnectorOAuthState,@@ -570,6 +572,7 @@ export const connectorRouter = router({// 2. Resolve the OAuth client: pre-registration vs. DCR.let clientId = existing.clientId;let clientSecret = existing.clientSecret;+ let tokenEndpointAuthMethod = existing.tokenEndpointAuthMethod;const scheme: OIDCConfig['scheme'] = clientId ? 'pre_registration' : 'dcr';if (!clientId) {@@ -594,6 +597,7 @@ export const connectorRouter = router({});clientId = reg.client_id;clientSecret = reg.client_secret ?? undefined;+ tokenEndpointAuthMethod = registeredAuthMethod(reg, metadata);}// 3. Persist the resolved config so the callback + refresh can reuse it.@@ -608,6 +612,7 @@ export const connectorRouter = router({scheme,scopes,tokenEndpoint: metadata.token_endpoint,+ tokenEndpointAuthMethod,};await ctx.connectorModel.update(input.id, { oidcConfig: resolvedOidc });@@ -615,7 +620,7 @@ export const connectorRouter = router({const state = generateConnectorOAuthState();const { authorizationUrl, codeVerifier } = await buildAuthorizationUrl({authorizationServerUrl,- clientInformation: { client_id: clientId, client_secret: clientSecret },+ clientInformation: toClientInformation(resolvedOidc),metadata,redirectUri,resource: connector.mcpServerUrl,diff --git a/apps/server/src/services/connector/oauth.test.ts b/apps/server/src/services/connector/oauth.test.tsindex 515508bd7c0..a64ea386323 100644--- a/apps/server/src/services/connector/oauth.test.ts+++ b/apps/server/src/services/connector/oauth.test.ts@@ -1,8 +1,15 @@import { registerClient } from '@modelcontextprotocol/sdk/client/auth.js';import type { AuthorizationServerMetadata } from '@modelcontextprotocol/sdk/shared/auth.js';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { registerDynamicClient, selectRegistrationAuthMethod } from './oauth';+import {+ exchangeConnectorCode,+ refreshConnectorToken,+ registerDynamicClient,+ registeredAuthMethod,+ selectRegistrationAuthMethod,+ toClientInformation,+} from './oauth';vi.mock('@modelcontextprotocol/sdk/client/auth.js', async (importOriginal) => ({...(await importOriginal<object>()),@@ -73,3 +80,128 @@ describe('registerDynamicClient', () => {);});});++/**+ * Token endpoint that, like Linear's, only accepts the auth method the client+ * was registered with (`client_secret_post`). Records how each request+ * authenticated.+ */+const stubPostOnlyTokenEndpoint = () => {+ const attempts: string[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_url: string | URL, init?: RequestInit) => {+ const headers = new Headers(init?.headers);+ const body = new URLSearchParams(String(init?.body ?? ''));+ const method = headers.get('authorization')?.startsWith('Basic ')+ ? 'client_secret_basic'+ : body.has('client_secret')+ ? 'client_secret_post'+ : 'none';+ attempts.push(method);+ if (method !== 'client_secret_post') {+ return Response.json(+ { error: 'invalid_client', error_description: 'Client authentication failed' },+ { status: 401 },+ );+ }+ return Response.json({ access_token: 'tok', refresh_token: 'rt', token_type: 'Bearer' });+ }),+ );+ return attempts;+};++const exchange = (oidc: Parameters<typeof toClientInformation>[0], methods?: string[]) =>+ exchangeConnectorCode({+ authorizationCode: 'code',+ authorizationServerUrl: 'https://auth.example.com',+ clientInformation: toClientInformation(oidc),+ codeVerifier: 'verifier',+ metadata: metadataWith(methods),+ redirectUri: 'https://app.example.com/oauth/connector/callback',+ });++describe('token endpoint client authentication', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('uses the method recorded at registration instead of the SDK preference', async () => {+ // Regression: a DCR client registered as client_secret_post was sent with+ // HTTP Basic and rejected with `invalid_client: Client authentication failed`.+ const attempts = stubPostOnlyTokenEndpoint();++ const result = await exchange(+ { clientId: 'cid', clientSecret: 'secret', tokenEndpointAuthMethod: 'client_secret_post' },+ ['client_secret_basic', 'client_secret_post', 'none'],+ );++ expect(attempts).toEqual(['client_secret_post']);+ expect(result).toEqual({+ authMethod: undefined,+ tokens: expect.objectContaining({ access_token: 'tok' }),+ });+ });++ it('retries with the other secret method when none is recorded, and reports it', async () => {+ const attempts = stubPostOnlyTokenEndpoint();++ const result = await exchange({ clientId: 'cid', clientSecret: 'secret' }, [+ 'client_secret_basic',+ 'client_secret_post',+ ]);++ expect(attempts).toEqual(['client_secret_basic', 'client_secret_post']);+ expect(result.authMethod).toBe('client_secret_post');+ });++ it('does not retry when the recorded method is rejected', async () => {+ const attempts = stubPostOnlyTokenEndpoint();++ await expect(+ exchange(+ { clientId: 'cid', clientSecret: 'secret', tokenEndpointAuthMethod: 'client_secret_basic' },+ ['client_secret_basic', 'client_secret_post'],+ ),+ ).rejects.toThrow('Client authentication failed');+ expect(attempts).toEqual(['client_secret_basic']);+ });++ it('does not retry a public client', async () => {+ const attempts = stubPostOnlyTokenEndpoint();++ await expect(exchange({ clientId: 'cid' }, ['none'])).rejects.toThrow();+ expect(attempts).toEqual(['none']);+ });++ it('applies the same fallback to token refresh', async () => {+ const attempts = stubPostOnlyTokenEndpoint();++ const result = await refreshConnectorToken({+ authorizationServerUrl: 'https://auth.example.com',+ clientInformation: toClientInformation({ clientId: 'cid', clientSecret: 'secret' }),+ metadata: metadataWith(['client_secret_basic', 'client_secret_post']),+ refreshToken: 'rt',+ });++ expect(attempts).toEqual(['client_secret_basic', 'client_secret_post']);+ expect(result.authMethod).toBe('client_secret_post');+ });+});++describe('registeredAuthMethod', () => {+ it('prefers the method the server echoed back', () => {+ expect(+ registeredAuthMethod(+ { client_id: 'c', redirect_uris: [], token_endpoint_auth_method: 'client_secret_basic' },+ metadataWith(['client_secret_post', 'client_secret_basic']),+ ),+ ).toBe('client_secret_basic');+ });++ it('falls back to the requested method when the response omits it', () => {+ expect(+ registeredAuthMethod({ client_id: 'c', redirect_uris: [] }, metadataWith(['none'])),+ ).toBe('none');+ });+});diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.tsindex 4fe52cf3e60..111d4748408 100644--- a/apps/server/src/services/connector/oauth.ts+++ b/apps/server/src/services/connector/oauth.ts@@ -7,6 +7,7 @@ import {registerClient,startAuthorization,} from '@modelcontextprotocol/sdk/client/auth.js';+import { InvalidClientError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import type {AuthorizationServerMetadata,OAuthClientInformationFull,@@ -15,6 +16,7 @@ import type {} from '@modelcontextprotocol/sdk/shared/auth.js';import debug from 'debug';+import type { OIDCConfig } from '@/database/schemas';import { appEnv } from '@/envs/app';const log = debug('lobe-server:connector:oauth');@@ -127,6 +129,26 @@ export const registerDynamicClient = async (params: {});};+const TOKEN_ENDPOINT_AUTH_METHODS = new Set<string>([+ 'client_secret_basic',+ 'client_secret_post',+ 'none',+]);++/**+ * The token endpoint auth method a dynamic registration settled on: what the+ * server echoed back (it may override the request), else what was requested.+ */+export const registeredAuthMethod = (+ registration: OAuthClientInformationFull,+ metadata: AuthorizationServerMetadata,+): RegistrationAuthMethod => {+ const echoed = registration.token_endpoint_auth_method;+ return echoed && TOKEN_ENDPOINT_AUTH_METHODS.has(echoed)+ ? (echoed as RegistrationAuthMethod)+ : selectRegistrationAuthMethod(metadata);+};+/*** Build the authorization-code redirect URL (with PKCE). Returns the URL to* open in the popup plus the `codeVerifier` that must be stashed (server-side,@@ -155,6 +177,68 @@ export const buildAuthorizationUrl = async (params: {return { authorizationUrl: authorizationUrl.toString(), codeVerifier };};+type TokenEndpointAuthMethod = NonNullable<OIDCConfig['tokenEndpointAuthMethod']>;++/**+ * Client information for token requests. The stored auth method is passed+ * through so the SDK uses it instead of its own preference (it picks+ * `client_secret_basic` whenever a secret exists), which servers that enforce+ * the registered method reject with `invalid_client`.+ */+export const toClientInformation = (+ oidc: Pick<OIDCConfig, 'clientId' | 'clientSecret' | 'tokenEndpointAuthMethod'>,+): OAuthClientInformationMixed => ({+ client_id: oidc.clientId!,+ client_secret: oidc.clientSecret,+ ...(oidc.tokenEndpointAuthMethod && {+ token_endpoint_auth_method: oidc.tokenEndpointAuthMethod,+ }),+});++const alternateSecretMethod = (+ clientInformation: OAuthClientInformationMixed,+ metadata: AuthorizationServerMetadata,+): TokenEndpointAuthMethod | undefined => {+ if (!clientInformation.client_secret) return;+ if (+ 'token_endpoint_auth_method' in clientInformation &&+ clientInformation.token_endpoint_auth_method+ )+ return;+ // Without a recorded method the SDK tried basic when the server supports it,+ // and post otherwise; the other one is the only remaining confidential option.+ const supported = metadata.token_endpoint_auth_methods_supported ?? [];+ const tried =+ supported.length === 0 || supported.includes('client_secret_basic')+ ? 'client_secret_basic'+ : 'client_secret_post';+ const other = tried === 'client_secret_basic' ? 'client_secret_post' : 'client_secret_basic';+ return supported.length === 0 || supported.includes(other) ? other : undefined;+};++/**+ * Run a token request, retrying once with the other confidential auth method+ * when the server rejects the client and no method is on record β the case+ * for pre-registered clients, whose registered method the user never told us.+ * Returns the method that worked so callers can persist it.+ */+const withClientAuthFallback = async (+ clientInformation: OAuthClientInformationMixed,+ metadata: AuthorizationServerMetadata,+ request: (clientInformation: OAuthClientInformationMixed) => Promise<OAuthTokens>,+): Promise<{ authMethod?: TokenEndpointAuthMethod; tokens: OAuthTokens }> => {+ try {+ return { tokens: await request(clientInformation) };+ } catch (error) {+ const other =+ error instanceof InvalidClientError && alternateSecretMethod(clientInformation, metadata);+ if (!other) throw error;+ log('token endpoint rejected client auth, retrying with %s', other);+ const tokens = await request({ ...clientInformation, token_endpoint_auth_method: other });+ return { authMethod: other, tokens };+ }+};+/** Exchange the authorization code for tokens (callback step). */export const exchangeConnectorCode = async (params: {authorizationCode: string;@@ -164,16 +248,17 @@ export const exchangeConnectorCode = async (params: {metadata: AuthorizationServerMetadata;redirectUri: string;resource?: string;-}): Promise<OAuthTokens> => {- return exchangeAuthorization(params.authorizationServerUrl, {- authorizationCode: params.authorizationCode,- clientInformation: params.clientInformation,- codeVerifier: params.codeVerifier,- metadata: params.metadata,- redirectUri: params.redirectUri,- resource: params.resource ? new URL(params.resource) : undefined,- });-};+}): Promise<{ authMethod?: TokenEndpointAuthMethod; tokens: OAuthTokens }> =>+ withClientAuthFallback(params.clientInformation, params.metadata, (clientInformation) =>+ exchangeAuthorization(params.authorizationServerUrl, {+ authorizationCode: params.authorizationCode,+ clientInformation,+ codeVerifier: params.codeVerifier,+ metadata: params.metadata,+ redirectUri: params.redirectUri,+ resource: params.resource ? new URL(params.resource) : undefined,+ }),+ );/** Refresh an expired access token using the stored refresh token. */export const refreshConnectorToken = async (params: {@@ -182,11 +267,12 @@ export const refreshConnectorToken = async (params: {metadata: AuthorizationServerMetadata;refreshToken: string;resource?: string;-}): Promise<OAuthTokens> => {- return refreshAuthorization(params.authorizationServerUrl, {- clientInformation: params.clientInformation,- metadata: params.metadata,- refreshToken: params.refreshToken,- resource: params.resource ? new URL(params.resource) : undefined,- });-};+}): Promise<{ authMethod?: TokenEndpointAuthMethod; tokens: OAuthTokens }> =>+ withClientAuthFallback(params.clientInformation, params.metadata, (clientInformation) =>+ refreshAuthorization(params.authorizationServerUrl, {+ clientInformation,+ metadata: params.metadata,+ refreshToken: params.refreshToken,+ resource: params.resource ? new URL(params.resource) : undefined,+ }),+ );diff --git a/apps/server/src/services/connector/tokens.ts b/apps/server/src/services/connector/tokens.tsindex e8ba55bd0ed..0e39aee7433 100644--- a/apps/server/src/services/connector/tokens.ts+++ b/apps/server/src/services/connector/tokens.ts@@ -5,7 +5,7 @@ import debug from 'debug';import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';import type { ConnectorCredentials } from '@/database/schemas';-import { refreshConnectorToken } from './oauth';+import { refreshConnectorToken, toClientInformation } from './oauth';const log = debug('lobe-server:connector:tokens');@@ -53,9 +53,9 @@ export const ensureFreshConnectorToken = async (const metadata = await discoverAuthorizationServerMetadata(oidc.issuer);if (!metadata) return connector;- const tokens = await refreshConnectorToken({+ const { authMethod, tokens } = await refreshConnectorToken({authorizationServerUrl: oidc.issuer,- clientInformation: { client_id: oidc.clientId, client_secret: oidc.clientSecret },+ clientInformation: toClientInformation(oidc),metadata,refreshToken: creds.refreshToken,resource: connector.mcpServerUrl ?? undefined,@@ -68,6 +68,7 @@ export const ensureFreshConnectorToken = async (await connectorModel.update(connector.id, {credentials: JSON.stringify(credentials),+ ...(authMethod && { oidcConfig: { ...oidc, tokenEndpointAuthMethod: authMethod } }),tokenExpiresAt,});diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.tsindex 999f88807f1..03c4f37d184 100644--- a/packages/database/src/schemas/connector.ts+++ b/packages/database/src/schemas/connector.ts@@ -51,6 +51,13 @@ export interface OIDCConfig {scopes?: string[];tokenEndpoint?: string;+ /**+ * How the client authenticates at the token endpoint. DCR records the method+ * the server registered; otherwise it is learned from the first successful+ * exchange. Servers that enforce the registered method reject any other one.+ */+ tokenEndpointAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'none';+/** Recommended for public clients */usePKCE?: boolean;}diff --git a/src/app/(backend)/oauth/connector/callback/route.test.ts b/src/app/(backend)/oauth/connector/callback/route.test.tsindex 8d3bc879870..c652f7374f9 100644--- a/src/app/(backend)/oauth/connector/callback/route.test.ts+++ b/src/app/(backend)/oauth/connector/callback/route.test.ts@@ -7,8 +7,9 @@ import { ConnectorToolModel } from '@/database/models/connectorTool';import { GET } from './route';-const { mockConsume, mockFindById, mockSync, mockUpdate } = vi.hoisted(() => ({+const { mockConsume, mockExchange, mockFindById, mockSync, mockUpdate } = vi.hoisted(() => ({mockConsume: vi.fn(),+ mockExchange: vi.fn(),mockFindById: vi.fn(),mockSync: vi.fn(),mockUpdate: vi.fn(),@@ -25,7 +26,11 @@ vi.mock('@modelcontextprotocol/sdk/client/auth.js', () => ({.mockResolvedValue({ token_endpoint: 'https://as/token' }),}));vi.mock('@/server/services/connector/oauth', () => ({- exchangeConnectorCode: vi.fn().mockResolvedValue({ access_token: 'tok' }),+ exchangeConnectorCode: mockExchange,+ toClientInformation: (oidc: { clientId: string; clientSecret?: string }) => ({+ client_id: oidc.clientId,+ client_secret: oidc.clientSecret,+ }),}));vi.mock('@/server/services/connector/tokens', () => ({tokensToCredentials: vi@@ -65,6 +70,7 @@ beforeEach(() => {},});mockUpdate.mockResolvedValue(undefined);+ mockExchange.mockResolvedValue({ tokens: { access_token: 'tok' } });vi.spyOn(console, 'error').mockImplementation(() => {});});@@ -156,4 +162,32 @@ describe('connector OAuth callback', () => {expect(body).not.toContain('<img');expect(mockConsume).not.toHaveBeenCalled();});++ it('remembers the client auth method that the token endpoint accepted', async () => {+ mockSync.mockResolvedValue({ toolCount: 1 });+ mockExchange.mockResolvedValue({+ authMethod: 'client_secret_post',+ tokens: { access_token: 'tok' },+ });++ await GET(makeReq());++ expect(mockUpdate).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({+ oidcConfig: expect.objectContaining({+ clientId: 'cid',+ tokenEndpointAuthMethod: 'client_secret_post',+ }),+ }),+ );+ });++ it('leaves the OIDC config alone when the first auth method worked', async () => {+ mockSync.mockResolvedValue({ toolCount: 1 });++ await GET(makeReq());++ expect(mockUpdate.mock.calls[0][1]).not.toHaveProperty('oidcConfig');+ });});diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.tsindex 64b88be8456..45cd00e5f6a 100644--- a/src/app/(backend)/oauth/connector/callback/route.ts+++ b/src/app/(backend)/oauth/connector/callback/route.ts@@ -7,7 +7,7 @@ import { ConnectorToolModel } from '@/database/models/connectorTool';import { serverDB } from '@/database/server';import { appEnv } from '@/envs/app';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { exchangeConnectorCode } from '@/server/services/connector/oauth';+import { exchangeConnectorCode, toClientInformation } from '@/server/services/connector/oauth';import { consumeConnectorOAuthState } from '@/server/services/connector/stateStore';import { syncConnectorToolsById } from '@/server/services/connector/sync';import { tokensToCredentials } from '@/server/services/connector/tokens';@@ -132,10 +132,10 @@ export const GET = async (req: NextRequest) => {return renderFailure('metadata_discovery_failed');}- const tokens = await exchangeConnectorCode({+ const { authMethod, tokens } = await exchangeConnectorCode({authorizationCode: code,authorizationServerUrl: payload.authorizationServerUrl,- clientInformation: { client_id: oidc.clientId, client_secret: oidc.clientSecret },+ clientInformation: toClientInformation(oidc),codeVerifier: payload.codeVerifier,metadata,redirectUri: oidc.redirectUri!,@@ -148,6 +148,8 @@ export const GET = async (req: NextRequest) => {await connectorModel.update(payload.connectorId, {credentials: JSON.stringify(credentials),+ // Remember the auth method that worked so refreshes don't fail the same way.+ ...(authMethod && { oidcConfig: { ...oidc, tokenEndpointAuthMethod: authMethod } }),tokenExpiresAt,});