mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-21 15:33:45 +00:00
🔐 fix: Redact MCP OAuth Diagnostics (#17603)
* 🔐 fix: Redact MCP OAuth Diagnostics
* fix: Keep OAuth Resource Credentials Out of Diagnostics
* test: Type the OAuth Completion Diagnostic Fixture
This commit is contained in:
parent
d2126b8ac7
commit
9aa81cf1ab
3 changed files with 327 additions and 16 deletions
|
|
@ -368,6 +368,112 @@ describe('MCP Routes', () => {
|
|||
expect(routeLayer.route.stack[1].handle).toBe(admissionLimiter);
|
||||
});
|
||||
|
||||
describe('OAuth diagnostic confidentiality', () => {
|
||||
const { MCPOAuthHandler } = require('@librechat/api');
|
||||
const { logger } = require('@librechat/data-schemas');
|
||||
const expectPrivate = (...secrets) => {
|
||||
const output = inspect(
|
||||
['debug', 'info', 'warn', 'error'].flatMap((level) => logger[level].mock.calls),
|
||||
{ depth: null },
|
||||
);
|
||||
for (const secret of secrets) expect(output.includes(secret)).toBe(false);
|
||||
};
|
||||
|
||||
it('redirects initiation normally without logging the generated authorization URL or metadata', async () => {
|
||||
const secret = 'fixture-private-authorization';
|
||||
const authorizationUrl = `https://oauth.example.com/auth?state=${secret}`;
|
||||
const flowId = 'test-user-id:test-server';
|
||||
mockResolveAllMcpConfigs.mockResolvedValue({
|
||||
'test-server': { url: 'https://test-server.com' },
|
||||
});
|
||||
require('~/config').getFlowStateManager.mockReturnValue({
|
||||
getFlowState: jest.fn().mockResolvedValue({
|
||||
status: 'PENDING',
|
||||
createdAt: Date.now(),
|
||||
metadata: { serverUrl: 'https://test-server.com', oauth: { client_id: 'client' } },
|
||||
}),
|
||||
initFlow: jest.fn().mockResolvedValue(),
|
||||
});
|
||||
MCPOAuthHandler.initiateOAuthFlow.mockResolvedValueOnce({
|
||||
authorizationUrl,
|
||||
flowId,
|
||||
flowMetadata: {
|
||||
state: secret,
|
||||
codeVerifier: secret,
|
||||
oauthHeaders: { Authorization: secret },
|
||||
},
|
||||
});
|
||||
MCPOAuthHandler.storeStateMapping.mockResolvedValueOnce();
|
||||
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/initiate')
|
||||
.query({ userId: 'test-user-id', flowId });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.location).toBe(authorizationUrl);
|
||||
expectPrivate(secret, authorizationUrl);
|
||||
expect(logger.debug).toHaveBeenCalledWith('[MCP OAuth] OAuth flow initiated', {
|
||||
oauthFlowId: flowId,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports callback presence without logging unrecognized state or authorization code', async () => {
|
||||
const state = 'fixture-private-unrecognized-state';
|
||||
const code = 'fixture-private-authorization-code';
|
||||
MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(null);
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.query({ state, code });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.location).toContain('error=invalid_state');
|
||||
expectPrivate(state, code);
|
||||
expect(logger.debug).toHaveBeenCalledWith('[MCP OAuth] Callback received', {
|
||||
serverName: 'test-server',
|
||||
code: 'present',
|
||||
hasState: true,
|
||||
hasError: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not log raw provider error text on an error callback', async () => {
|
||||
const secret = 'fixture-private-provider-error';
|
||||
MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(null);
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.query({ state: secret, error: secret });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expectPrivate(secret);
|
||||
expect(logger.error).toHaveBeenCalledWith('[MCP OAuth] OAuth error received');
|
||||
});
|
||||
|
||||
it('projects callback failures to safe type/status without changing the failure redirect', async () => {
|
||||
const secret = 'fixture-private-callback-failure';
|
||||
const flowId = 'test-user-id:test-server';
|
||||
MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(flowId);
|
||||
MCPOAuthHandler.getFlowState.mockRejectedValueOnce(
|
||||
Object.assign(new Error(secret), {
|
||||
status: 503,
|
||||
codeVerifier: secret,
|
||||
tokens: { access_token: secret, refresh_token: secret },
|
||||
}),
|
||||
);
|
||||
const response = await request(app)
|
||||
.get('/api/mcp/test-server/oauth/callback')
|
||||
.set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`])
|
||||
.query({ state: secret, code: secret });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.location).toContain('error=callback_failed');
|
||||
expectPrivate(secret);
|
||||
expect(logger.error).toHaveBeenCalledWith('[MCP OAuth] OAuth callback error', {
|
||||
type: 'Error',
|
||||
status: 503,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /:serverName/oauth/initiate', () => {
|
||||
const { MCPOAuthHandler } = require('@librechat/api');
|
||||
const { getLogStores } = require('~/cache');
|
||||
|
|
|
|||
199
packages/api/src/mcp/__tests__/MCPOAuthLogging.test.ts
Normal file
199
packages/api/src/mcp/__tests__/MCPOAuthLogging.test.ts
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
import { Keyv } from 'keyv';
|
||||
import { inspect } from 'util';
|
||||
import { logger } from '@librechat/data-schemas';
|
||||
import * as sdkAuth from '@modelcontextprotocol/sdk/client/auth.js';
|
||||
import type { OAuthTestServer } from './helpers/oauthTestServer';
|
||||
import type { MCPOAuthTokens } from '~/mcp/oauth/types';
|
||||
import { createOAuthMCPServer } from './helpers/oauthTestServer';
|
||||
import { MCPOAuthHandler } from '~/mcp/oauth/handler';
|
||||
import { FlowStateManager } from '~/flow/manager';
|
||||
|
||||
describe('MCP OAuth initiation log boundary', () => {
|
||||
let server: OAuthTestServer;
|
||||
let logs: jest.SpyInstance[];
|
||||
|
||||
beforeEach(async () => {
|
||||
logs = (['debug', 'info', 'warn', 'error'] as const).map((level) =>
|
||||
jest.spyOn(logger, level).mockImplementation(() => logger),
|
||||
);
|
||||
server = await createOAuthMCPServer({ issueRefreshTokens: true });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await server?.close();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each(['dynamic', 'configured'] as const)(
|
||||
'keeps %s authorization secrets out of every logger argument while retaining flow status',
|
||||
async (clientSource) => {
|
||||
const headerSecret = 'fixture-oauth-header-secret';
|
||||
const configuredSecret = 'fixture-configured-client-secret';
|
||||
const result = await MCPOAuthHandler.initiateOAuthFlow(
|
||||
'logging-server',
|
||||
server.url,
|
||||
'logging-user',
|
||||
{ 'X-Fixture-Authorization': headerSecret },
|
||||
clientSource === 'configured'
|
||||
? {
|
||||
authorization_url: new URL('authorize', server.url).href,
|
||||
token_url: new URL('token', server.url).href,
|
||||
client_id: 'configured-client',
|
||||
client_secret: configuredSecret,
|
||||
}
|
||||
: undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
[`127.0.0.1:${server.port}`],
|
||||
'logging-tenant',
|
||||
);
|
||||
|
||||
const authorization = new URL(result.authorizationUrl);
|
||||
expect(authorization.searchParams.get('state')).toBe(result.flowMetadata.state);
|
||||
expect(result.flowMetadata.codeVerifier).toEqual(expect.any(String));
|
||||
expect(result.flowMetadata.clientInfo?.client_secret).toEqual(expect.any(String));
|
||||
expect(result.flowMetadata.oauthHeaders).toEqual({ 'X-Fixture-Authorization': headerSecret });
|
||||
const output = inspect(
|
||||
logs.flatMap((spy) => spy.mock.calls),
|
||||
{ depth: null },
|
||||
);
|
||||
for (const secret of [
|
||||
result.authorizationUrl,
|
||||
result.flowMetadata.state,
|
||||
result.flowMetadata.codeVerifier,
|
||||
result.flowMetadata.clientInfo?.client_secret,
|
||||
authorization.searchParams.get('code_challenge'),
|
||||
headerSecret,
|
||||
configuredSecret,
|
||||
]) {
|
||||
if (secret) expect(output.includes(secret)).toBe(false);
|
||||
}
|
||||
expect(logger.debug).toHaveBeenCalledWith('[MCPOAuth] Authorization flow ready', {
|
||||
flowId: result.flowId,
|
||||
serverName: 'logging-server',
|
||||
clientSource,
|
||||
hasClientSecret: true,
|
||||
hasResourceMetadata: true,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('redacts stored registration lookup outages before dynamically registering again', async () => {
|
||||
const secret = 'fixture-private-cached-registration';
|
||||
const failure = Object.assign(new Error(secret), {
|
||||
status: 503,
|
||||
request: { headers: { Authorization: secret } },
|
||||
});
|
||||
const result = await MCPOAuthHandler.initiateOAuthFlow(
|
||||
'logging-server',
|
||||
server.url,
|
||||
'logging-user',
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
jest.fn(async () => {
|
||||
throw failure;
|
||||
}),
|
||||
[`127.0.0.1:${server.port}`],
|
||||
);
|
||||
expect(result.flowMetadata.clientInfo?.client_id).toEqual(expect.any(String));
|
||||
const output = inspect(
|
||||
logs.flatMap((spy) => spy.mock.calls),
|
||||
{ depth: null },
|
||||
);
|
||||
expect(output.includes(secret)).toBe(false);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
'[MCPOAuth] Failed to look up existing client registration, falling back to new registration',
|
||||
{ type: 'Error', status: 503, serverName: 'logging-server', userId: 'logging-user' },
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps resource query credentials and exchanged tokens out of completion diagnostics', async () => {
|
||||
const secret = 'fixture-private-resource-query';
|
||||
const tokens = {
|
||||
access_token: 'fixture-private-access-token',
|
||||
token_type: 'Bearer',
|
||||
expires_in: 3600,
|
||||
};
|
||||
const result = await MCPOAuthHandler.initiateOAuthFlow(
|
||||
'logging-server',
|
||||
server.url,
|
||||
'logging-user',
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
[`127.0.0.1:${server.port}`],
|
||||
);
|
||||
const resource = `${server.url}?credential=${secret}`;
|
||||
const manager = new FlowStateManager<MCPOAuthTokens>(new Keyv(), { ttl: 30_000, ci: true });
|
||||
await manager.initFlow(result.flowId, 'mcp_oauth', {
|
||||
...result.flowMetadata,
|
||||
serverUrl: resource,
|
||||
resourceMetadata: { ...result.flowMetadata.resourceMetadata, resource },
|
||||
});
|
||||
const exchange = jest.spyOn(sdkAuth, 'exchangeAuthorization').mockResolvedValueOnce(tokens);
|
||||
const completed = await MCPOAuthHandler.completeOAuthFlow(
|
||||
result.flowId,
|
||||
'fixture-private-code',
|
||||
manager,
|
||||
{},
|
||||
);
|
||||
expect(exchange).toHaveBeenCalledTimes(1);
|
||||
expect(completed.access_token).toBe(tokens.access_token);
|
||||
expect((await manager.getFlowState(result.flowId, 'mcp_oauth'))?.status).toBe('COMPLETED');
|
||||
const output = inspect(
|
||||
logs.flatMap((spy) => spy.mock.calls),
|
||||
{ depth: null },
|
||||
);
|
||||
for (const value of [
|
||||
secret,
|
||||
resource,
|
||||
tokens.access_token,
|
||||
'fixture-private-code',
|
||||
result.flowMetadata.state,
|
||||
result.flowMetadata.codeVerifier,
|
||||
]) {
|
||||
if (value) expect(output.includes(value)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('retains safe error type/status but not provider echoes, request data or stacks', async () => {
|
||||
const secret = 'fixture-sensitive-provider-echo';
|
||||
const error = Object.assign(new Error(`Provider rejected ${secret}`), {
|
||||
status: 400,
|
||||
codeVerifier: secret,
|
||||
authorizationUrl: `https://example.invalid/authorize?state=${secret}`,
|
||||
request: { headers: { Authorization: secret } },
|
||||
});
|
||||
jest.spyOn(sdkAuth, 'startAuthorization').mockRejectedValueOnce(error);
|
||||
|
||||
await expect(
|
||||
MCPOAuthHandler.initiateOAuthFlow(
|
||||
'logging-server',
|
||||
server.url,
|
||||
'logging-user',
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
[`127.0.0.1:${server.port}`],
|
||||
),
|
||||
).rejects.toBe(error);
|
||||
|
||||
const output = inspect(
|
||||
logs.flatMap((spy) => spy.mock.calls),
|
||||
{ depth: null },
|
||||
);
|
||||
expect(output.includes(secret)).toBe(false);
|
||||
expect(logger.error).toHaveBeenCalledWith('[MCPOAuth] startAuthorization failed:', {
|
||||
type: 'Error',
|
||||
status: 400,
|
||||
});
|
||||
expect(logger.error).toHaveBeenCalledWith('[MCPOAuth] Failed to initiate OAuth flow', {
|
||||
error: { type: 'Error', status: 400 },
|
||||
serverName: 'logging-server',
|
||||
userId: 'logging-user',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -219,7 +219,10 @@ export class MCPOAuthHandler {
|
|||
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post', 'none'],
|
||||
};
|
||||
|
||||
logger.debug(`[MCPOAuth] Using fallback metadata:`, fallbackMetadata);
|
||||
logger.debug('[MCPOAuth] Using fallback authorization capabilities', {
|
||||
grant_types_supported: fallbackMetadata.grant_types_supported,
|
||||
token_endpoint_auth_methods_supported: fallbackMetadata.token_endpoint_auth_methods_supported,
|
||||
});
|
||||
return {
|
||||
metadata: fallbackMetadata,
|
||||
resourceMetadata,
|
||||
|
|
@ -1013,9 +1016,13 @@ export class MCPOAuthHandler {
|
|||
...(tenantId && { tenantId }),
|
||||
};
|
||||
|
||||
logger.debug(
|
||||
`[MCPOAuth] Authorization URL generated: ${sanitizeUrlForLogging(authorizationUrl.toString())}`,
|
||||
);
|
||||
logger.debug('[MCPOAuth] Authorization flow ready', {
|
||||
flowId,
|
||||
serverName,
|
||||
clientSource: flowMetadata.clientSource,
|
||||
hasClientSecret: Boolean(clientInfo.client_secret),
|
||||
hasResourceMetadata: Boolean(resourceMetadata),
|
||||
});
|
||||
return {
|
||||
authorizationUrl: authorizationUrl.toString(),
|
||||
flowId,
|
||||
|
|
@ -1111,7 +1118,7 @@ export class MCPOAuthHandler {
|
|||
} catch (error) {
|
||||
logger.warn(
|
||||
`[MCPOAuth] Failed to look up existing client registration, falling back to new registration`,
|
||||
{ error, serverName, userId },
|
||||
{ ...getSafeErrorMetadata(error), serverName, userId },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1155,9 +1162,6 @@ export class MCPOAuthHandler {
|
|||
codeVerifier = authResult.codeVerifier;
|
||||
|
||||
logger.debug(`[MCPOAuth] startAuthorization completed successfully`);
|
||||
logger.debug(
|
||||
`[MCPOAuth] Authorization URL: ${sanitizeUrlForLogging(authorizationUrl.toString())}`,
|
||||
);
|
||||
|
||||
/** Add cryptographic state parameter to the authorization URL */
|
||||
authorizationUrl.searchParams.set('state', state);
|
||||
|
|
@ -1227,19 +1231,19 @@ export class MCPOAuthHandler {
|
|||
...(tenantId && { tenantId }),
|
||||
};
|
||||
|
||||
logger.debug(
|
||||
`[MCPOAuth] Authorization URL generated for ${serverName}: ${sanitizeUrlForLogging(authorizationUrl.toString())}`,
|
||||
);
|
||||
|
||||
const result = {
|
||||
authorizationUrl: authorizationUrl.toString(),
|
||||
flowId,
|
||||
flowMetadata,
|
||||
};
|
||||
|
||||
logger.debug(
|
||||
`[MCPOAuth] Returning from initiateOAuthFlow with result ${flowId} for ${serverName}`,
|
||||
);
|
||||
logger.debug('[MCPOAuth] Authorization flow ready', {
|
||||
flowId,
|
||||
serverName,
|
||||
clientSource,
|
||||
hasClientSecret: Boolean(clientInfo.client_secret),
|
||||
hasResourceMetadata: Boolean(resourceMetadata),
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
logger.error('[MCPOAuth] Failed to initiate OAuth flow', {
|
||||
|
|
@ -1315,7 +1319,9 @@ export class MCPOAuthHandler {
|
|||
);
|
||||
} else if (metadata.resourceMetadata.resource) {
|
||||
resource = new URL(metadata.resourceMetadata.resource);
|
||||
logger.debug(`[MCPOAuth] Resource URL for flow ${flowId}: ${resource.toString()}`);
|
||||
logger.debug(
|
||||
`[MCPOAuth] Resource URL for flow ${flowId}: ${sanitizeUrlForLogging(resource)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue