Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
💌 feat: Authenticate RUM Proxy Exports (#16114)
lia-by-librechat[bot]16a7e116efdd
diff --git a/.env.example b/.env.exampleindex fa196f5e3c..a85ba4c923 100644--- a/.env.example+++ b/.env.example@@ -378,6 +378,12 @@ NODE_MAX_OLD_SPACE_SIZE=6144# RUM_AUTH_MODE=proxy# RUM_PROXY_TARGET_URL=http://otel-collector:4318# RUM_PROXY_TIMEOUT_MS=10000+# Optional server-only Authorization header for the upstream collector. Kept in env+# as a deployment secret, never exposed through browser startup config.+# For ClickStack, use the raw ingestion API key (no Bearer prefix).+# RUM_PROXY_AUTHORIZATION=+# Use an HTTPS RUM_PROXY_TARGET_URL across trust boundaries. With authorization set,+# redirects are rejected; configure the final OTLP base URL, not a UI URL or /v1/traces.# Optional comma-separated first-party HTTPS origins/URLs that should receive traceparent headers.# Wildcards and non-HTTPS targets are ignored.diff --git a/api/server/routes/__tests__/config.rum.spec.js b/api/server/routes/__tests__/config.rum.spec.jsindex 2b0a5b20e2..4400888ac2 100644--- a/api/server/routes/__tests__/config.rum.spec.js+++ b/api/server/routes/__tests__/config.rum.spec.js@@ -59,6 +59,7 @@ afterEach(() => {delete process.env.RUM_PROVIDER;delete process.env.RUM_URL;delete process.env.RUM_PROXY_TARGET_URL;+ delete process.env.RUM_PROXY_AUTHORIZATION;delete process.env.RUM_SERVICE_NAME;delete process.env.RUM_AUTH_MODE;delete process.env.RUM_PUBLIC_TOKEN;@@ -112,26 +113,32 @@ describe('GET /api/config RUM config', () => {expect(response.body).not.toHaveProperty('rum');});- it('includes proxy RUM config when enabled with valid env', async () => {- mockGetAppConfig.mockResolvedValue(baseAppConfig);- process.env.RUM_ENABLED = 'true';- process.env.RUM_AUTH_MODE = 'proxy';- process.env.RUM_PROXY_TARGET_URL = 'http://otel-collector:4318';- const app = createApp(mockUser);-- const response = await request(app).get('/api/config');-- expect(response.body.rum).toEqual({- provider: 'hyperdx',- enabled: true,- url: '/api/rum',- serviceName: 'librechat-web',- authMode: 'proxy',- consoleCapture: false,- disableReplay: true,- advancedNetworkCapture: false,- });- });+ it.each([null, mockUser])(+ 'keeps proxy credentials out of startup config for %p',+ async (user) => {+ mockGetAppConfig.mockResolvedValue(baseAppConfig);+ process.env.RUM_ENABLED = 'true';+ process.env.RUM_AUTH_MODE = 'proxy';+ process.env.RUM_PROXY_TARGET_URL = 'http://otel-collector:4318';+ process.env.RUM_PROXY_AUTHORIZATION = 'server-only-ingestion-key';+ const app = createApp(user);++ const response = await request(app).get('/api/config');++ expect(JSON.stringify(response.body)).not.toContain('server-only-ingestion-key');+ expect(JSON.stringify(response.body)).not.toContain('otel-collector');+ expect(response.body.rum).toEqual({+ provider: 'hyperdx',+ enabled: true,+ url: '/api/rum',+ serviceName: 'librechat-web',+ authMode: 'proxy',+ consoleCapture: false,+ disableReplay: true,+ advancedNetworkCapture: false,+ });+ },+ );it('omits proxy RUM config without a target collector URL', async () => {mockGetAppConfig.mockResolvedValue(baseAppConfig);diff --git a/api/server/routes/__tests__/rum.spec.js b/api/server/routes/__tests__/rum.spec.jsindex cdd0ec3e76..39acf89008 100644--- a/api/server/routes/__tests__/rum.spec.js+++ b/api/server/routes/__tests__/rum.spec.js@@ -31,6 +31,10 @@ describe('RUM proxy routes', () => {mockProxyRumRequest.mockClear();});+ afterEach(() => {+ delete process.env.RUM_PROXY_AUTHORIZATION;+ });+it('returns 404 before auth and proxying when RUM proxy mode is disabled', async () => {mockIsRumProxyEnabled.mockReturnValue(false);@@ -45,18 +49,44 @@ describe('RUM proxy routes', () => {expect(mockProxyRumRequest).not.toHaveBeenCalled();});- it('authenticates and proxies when RUM proxy mode is enabled', async () => {- mockIsRumProxyEnabled.mockReturnValue(true);-- const response = await request(app)- .post('/api/rum/v1/traces')- .set('Content-Type', 'application/x-protobuf')- .send(Buffer.from('payload'));-- expect(response.status).toBe(202);- expect(mockRequireRumProxyAuth).toHaveBeenCalledTimes(1);- expect(mockProxyRumRequest).toHaveBeenCalledTimes(1);- });+ it.each(['traces', 'logs'])(+ 'passes server authorization to the %s proxy after auth',+ async (signal) => {+ process.env.RUM_PROXY_AUTHORIZATION = 'server-only-ingestion-key';+ mockIsRumProxyEnabled.mockReturnValue(true);++ const response = await request(app)+ .post(`/api/rum/v1/${signal}`)+ .set('Content-Type', 'application/x-protobuf')+ .send(Buffer.from('payload'));++ expect(response.status).toBe(202);+ expect(mockRequireRumProxyAuth).toHaveBeenCalledTimes(1);+ expect(mockProxyRumRequest).toHaveBeenCalledTimes(1);+ expect(mockProxyRumRequest).toHaveBeenCalledWith(+ expect.any(Object),+ expect.any(Object),+ 'server-only-ingestion-key',+ );+ },+ );++ it.each(['traces', 'logs'])(+ 'does not export %s when session authentication fails',+ async (signal) => {+ process.env.RUM_PROXY_AUTHORIZATION = 'server-only-ingestion-key';+ mockIsRumProxyEnabled.mockReturnValue(true);+ mockRequireRumProxyAuth.mockImplementationOnce((_req, res) => res.status(401).end());++ const response = await request(app)+ .post(`/api/rum/v1/${signal}`)+ .set('Content-Type', 'application/x-protobuf')+ .send(Buffer.from('payload'));++ expect(response.status).toBe(401);+ expect(mockProxyRumRequest).not.toHaveBeenCalled();+ },+ );it('uses RUM-specific auth for logs as well as traces', async () => {mockIsRumProxyEnabled.mockReturnValue(true);diff --git a/api/server/routes/rum.js b/api/server/routes/rum.jsindex cc5c2f281a..08c78939b8 100644--- a/api/server/routes/rum.js+++ b/api/server/routes/rum.js@@ -16,13 +16,9 @@ function requireRumProxyEnabled(_req, res, next) {return next();}-router.post(- '/v1/traces',- requireRumProxyEnabled,- requireRumProxyAuth,- rawOtlpBody,- proxyRumRequest,-);-router.post('/v1/logs', requireRumProxyEnabled, requireRumProxyAuth, rawOtlpBody, proxyRumRequest);+const proxyTelemetry = (req, res) => proxyRumRequest(req, res, process.env.RUM_PROXY_AUTHORIZATION);++router.post('/v1/traces', requireRumProxyEnabled, requireRumProxyAuth, rawOtlpBody, proxyTelemetry);+router.post('/v1/logs', requireRumProxyEnabled, requireRumProxyAuth, rawOtlpBody, proxyTelemetry);module.exports = router;diff --git a/packages/api/src/rum/proxy.spec.ts b/packages/api/src/rum/proxy.spec.tsindex 22aeeb9374..9d04d7e927 100644--- a/packages/api/src/rum/proxy.spec.ts+++ b/packages/api/src/rum/proxy.spec.ts@@ -2,6 +2,11 @@ jest.mock('~/app/metrics', () => ({recordRumProxyRequest: jest.fn(),}));+import express from 'express';+import request from 'supertest';+import { createServer } from 'node:http';+import { logger } from '@librechat/data-schemas';+import type { Server } from 'node:http';import { recordRumProxyRequest } from '~/app/metrics';import {getRumProxyBodyLimit,@@ -110,6 +115,7 @@ describe('RUM proxy configuration', () => {expect(fetchMock).toHaveBeenCalledWith('http://otel-collector:4318/v1/traces', {method: 'POST',+ redirect: 'follow',headers: {accept: 'application/json','content-type': 'application/json',@@ -180,3 +186,148 @@ describe('RUM proxy configuration', () => {fetchMock.mockRestore();});});++describe('RUM proxy upstream HTTP contract', () => {+ const originalEnv = process.env;+ let collector: Server;+ let collectorUrl: string;++ beforeEach(async () => {+ process.env = { ...originalEnv };+ jest.mocked(recordRumProxyRequest).mockClear();+ collector = createServer();+ await new Promise<void>((resolve) => collector.listen(0, '127.0.0.1', resolve));+ const address = collector.address();+ if (!address || typeof address === 'string') {+ throw new Error('Expected a TCP collector address');+ }+ collectorUrl = `http://127.0.0.1:${address.port}`;+ process.env.RUM_PROXY_TARGET_URL = collectorUrl;+ });++ afterEach(async () => {+ process.env = originalEnv;+ collector.closeAllConnections();+ await new Promise<void>((resolve, reject) =>+ collector.close((error) => (error ? reject(error) : resolve())),+ );+ });++ function createProxy(authorization?: string) {+ const app = express();+ app.use(express.raw({ type: '*/*' }));+ app.post('/v1/:signal', (req, res) => proxyRumRequest(req, res, authorization));+ return app;+ }++ it.each(['traces', 'logs'])(+ 'sends only server credentials and intact %s payloads',+ async (signal) => {+ const payload = Buffer.from([0x0a, 0x02, 0x00, 0xff]);+ const received: {+ authorization?: string;+ cookie?: string;+ apiKey?: string;+ path?: string;+ body: Buffer;+ } = {+ body: Buffer.alloc(0),+ };+ collector.on('request', (req, res) => {+ received.authorization = req.headers.authorization;+ received.cookie = req.headers.cookie;+ received.apiKey = req.headers['x-api-key']?.toString();+ received.path = req.url;+ req.on('data', (chunk: Buffer) => {+ received.body = Buffer.concat([received.body, chunk]);+ });+ req.on('end', () => {+ res.writeHead(202, { 'content-type': 'application/x-protobuf' });+ res.end(Buffer.from([0x00]));+ });+ });++ const response = await request(createProxy(' clickstack-ingestion-key '))+ .post(`/v1/${signal}`)+ .set('Content-Type', 'application/x-protobuf')+ .set('Authorization', 'Bearer librechat-session-token')+ .set('Cookie', 'refreshToken=private-cookie')+ .set('X-Api-Key', 'browser-supplied-key')+ .send(payload);++ expect(response.status).toBe(202);+ expect(received).toEqual({+ authorization: 'clickstack-ingestion-key',+ cookie: undefined,+ apiKey: undefined,+ path: `/v1/${signal}`,+ body: payload,+ });+ expect(recordRumProxyRequest).toHaveBeenCalledWith(signal, 'success');+ },+ );++ it.each([undefined, '', ' '])(+ 'preserves unauthenticated collectors with authorization %p',+ async (authorization) => {+ let receivedAuthorization: string | undefined;+ collector.on('request', (req, res) => {+ receivedAuthorization = req.headers.authorization;+ req.resume();+ res.writeHead(200);+ res.end('{}');+ });+ const response = await request(createProxy(authorization))+ .post('/v1/logs')+ .set('Authorization', 'Bearer app-token')+ .set('Content-Type', 'application/json')+ .send('{}');++ expect(response.status).toBe(200);+ expect(receivedAuthorization).toBeUndefined();+ },+ );++ it.each([301, 302, 303, 307, 308])(+ 'does not follow a credentialed %s redirect, even on the same origin',+ async (status) => {+ const paths: string[] = [];+ collector.on('request', (req, res) => {+ paths.push(req.url ?? '');+ req.resume();+ res.writeHead(status, { location: `${collectorUrl}/redirect-target` });+ res.end();+ });+ const response = await request(createProxy('clickstack-ingestion-key'))+ .post('/v1/traces')+ .set('Content-Type', 'application/json')+ .send('{}');++ expect(response.status).toBe(502);+ expect(paths).toEqual(['/v1/traces']);+ expect(response.headers.location).toBeUndefined();+ expect(recordRumProxyRequest).toHaveBeenCalledWith('traces', 'collector_error');+ },+ );++ it.each(['private-key\r\ninjected: value', 'private-key-😀'])(+ 'rejects invalid credentials without leaking them',+ async (authorization) => {+ const fetchSpy = jest.spyOn(global, 'fetch');+ const logSpy = jest.spyOn(logger, 'warn');+ const response = await request(createProxy(authorization))+ .post('/v1/traces')+ .set('Content-Type', 'application/json')+ .send('{}');++ expect(response.status).toBe(502);+ expect(fetchSpy).not.toHaveBeenCalled();+ expect(logSpy).toHaveBeenCalledWith('[rumProxy] Failed to proxy RUM telemetry', {+ error: 'Invalid RUM proxy authorization header',+ target: `${collectorUrl}/v1/traces`,+ });+ expect(response.text).not.toContain('private-key');+ expect(JSON.stringify(logSpy.mock.calls)).not.toContain('private-key');+ },+ );+});diff --git a/packages/api/src/rum/proxy.ts b/packages/api/src/rum/proxy.tsindex 856457be5f..2b68805478 100644--- a/packages/api/src/rum/proxy.ts+++ b/packages/api/src/rum/proxy.ts@@ -1,3 +1,4 @@+import { validateHeaderValue } from 'node:http';import { logger } from '@librechat/data-schemas';import type { Request, Response } from 'express';import type { RumProxyEndpoint, RumProxyResult } from '~/app/metrics';@@ -121,17 +122,35 @@ function getHeader(req: Request, name: string): string | undefined {return typeof value === 'string' ? value : undefined;}-function getProxyHeaders(req: Request, body: Buffer | string): Record<string, string> {+function getProxyHeaders(+ req: Request,+ body: Buffer | string,+ authorization: string | undefined,+): Record<string, string> {+ if (authorization) {+ try {+ validateHeaderValue('authorization', authorization);+ } catch {+ throw new Error('Invalid RUM proxy authorization header');+ }+ }+const contentType =getHeader(req, 'content-type') || (typeof body === 'string' ? 'application/json' : undefined);const accept = getHeader(req, 'accept');return {...(contentType ? { 'content-type': contentType } : {}),...(accept ? { accept } : {}),+ ...(authorization ? { authorization } : {}),};}-export async function proxyRumRequest(req: Request, res: Response): Promise<void> {+export async function proxyRumRequest(+ req: Request,+ res: Response,+ upstreamAuthorization?: string,+): Promise<void> {+ const authorization = upstreamAuthorization?.trim();const endpoint = getRumProxyEndpoint(req.path);const target = resolveRumProxyTarget(req.path);if (!target) {@@ -152,7 +171,8 @@ export async function proxyRumRequest(req: Request, res: Response): Promise<voidtry {const response = await fetch(target, {method: 'POST',- headers: getProxyHeaders(req, body),+ headers: getProxyHeaders(req, body, authorization),+ redirect: authorization ? 'error' : 'follow',// TS 5.9 made `Buffer` generic (`Buffer<ArrayBufferLike>`), which no longer// structurally matches `BodyInit`; Node's fetch accepts a Buffer body at runtime.body: body as BodyInit,