diff --git a/packages/api/src/mcp/__tests__/dbSourced.integration.test.ts b/packages/api/src/mcp/__tests__/dbSourced.integration.test.ts index 981f537a57..966224541c 100644 --- a/packages/api/src/mcp/__tests__/dbSourced.integration.test.ts +++ b/packages/api/src/mcp/__tests__/dbSourced.integration.test.ts @@ -23,6 +23,8 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/ import type { MCPOptions } from 'librechat-data-provider'; import type { IUser } from '@librechat/data-schemas'; import type { Socket } from 'net'; +import { applyRequestHeaders, hasCustomUserVars, getMissingCustomUserVars } from '~/mcp/utils'; +import { getUserApiKeyVariable } from '~/mcp/registry/binding'; import { MCPConnection } from '~/mcp/connection'; import { processMCPEnv } from '~/utils/env'; @@ -208,10 +210,114 @@ describe('dbSourced header security – integration', () => { delete process.env.INTERNAL_API_KEY; }); + it('does not send a saved key to a new URL even when old field names are injected', async () => { + const original: MCPOptions = { + type: 'streamable-http', + url: 'https://trusted.example.com/mcp', + apiKey: { source: 'user', authorization_type: 'bearer' }, + }; + const updated: MCPOptions = { ...original, url: server.url }; + const oldField = getUserApiKeyVariable(original); + const newField = getUserApiKeyVariable(updated); + const resolved = processMCPEnv({ + options: { + ...updated, + customUserVars: { [newField]: { title: 'API Key', description: 'Per-user key' } }, + headers: { + Authorization: `Bearer {{${newField}}}`, + 'X-Stolen-Key': `{{${oldField}}}`, + 'X-Legacy-Key': '{{MCP_API_KEY}}', + }, + }, + dbSourced: true, + customUserVars: { [oldField]: 'another-users-secret', MCP_API_KEY: 'legacy-secret' }, + }); + conn = new MCPConnection({ + serverName: 'rebound-key', + serverConfig: resolved, + useSSRFProtection: false, + }); + if ('headers' in resolved) { + conn.setRequestHeaders(resolved.headers || {}); + } + await conn.connect(); + await conn.fetchTools(); + const captured = JSON.stringify(server.getLastHeaders()); + expect(captured).not.toContain('another-users-secret'); + expect(captured).not.toContain('legacy-secret'); + }); + + it('does not require or send a bound key shadowed by request authentication', async () => { + const options: MCPOptions = { + type: 'streamable-http', + url: server.url, + apiKey: { source: 'user', authorization_type: 'bearer' }, + }; + const field = getUserApiKeyVariable(options); + const declared: MCPOptions = { + ...options, + customUserVars: { [field]: { title: 'API Key', description: 'Per-user key' } }, + headers: { Authorization: `Bearer {{${field}}}` }, + requestHeaders: { authorization: 'Bearer request-secret' }, + }; + expect(hasCustomUserVars(declared)).toBe(false); + expect(getMissingCustomUserVars(declared)).toEqual([]); + const resolved = processMCPEnv({ + options: applyRequestHeaders(declared), + dbSourced: true, + customUserVars: { [field]: 'unused-user-secret' }, + }); + conn = new MCPConnection({ + serverName: 'shadowed-bound-key', + serverConfig: resolved, + useSSRFProtection: false, + }); + if ('headers' in resolved) { + conn.setRequestHeaders(resolved.headers || {}); + } + await conn.connect(); + await conn.fetchTools(); + const captured = server.getLastHeaders(); + expect(captured.authorization).toBe('Bearer request-secret'); + expect(JSON.stringify(captured)).not.toContain('unused-user-secret'); + }); + + it('sends the saved bound key after a fragment-only URL edit', async () => { + const original: MCPOptions = { + type: 'streamable-http', + url: `${server.url}#old`, + apiKey: { source: 'user', authorization_type: 'bearer' }, + }; + const field = getUserApiKeyVariable(original); + const updated: MCPOptions = { ...original, url: `${server.url}#new` }; + expect(getUserApiKeyVariable(updated)).toBe(field); + const resolved = processMCPEnv({ + options: { + ...updated, + customUserVars: { [field]: { title: 'API Key', description: 'Per-user key' } }, + headers: { Authorization: `Bearer {{${field}}}` }, + }, + dbSourced: true, + customUserVars: { [field]: 'saved-user-secret' }, + }); + conn = new MCPConnection({ + serverName: 'fragment-bound-key', + serverConfig: resolved, + useSSRFProtection: false, + }); + if ('headers' in resolved) { + conn.setRequestHeaders(resolved.headers || {}); + } + await conn.connect(); + await conn.fetchTools(); + expect(server.getLastHeaders().authorization).toBe('Bearer saved-user-secret'); + }); + it('DB-sourced: resolves {{MCP_API_KEY}} via customUserVars', async () => { const options: MCPOptions = { type: 'streamable-http', url: server.url, + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', }, @@ -346,6 +452,7 @@ describe('dbSourced header security – integration', () => { const options: MCPOptions = { type: 'streamable-http', url: server.url, + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', 'X-Env-Leak': '${SECRET_DB_URL}', @@ -458,6 +565,11 @@ describe('dbSourced header security – integration', () => { const options: MCPOptions = { type: 'streamable-http', url: server.url, + customUserVars: { + API_TOKEN: { title: 'Token', description: 'Per-user token' }, + WORKSPACE_ID: { title: 'Workspace', description: 'Per-user workspace' }, + REGION: { title: 'Region', description: 'Per-user region' }, + }, headers: { Authorization: 'Bearer {{API_TOKEN}}', 'X-Workspace': '{{WORKSPACE_ID}}', @@ -498,6 +610,7 @@ describe('dbSourced header security – integration', () => { const options: MCPOptions = { type: 'streamable-http', url: server.url, + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', }, diff --git a/packages/api/src/mcp/__tests__/utils.test.ts b/packages/api/src/mcp/__tests__/utils.test.ts index f3aec6ff0f..ea39bc18d8 100644 --- a/packages/api/src/mcp/__tests__/utils.test.ts +++ b/packages/api/src/mcp/__tests__/utils.test.ts @@ -1575,46 +1575,74 @@ describe('waitUntilDeadline', () => { }); }); -describe('shadowed generated user API keys', () => { - const config: ParsedServerConfig = { - type: 'streamable-http', - url: 'https://mcp.example.test/mcp', - apiKey: { source: 'user', authorization_type: 'bearer' }, - headers: { Authorization: 'Bearer {{MCP_API_KEY}}' }, - requestHeaders: { authorization: 'Bearer request-secret' }, - customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Generated key' } }, - }; - - it('removes only the unused generated requirement and preserves the declaration', () => { - expect(hasCustomUserVars(config)).toBe(false); - expect(getMissingCustomUserVars(config)).toEqual([]); - const effective = applyRequestHeaders(config); - expect(effective.customUserVars).toEqual({}); - expect(getMissingCustomUserVars(effective)).toEqual([]); - expect(applyRequestHeaders(effective)).toBe(effective); - expect(getMissingCustomUserVars(toCatalogConnectionConfig(config))).toEqual(['MCP_API_KEY']); - expect(config.customUserVars).toHaveProperty('MCP_API_KEY'); - }); - - it.each([ - { requestHeaders: { authorization: 'Bearer {{MCP_API_KEY}}' } }, - { headers: { Authorization: 'Bearer {{MCP_API_KEY}}', 'X-Key': '{{MCP_API_KEY}}' } }, - { url: 'https://mcp.example.test/{{MCP_API_KEY}}' }, - { oauth_headers: { 'X-Key': '{{MCP_API_KEY}}' } }, - { requestHeaders: { 'X-Unrelated': 'value' } }, - ])('retains a key referenced by the effective configuration: %j', (fields) => { - expect(getMissingCustomUserVars({ ...config, ...fields })).toEqual(['MCP_API_KEY']); - }); - - it('retains explicitly declared variables', () => { - const declared = { - ...config, - customUserVars: { - ...config.customUserVars, - REGION: { title: 'Region', description: 'Required region' }, - }, +describe.each(['MCP_API_KEY', `MCP_API_KEY_${'a'.repeat(64)}`])( + 'shadowed generated user API key %s', + (variable) => { + const config: ParsedServerConfig = { + type: 'streamable-http', + url: 'https://mcp.example.test/mcp', + apiKey: { source: 'user', authorization_type: 'bearer' }, + headers: { Authorization: `Bearer {{${variable}}}` }, + requestHeaders: { authorization: 'Bearer request-secret' }, + customUserVars: { [variable]: { title: 'API Key', description: 'Generated key' } }, }; - expect(getMissingCustomUserVars(declared)).toEqual(['REGION']); - expect(hasCustomUserVars(declared)).toBe(true); - }); -}); + + it('removes only the unused generated requirement and preserves the declaration', () => { + expect(hasCustomUserVars(config)).toBe(false); + expect(getMissingCustomUserVars(config)).toEqual([]); + const effective = applyRequestHeaders(config); + expect(effective.customUserVars).toEqual({}); + expect(getMissingCustomUserVars(effective)).toEqual([]); + expect(applyRequestHeaders(effective)).toBe(effective); + expect(getMissingCustomUserVars(toCatalogConnectionConfig(config))).toEqual([variable]); + expect(config.customUserVars).toHaveProperty(variable); + }); + + it.each([ + { requestHeaders: { authorization: `Bearer {{${variable}}}` } }, + { headers: { Authorization: `Bearer {{${variable}}}`, 'X-Key': `{{${variable}}}` } }, + { url: `https://mcp.example.test/{{${variable}}}` }, + { oauth_headers: { 'X-Key': `{{${variable}}}` } }, + { oauth: { client_id: `{{${variable}}}` } }, + { args: [`{{${variable}}}`] }, + { env: { API_KEY: `{{${variable}}}` } }, + { requestHeaders: { 'X-Unrelated': 'value' } }, + ])('retains a key referenced by the effective configuration: %j', (fields) => { + expect(getMissingCustomUserVars({ ...config, ...fields })).toEqual([variable]); + }); + + it('retains explicitly declared variables', () => { + const declared = { + ...config, + customUserVars: { + ...config.customUserVars, + REGION: { title: 'Region', description: 'Required region' }, + MCP_API_KEY_EXTRA: { title: 'Explicit', description: 'Not a generated key' }, + }, + }; + expect(getMissingCustomUserVars(declared)).toEqual(['REGION', 'MCP_API_KEY_EXTRA']); + expect(hasCustomUserVars(declared)).toBe(true); + }); + it('retains explicit keys outside user API-key authentication', () => { + expect(getMissingCustomUserVars({ ...config, apiKey: undefined })).toEqual([variable]); + }); + + it('retains a custom-header key when the override still uses it', () => { + const declared = { + ...config, + apiKey: { + source: 'user' as const, + authorization_type: 'custom' as const, + custom_header: 'X-Key', + }, + headers: { 'X-Key': `{{${variable}}}` }, + requestHeaders: { 'x-key': 'request-secret' }, + }; + expect(getMissingCustomUserVars(declared)).toEqual([]); + expect(getMissingCustomUserVars(toCatalogConnectionConfig(declared))).toEqual([variable]); + expect( + getMissingCustomUserVars({ ...declared, requestHeaders: { 'x-key': `{{${variable}}}` } }), + ).toEqual([variable]); + }); + }, +); diff --git a/packages/api/src/mcp/headers.ts b/packages/api/src/mcp/headers.ts index 63d6af270a..9fa4c7fdc6 100644 --- a/packages/api/src/mcp/headers.ts +++ b/packages/api/src/mcp/headers.ts @@ -2,6 +2,11 @@ import type { MCPOptions } from 'librechat-data-provider'; type ApiKeyConfig = Partial> | null | undefined; +/** Recognizes only server-generated API key fields, not similarly named explicit variables. */ +export function isGeneratedUserApiKeyVariable(name: string): boolean { + return /^MCP_API_KEY(?:_[a-f0-9]{64})?$/.test(name); +} + function getApiKeyHeaderName(apiKey: ApiKeyConfig): string { return apiKey?.authorization_type === 'custom' ? apiKey.custom_header || 'X-Api-Key' diff --git a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts index 37f1096e3d..291ae55da1 100644 --- a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts +++ b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts @@ -24,6 +24,10 @@ let MCPOAuthHandler: MCPOAuthHandlerType; let createModels: CreateModelsType; let createMethods: CreateMethodsType; let RoleBits: RoleBitsType; +let encrypt: typeof import('@librechat/data-schemas').encrypt; +let getUserMCPAuthMap: typeof import('~/mcp/auth').getUserMCPAuthMap; +let processMCPEnv: typeof import('~/utils/env').processMCPEnv; +let getMissingCustomUserVars: typeof import('~/mcp/utils').getMissingCustomUserVars; let getMCPAppToolsPublicationGeneration: typeof import('~/mcp/toolsChanged').getMCPAppToolsPublicationGeneration; // Test data helpers @@ -61,6 +65,10 @@ beforeAll(async () => { createModels = dataSchemas.createModels; createMethods = dataSchemas.createMethods; RoleBits = dataSchemas.RoleBits; + encrypt = dataSchemas.encrypt; + ({ getUserMCPAuthMap } = await import('~/mcp/auth')); + ({ processMCPEnv } = await import('~/utils/env')); + ({ getMissingCustomUserVars } = await import('~/mcp/utils')); // Mock logger after import (suppress logs during tests) jest.spyOn(dataSchemas.logger, 'error').mockReturnValue(dataSchemas.logger); @@ -100,6 +108,7 @@ beforeEach(async () => { // Clear collections except AccessRole await mongoose.models.MCPServer.deleteMany({}); await mongoose.models.Agent.deleteMany({}); + await mongoose.models.PluginAuth.deleteMany({}); await mongoose.models.AclEntry.deleteMany({}); }); @@ -785,16 +794,16 @@ describe('ServerConfigsDB', () => { headers?: Record; }; - // Should have customUserVars with MCP_API_KEY - expect(retrieved?.customUserVars).toBeDefined(); - expect(retrieved?.customUserVars?.MCP_API_KEY).toEqual({ + const variable = Object.keys(retrieved!.customUserVars!)[0]; + expect(variable).toMatch(/^MCP_API_KEY_[a-f0-9]{64}$/); + expect(retrieved?.customUserVars?.[variable]).toEqual({ title: 'API Key', description: 'Your API key for this MCP server', }); // Should have headers with placeholder expect(retrievedWithHeaders?.headers).toBeDefined(); - expect(retrievedWithHeaders?.headers?.Authorization).toBe('Bearer {{MCP_API_KEY}}'); + expect(retrievedWithHeaders?.headers?.Authorization).toBe(`Bearer {{${variable}}}`); // Key should be undefined (user provides it) expect(retrieved?.apiKey?.key).toBeUndefined(); @@ -819,11 +828,420 @@ describe('ServerConfigsDB', () => { headers?: Record; }; - expect(retrievedWithHeaders?.headers?.['X-My-Api-Key']).toBe('{{MCP_API_KEY}}'); + const variable = Object.keys(retrieved!.customUserVars!)[0]; + expect(retrievedWithHeaders?.headers?.['X-My-Api-Key']).toBe(`{{${variable}}}`); expect(retrievedWithHeaders?.headers?.Authorization).toBeUndefined(); }); }); + describe('per-user API key destination binding', () => { + const config: Extract = { + type: 'streamable-http', + url: 'https://trusted.example.com/mcp', + title: 'Shared User Key Server', + apiKey: { source: 'user', authorization_type: 'bearer' }, + }; + + async function saveUserKey( + serverName: string, + authField: string, + ): Promise> { + await dbMethods.updatePluginAuth({ + userId: userId2, + pluginKey: `mcp_${serverName}`, + authField, + value: await encrypt('another-users-secret'), + }); + const authMap = await getUserMCPAuthMap({ + userId: userId2, + servers: [serverName], + findPluginAuthsByKeys: dbMethods.findPluginAuthsByKeys, + }); + return authMap[`mcp_${serverName}`]; + } + + const changes: Array<[string, (original: typeof config) => ParsedServerConfig]> = [ + ['URL', (original) => ({ ...original, url: 'https://attacker.example.com/mcp' })], + ['URL query', (original) => ({ ...original, url: `${config.url}?tenant=other` })], + ['proxy', (original) => ({ ...original, proxy: 'http://attacker.example.com/' })], + ['transport', (original) => ({ ...original, type: 'sse' })], + [ + 'authorization type', + (original) => ({ ...original, apiKey: { source: 'user', authorization_type: 'basic' } }), + ], + [ + 'custom header', + (original) => ({ + ...original, + apiKey: { source: 'user', authorization_type: 'custom', custom_header: 'X-Key' }, + }), + ], + [ + 'OAuth destination', + (original) => ({ ...original, oauth: { token_url: 'https://attacker.example.com/token' } }), + ], + [ + 'OAuth revocation destination', + (original) => ({ + ...original, + oauth: { revocation_endpoint: 'https://attacker.example.com/revoke' }, + }), + ], + ]; + + it.each(changes)( + 'requires each user to re-enter their key after a %s change', + async (_field, change) => { + const created = await serverConfigsDB.add('temp-name', config, userId); + const oldField = Object.keys(created.config.customUserVars!)[0]; + const savedVars = await saveUserKey(created.serverName, oldField); + expect( + JSON.stringify(processMCPEnv({ options: created.config, customUserVars: savedVars })), + ).toContain('another-users-secret'); + + await serverConfigsDB.update(created.serverName, change(config), userId); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect(updated).toBeDefined(); + expect(getMissingCustomUserVars(updated!, savedVars)).toHaveLength(1); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).not.toContain('another-users-secret'); + + const newField = Object.keys(updated!.customUserVars!)[0]; + const replacementVars = await saveUserKey(created.serverName, newField); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: replacementVars })), + ).toContain('another-users-secret'); + }, + ); + + it.each(['user', 'admin', 'none'] as const)( + 'does not resolve old keys injected into headers after switching to %s authentication', + async (source) => { + const created = await serverConfigsDB.add('temp-name', config, userId); + const oldField = Object.keys(created.config.customUserVars!)[0]; + const savedVars = await saveUserKey(created.serverName, oldField); + await serverConfigsDB.update( + created.serverName, + { + ...config, + url: 'https://attacker.example.com/mcp', + apiKey: + source === 'none' + ? undefined + : { source, authorization_type: 'bearer', key: 'editor-key' }, + headers: { 'X-Stolen-Key': `{{${oldField}}}` }, + requestHeaders: { 'X-Stolen-Key': `{{${oldField}}}` }, + }, + userId, + ); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).not.toContain('another-users-secret'); + }, + ); + + it('does not recover old keys by removing and re-adding user authentication', async () => { + const created = await serverConfigsDB.add('temp-name', config, userId); + const oldField = Object.keys(created.config.customUserVars!)[0]; + const savedVars = await saveUserKey(created.serverName, oldField); + await serverConfigsDB.update(created.serverName, { ...config, apiKey: undefined }, userId); + await serverConfigsDB.update( + created.serverName, + { + ...config, + url: 'https://attacker.example.com/mcp', + headers: { 'X-Stolen-Key': `{{${oldField}}}` }, + }, + userId, + ); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect(getMissingCustomUserVars(updated!, savedVars)).toHaveLength(1); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).not.toContain('another-users-secret'); + }); + + it('does not reuse saved keys when the same server name is recreated at a new URL', async () => { + const created = await serverConfigsDB.add('temp-name', config, userId); + const oldField = Object.keys(created.config.customUserVars!)[0]; + const savedVars = await saveUserKey(created.serverName, oldField); + await serverConfigsDB.remove(created.serverName, userId); + const recreated = await serverConfigsDB.add( + 'temp-name', + { + ...config, + url: 'https://attacker.example.com/mcp', + headers: { 'X-Stolen-Key': `{{${oldField}}}` }, + }, + userId, + ); + expect(recreated.serverName).toBe(created.serverName); + expect(getMissingCustomUserVars(recreated.config, savedVars)).toHaveLength(1); + expect( + JSON.stringify(processMCPEnv({ options: recreated.config, customUserVars: savedVars })), + ).not.toContain('another-users-secret'); + }); + + it.each(['streamable-http', 'sse'] as const)( + 'preserves a saved %s key when only the URL fragment changes', + async (type) => { + const original: ParsedServerConfig = { ...config, type, url: `${config.url}#old` }; + const created = await serverConfigsDB.add('temp-name', original, userId); + const field = Object.keys(created.config.customUserVars!)[0]; + const savedVars = await saveUserKey(created.serverName, field); + await serverConfigsDB.update( + created.serverName, + { ...original, url: `${config.url}#new` }, + userId, + ); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect(Object.keys(updated!.customUserVars!)).toEqual([field]); + expect(getMissingCustomUserVars(updated!, savedVars)).toEqual([]); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).toContain('another-users-secret'); + }, + ); + + it('retains an already-stored bound field for a fragment-only edit', async () => { + const original: ParsedServerConfig = { ...config, url: `${config.url}#old` }; + const created = await serverConfigsDB.add('temp-name', original, userId); + const field = `MCP_API_KEY_${'b'.repeat(64)}`; + await mongoose.models.MCPServer.updateOne( + { serverName: created.serverName }, + { + $set: { + config: { + ...original, + customUserVars: { + [field]: { title: 'API Key', description: 'Previously bound key' }, + }, + headers: { Authorization: `Bearer {{${field}}}` }, + }, + }, + }, + ); + const savedVars = await saveUserKey(created.serverName, field); + await serverConfigsDB.update( + created.serverName, + { ...original, url: `${config.url}#new` }, + userId, + ); + const equivalent = await serverConfigsDB.get(created.serverName, userId); + expect(getMissingCustomUserVars(equivalent!, savedVars)).toEqual([]); + expect( + JSON.stringify(processMCPEnv({ options: equivalent!, customUserVars: savedVars })), + ).toContain('another-users-secret'); + await serverConfigsDB.update( + created.serverName, + { + ...original, + url: 'https://attacker.example.com/mcp#new', + }, + userId, + ); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect(getMissingCustomUserVars(updated!, savedVars)).toHaveLength(1); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).not.toContain('another-users-secret'); + }); + + it.each([ + 'MCP_API_KEY_EXTRA', + `MCP_API_KEY_${'a'.repeat(63)}`, + `MCP_API_KEY_${'g'.repeat(64)}`, + `MCP_API_KEY_${'a'.repeat(64)}_EXTRA`, + ])('preserves explicit variable %s across add, update, and upsert', async (explicitField) => { + const staleField = `MCP_API_KEY_${'c'.repeat(64)}`; + const declaration = { title: 'Explicit setting', description: 'Required per-user setting' }; + const original: typeof config = { + ...config, + customUserVars: { + [explicitField]: declaration, + MCP_API_KEY: { title: 'API Key', description: 'Legacy generated key' }, + [staleField]: { title: 'API Key', description: 'Stale generated key' }, + }, + headers: { 'X-Setting': `{{${explicitField}}}` }, + requestHeaders: { 'X-Chat-Setting': `{{${explicitField}}}` }, + }; + const created = await serverConfigsDB.add('temp-name', original, userId); + const field = Object.keys(created.config.customUserVars!).find( + (name) => name !== explicitField, + )!; + expect(field).toMatch(/^MCP_API_KEY_[a-f0-9]{64}$/); + const savedKey = await saveUserKey(created.serverName, field); + expect(created.config.customUserVars).toEqual({ + [explicitField]: declaration, + [field]: { title: 'API Key', description: 'Your API key for this MCP server' }, + }); + expect(getMissingCustomUserVars(created.config, savedKey)).toEqual([explicitField]); + await dbMethods.updatePluginAuth({ + userId: userId2, + pluginKey: `mcp_${created.serverName}`, + authField: explicitField, + value: await encrypt('explicit-setting'), + }); + const loadVars = async () => { + const authMap = await getUserMCPAuthMap({ + userId: userId2, + servers: [created.serverName], + findPluginAuthsByKeys: dbMethods.findPluginAuthsByKeys, + }); + return authMap[`mcp_${created.serverName}`]; + }; + const assertResolved = async (current: ParsedServerConfig) => { + const vars = await loadVars(); + expect(current.customUserVars).toEqual({ + [explicitField]: declaration, + [field]: { title: 'API Key', description: 'Your API key for this MCP server' }, + }); + expect(getMissingCustomUserVars(current, vars)).toEqual([]); + expect(processMCPEnv({ options: current, customUserVars: vars })).toMatchObject({ + headers: { + Authorization: 'Bearer another-users-secret', + 'X-Setting': 'explicit-setting', + }, + }); + }; + await assertResolved(created.config); + await serverConfigsDB.update( + created.serverName, + { ...original, description: 'Updated' }, + userId, + ); + await assertResolved((await serverConfigsDB.get(created.serverName, userId))!); + await serverConfigsDB.upsert( + created.serverName, + { ...original, description: 'Upserted' }, + userId, + ); + await assertResolved((await serverConfigsDB.get(created.serverName, userId))!); + + await serverConfigsDB.update( + created.serverName, + { + ...original, + url: 'https://replacement.example.com/mcp', + customUserVars: { + ...original.customUserVars, + [field]: { title: 'API Key', description: 'Previous generated key' }, + }, + headers: { ...original.headers, 'X-Old-Key': `{{${field}}}` }, + }, + userId, + ); + const rebound = (await serverConfigsDB.get(created.serverName, userId))!; + const vars = await loadVars(); + const reboundField = Object.keys(rebound.customUserVars!).find( + (name) => name !== explicitField, + )!; + expect(reboundField).not.toBe(field); + expect(rebound.customUserVars?.[explicitField]).toEqual(declaration); + expect(Object.keys(rebound.customUserVars!)).toHaveLength(2); + expect(getMissingCustomUserVars(rebound, vars)).toEqual([reboundField]); + const resolved = processMCPEnv({ options: rebound, customUserVars: vars }); + expect(resolved).toMatchObject({ headers: { 'X-Setting': 'explicit-setting' } }); + expect(JSON.stringify(resolved)).not.toContain('another-users-secret'); + }); + + it('preserves saved keys for equivalent and cosmetic updates', async () => { + const created = await serverConfigsDB.add('temp-name', config, userId); + const field = Object.keys(created.config.customUserVars!)[0]; + const savedVars = await saveUserKey(created.serverName, field); + await serverConfigsDB.update( + created.serverName, + { + ...config, + type: 'http', + url: 'https://TRUSTED.EXAMPLE.COM:443/mcp', + description: 'Updated description', + }, + userId, + ); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect(getMissingCustomUserVars(updated!, savedVars)).toEqual([]); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).toContain('another-users-secret'); + }); + + it('binds to a restored OAuth revocation destination when an update omits it', async () => { + const oauth = { + client_id: 'shared-client', + client_secret: 'shared-oauth-secret', + authorization_url: 'https://trusted.example.com/authorize', + token_url: 'https://trusted.example.com/token', + revocation_endpoint: 'https://trusted.example.com/revoke', + }; + const created = await serverConfigsDB.add('temp-name', { ...config, oauth }, userId); + const field = Object.keys(created.config.customUserVars!)[0]; + const savedVars = await saveUserKey(created.serverName, field); + await serverConfigsDB.update( + created.serverName, + { + ...config, + description: 'Cosmetic change', + oauth: { + client_id: oauth.client_id, + authorization_url: oauth.authorization_url, + token_url: oauth.token_url, + }, + }, + userId, + ); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect(updated?.oauth?.revocation_endpoint).toBe(oauth.revocation_endpoint); + expect(getMissingCustomUserVars(updated!, savedVars)).toEqual([]); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).toContain('another-users-secret'); + }); + + it('preserves legacy keys until the destination changes, then ignores them', async () => { + const created = await serverConfigsDB.add('temp-name', config, userId); + await mongoose.models.MCPServer.updateOne( + { serverName: created.serverName }, + { + $set: { + config: { + ...config, + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Legacy key' } }, + headers: { Authorization: 'Bearer {{MCP_API_KEY}}' }, + }, + }, + }, + ); + const savedVars = await saveUserKey(created.serverName, 'MCP_API_KEY'); + await serverConfigsDB.update( + created.serverName, + { ...config, description: 'Cosmetic change' }, + userId, + ); + const equivalent = await serverConfigsDB.get(created.serverName, userId); + expect(getMissingCustomUserVars(equivalent!, savedVars)).toEqual([]); + expect( + JSON.stringify(processMCPEnv({ options: equivalent!, customUserVars: savedVars })), + ).toContain('another-users-secret'); + await serverConfigsDB.update( + created.serverName, + { + ...config, + url: 'https://attacker.example.com/mcp', + headers: { 'X-Stolen-Key': '{{MCP_API_KEY}}' }, + }, + userId, + ); + const updated = await serverConfigsDB.get(created.serverName, userId); + expect(getMissingCustomUserVars(updated!, savedVars)).toHaveLength(1); + expect( + JSON.stringify(processMCPEnv({ options: updated!, customUserVars: savedVars })), + ).not.toContain('another-users-secret'); + }); + }); + describe('credential placeholder sanitization', () => { it('should strip LIBRECHAT_OPENID placeholders from headers on add()', async () => { const config: ParsedServerConfig & { headers?: Record } = { diff --git a/packages/api/src/mcp/registry/binding.ts b/packages/api/src/mcp/registry/binding.ts index b589c1a1ca..bc9b2ecf8c 100644 --- a/packages/api/src/mcp/registry/binding.ts +++ b/packages/api/src/mcp/registry/binding.ts @@ -1,4 +1,6 @@ +import { createHash } from 'crypto'; import type { MCPOptions } from '~/mcp/types'; +import { isGeneratedUserApiKeyVariable } from '~/mcp/headers'; import { MCPApiKeyReentryRequiredError } from '~/mcp/errors'; function getUrl(config: MCPOptions): string | undefined { @@ -9,13 +11,17 @@ function getProxy(config: MCPOptions): string | undefined { return 'proxy' in config ? config.proxy : undefined; } -function normalizeUrl(value?: string): string | undefined { +function normalizeUrl(value?: string, stripFragment = false): string | undefined { if (!value) { return value; } try { - return new URL(value).href; + const url = new URL(value); + if (stripFragment) { + url.hash = ''; + } + return url.href; } catch { return value; } @@ -32,40 +38,62 @@ function normalizeCustomHeader(apiKey: MCPOptions['apiKey']): string | undefined return (apiKey.custom_header || 'X-Api-Key').toLowerCase(); } +function apiKeyBinding(config: MCPOptions): Record { + return { + url: normalizeUrl(getUrl(config), true), + type: normalizeTransport(config.type), + proxy: normalizeUrl(getProxy(config), true), + 'apiKey.authorization_type': config.apiKey?.authorization_type, + 'apiKey.custom_header': normalizeCustomHeader(config.apiKey), + }; +} + /** Returns fields that would move an omitted, stored admin key to a new request boundary. */ export function getChangedApiKeyBindingFields( existingConfig: MCPOptions, updatedConfig: MCPOptions, ): string[] { - const existingApiKey = existingConfig.apiKey; - const updatedApiKey = updatedConfig.apiKey; const preservesStoredKey = - existingApiKey?.source === 'admin' && - !!existingApiKey.key && - updatedApiKey?.source === 'admin' && - !updatedApiKey.key; + existingConfig.apiKey?.source === 'admin' && + !!existingConfig.apiKey.key && + updatedConfig.apiKey?.source === 'admin' && + !updatedConfig.apiKey.key; if (!preservesStoredKey) { return []; } - const fields = [ - ['url', normalizeUrl(getUrl(existingConfig)), normalizeUrl(getUrl(updatedConfig))], - ['type', normalizeTransport(existingConfig.type), normalizeTransport(updatedConfig.type)], - ['proxy', normalizeUrl(getProxy(existingConfig)), normalizeUrl(getProxy(updatedConfig))], - [ - 'apiKey.authorization_type', - existingApiKey.authorization_type, - updatedApiKey.authorization_type, - ], - [ - 'apiKey.custom_header', - normalizeCustomHeader(existingApiKey), - normalizeCustomHeader(updatedApiKey), - ], - ] as const; + const existing = apiKeyBinding(existingConfig); + const updated = apiKeyBinding(updatedConfig); + return Object.keys(existing).filter((field) => existing[field] !== updated[field]); +} - return fields.filter(([, existing, updated]) => existing !== updated).map(([field]) => field); +function userApiKeyBinding(config: MCPOptions): string { + return JSON.stringify([ + apiKeyBinding(config), + normalizeUrl(config.oauth?.authorization_url, true), + normalizeUrl(config.oauth?.token_url, true), + /** redirect_uri is sent as an OAuth parameter, not used as an outbound request URL. */ + normalizeUrl(config.oauth?.redirect_uri), + normalizeUrl(config.oauth?.revocation_endpoint, true), + config.oauth?.client_id, + ]); +} + +/** Uses the existing auth-field storage to bind each user's key to the request destination. + * Retains stored field names only for equivalent boundaries, including legacy names and + * names generated by earlier URL normalization. */ +export function getUserApiKeyVariable(config: MCPOptions, existingConfig?: MCPOptions): string { + const binding = userApiKeyBinding(config); + if (existingConfig?.apiKey?.source === 'user' && binding === userApiKeyBinding(existingConfig)) { + const variable = Object.keys(existingConfig.customUserVars ?? {}).find( + isGeneratedUserApiKeyVariable, + ); + if (variable) { + return variable; + } + } + return `MCP_API_KEY_${createHash('sha256').update(binding).digest('hex')}`; } /** Requires a replacement key before a stored admin credential can cross request boundaries. */ diff --git a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts index ffe7abe631..86327229b3 100644 --- a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts +++ b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts @@ -10,10 +10,11 @@ import type { AllMethods, MCPServerDocument, IAgent } from '@librechat/data-sche import type { IServerConfigsRepositoryInterface } from '~/mcp/registry/ServerConfigsRepositoryInterface'; import type { ParsedServerConfig, AddServerResult } from '~/mcp/types'; import type { ResolvedPrincipal } from '~/types/principal'; -import { requireApiKeyReentryForRebinding } from '~/mcp/registry/binding'; +import { getUserApiKeyVariable, requireApiKeyReentryForRebinding } from '~/mcp/registry/binding'; import { normalizeLegacyHeaderMaps } from '~/mcp/registry/compat'; import { MCPOAuthSecretReentryRequiredError } from '~/mcp/errors'; import { AccessControlService } from '~/acl/accessControlService'; +import { isGeneratedUserApiKeyVariable } from '~/mcp/headers'; /** * Regex patterns for credential/env placeholders that should not be allowed in user-provided configs. @@ -356,9 +357,6 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface { sanitizeConfigHeaderMaps(config), ); - /** Transformed user-provided API key config (adds customUserVars and headers) */ - configToSave = this.transformUserApiKeyConfig(configToSave); - const existingOAuth = existingServer?.config?.oauth; const existingOAuthSecret = existingOAuth?.client_secret; const preservesOAuthSecret = @@ -374,6 +372,9 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface { } } + /** Transformed user-provided API key config (adds customUserVars and headers) */ + configToSave = this.transformUserApiKeyConfig(configToSave, existingServer?.config); + /** Encrypted config before storing in database */ configToSave = await this.encryptConfig(configToSave); @@ -656,7 +657,10 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface { * @param config - The server config to transform * @returns The transformed config with customUserVars and headers set up */ - private transformUserApiKeyConfig(config: ParsedServerConfig): ParsedServerConfig { + private transformUserApiKeyConfig( + config: ParsedServerConfig, + existingConfig?: ParsedServerConfig, + ): ParsedServerConfig { if (!config.apiKey || config.apiKey.source !== 'user') { return config; } @@ -667,18 +671,28 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface { ? result.apiKey!.custom_header || 'X-Api-Key' : 'Authorization'; + const variable = getUserApiKeyVariable(config, existingConfig); + const placeholder = `{{${variable}}}`; let headerValue: string; if (result.apiKey!.authorization_type === 'basic') { - headerValue = 'Basic {{MCP_API_KEY}}'; + headerValue = `Basic ${placeholder}`; } else if (result.apiKey!.authorization_type === 'bearer') { - headerValue = 'Bearer {{MCP_API_KEY}}'; + headerValue = `Bearer ${placeholder}`; } else { - headerValue = '{{MCP_API_KEY}}'; + headerValue = placeholder; } - result.customUserVars = { + const customUserVars: NonNullable = { ...result.customUserVars, - MCP_API_KEY: { + }; + for (const name of Object.keys(customUserVars)) { + if (isGeneratedUserApiKeyVariable(name)) { + delete customUserVars[name]; + } + } + result.customUserVars = { + ...customUserVars, + [variable]: { title: 'API Key', description: 'Your API key for this MCP server', }, diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.ts index e393651903..5396dbcc94 100644 --- a/packages/api/src/mcp/utils.ts +++ b/packages/api/src/mcp/utils.ts @@ -10,9 +10,9 @@ import { import type { AgentToolOptions, MCPOptions } from 'librechat-data-provider'; import type { ParsedServerConfig } from '~/mcp/types'; import type { RequestBody } from '~/types'; +import { isApiKeyHeaderOverridden, isGeneratedUserApiKeyVariable } from './headers'; import { isDirectOpenIDBearerRecoveryEnabled } from '~/mcp/openid'; import { ALLOWED_BODY_FIELDS, isPluginSourced } from '~/utils/env'; -import { isApiKeyHeaderOverridden } from './headers'; import { isEnabled } from '~/utils/common'; export const mcpToolPattern: RegExp = new RegExp(`^.+${Constants.mcp_delimiter}.+$`); @@ -296,12 +296,18 @@ function requiredCustomUserVars(config: UserScopedConnectionConfig): string[] { const keys = Object.keys(config.customUserVars ?? {}); if ( config.apiKey?.source !== 'user' || - !isApiKeyHeaderOverridden(config.apiKey, config.requestHeaders) || - placeholderBearingFields(config).some((value) => hasPlaceholder(value, /\{\{MCP_API_KEY\}\}/)) + !isApiKeyHeaderOverridden(config.apiKey, config.requestHeaders) ) { return keys; } - return keys.filter((key) => key !== 'MCP_API_KEY'); + const fields = placeholderBearingFields(config); + return keys.filter((key) => { + if (!isGeneratedUserApiKeyVariable(key)) { + return true; + } + const pattern = new RegExp(`\\{\\{${key}\\}\\}`); + return fields.some((value) => hasPlaceholder(value, pattern)); + }); } /** Checks the effective chat requirements, without weakening catalog-only credentials. */ diff --git a/packages/api/src/utils/env.spec.ts b/packages/api/src/utils/env.spec.ts index a0f8c43c08..c4597f8da9 100644 --- a/packages/api/src/utils/env.spec.ts +++ b/packages/api/src/utils/env.spec.ts @@ -1800,6 +1800,7 @@ describe('processMCPEnv', () => { source: 'user', authorization_type: 'bearer', }, + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', }, @@ -1877,6 +1878,7 @@ describe('processMCPEnv', () => { const options: MCPOptions = { type: 'streamable-http', url: 'https://api.example.com', + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', }, @@ -1993,6 +1995,7 @@ describe('processMCPEnv', () => { const options: MCPOptions = { type: 'streamable-http', url: '${DATABASE_URL}', + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', 'X-Env-Leak': '${TEST_API_KEY}', @@ -2025,6 +2028,7 @@ describe('processMCPEnv', () => { const options: MCPOptions = { type: 'streamable-http', url: 'https://api.example.com', + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', 'X-Env': '${TEST_API_KEY}', @@ -2052,6 +2056,7 @@ describe('processMCPEnv', () => { const options: MCPOptions = { type: 'stdio', command: 'mcp-server', + customUserVars: { MY_VAR: { title: 'Custom', description: 'Per-user variable' } }, args: ['--key', '${TEST_API_KEY}', '--custom', '{{MY_VAR}}'], env: { SECRET: '${DATABASE_URL}', @@ -2118,6 +2123,10 @@ describe('processMCPEnv', () => { const options: MCPOptions = { type: 'streamable-http', url: 'https://api.example.com', + customUserVars: { + MY_CLIENT_ID: { title: 'Client ID', description: 'Per-user client' }, + MY_CLIENT_SECRET: { title: 'Client secret', description: 'Per-user secret' }, + }, oauth: { client_id: '{{MY_CLIENT_ID}}', client_secret: '{{MY_CLIENT_SECRET}}', @@ -2141,6 +2150,7 @@ describe('processMCPEnv', () => { const options: MCPOptions = { type: 'streamable-http', url: 'https://api.example.com', + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', }, @@ -2160,6 +2170,7 @@ describe('processMCPEnv', () => { const options: MCPOptions = { type: 'streamable-http', url: '${DATABASE_URL}', + customUserVars: { MCP_API_KEY: { title: 'API Key', description: 'Per-user key' } }, headers: { Authorization: 'Bearer {{MCP_API_KEY}}', 'X-Env': '${TEST_API_KEY}', diff --git a/packages/api/src/utils/env.ts b/packages/api/src/utils/env.ts index d880fedfda..e980c272d1 100644 --- a/packages/api/src/utils/env.ts +++ b/packages/api/src/utils/env.ts @@ -394,7 +394,7 @@ export function processMCPEnv(params: { /** When true, only resolve customUserVars — skip env vars, user/OpenID/body placeholders (for DB-stored servers) */ dbSourced?: boolean; }): MCPOptions { - const { options, user, customUserVars, body } = params; + const { options, user, body } = params; if (options === null || options === undefined) { return options; @@ -416,6 +416,18 @@ export function processMCPEnv(params: { /** Derive dbSourced from explicit param OR from dbId on the options (failsafe for callers that forget the flag) */ const dbSourced = params.dbSourced ?? !!options.dbId; + /** A shared-server editor can inject old auth-field names into any template. Only + * server-declared variables may resolve, including destination-bound API key fields. */ + const userManaged = dbSourced || !!options.dbId || options.source === 'user'; + const customUserVars = + userManaged && params.customUserVars + ? Object.fromEntries( + Object.entries(params.customUserVars).filter(([name]) => + Object.prototype.hasOwnProperty.call(options.customUserVars ?? {}, name), + ), + ) + : params.customUserVars; + const newObj: MCPOptions = structuredClone(options); const adminHeader = getAdminApiKeyHeader(newObj.apiKey);