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
🚸 fix: Align Image Authorization and Static Serving Paths (#17392)
lia-by-librechat[bot]2169a620ab18
diff --git a/packages/api/jest.config.mjs b/packages/api/jest.config.mjsindex 175226a1b4..232ac74a82 100644--- a/packages/api/jest.config.mjs+++ b/packages/api/jest.config.mjs@@ -45,6 +45,7 @@ export default {transformIgnorePatterns: [`/node_modules/(?!(${esModules})/).*/`],moduleNameMapper: {'^@src/(.*)$': '<rootDir>/src/$1',+ '^~/api/(.*)$': '<rootDir>/../../api/$1','~/(.*)': '<rootDir>/src/$1',},// coverageThreshold: {diff --git a/packages/api/src/images/authorization.spec.ts b/packages/api/src/images/authorization.spec.tsindex 2c24a445ac..c67aeb086d 100644--- a/packages/api/src/images/authorization.spec.ts+++ b/packages/api/src/images/authorization.spec.ts@@ -1,11 +1,20 @@+import express from 'express';import jwt from 'jsonwebtoken';+import request from 'supertest';+import { Types } from 'mongoose';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { gzipSync } from 'node:zlib';import { createHash } from 'node:crypto';-import type { NextFunction, Request, Response } from 'express';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import type { Express, NextFunction, Request, RequestHandler, Response } from 'express';import type { ImageAuthorizationDeps } from './authorization';import { createImageAuthorizationMiddleware } from './authorization';+import staticCache from '~/api/server/utils/staticCache';const VIEWER_ID = '65cfb246f7ecadb8b1e8036b';const OWNER_ID = '65cfb246f7ecadb8b1e8036c';+const VICTIM_ID = '65cfb246f7ecadb8b1e8036f';const AGENT_DB_ID = '65cfb246f7ecadb8b1e8036d';const AGENT_PATH = `/images/${OWNER_ID}/agent-agent_abc123-avatar-12345.png`;const USER_AVATAR_PATH = `/images/${OWNER_ID}/avatar-12345.png`;@@ -648,19 +657,233 @@ describe('createImageAuthorizationMiddleware', () => {expect(response.locals.privateImageCache).toBe(true);});- it('rejects encoded traversal before any resource lookup', async () => {- const token = signUser(VIEWER_ID);+ it.each([+ '..%2F..%2Fetc%2Fpasswd',+ 'x%3F%2F..%2F..%2Fsecret.png',+ 'x%23%2F..%2F..%2Fsecret.png',+ 'x%3f%2f..%2f..%2fsecret.png',+ '%2e%2e',+ 'x%5C..%5Csecret.png',+ 'x%00.png',+ 'x%ZZ.png',+ ])('rejects invalid pathname %s before any resource lookup', async (filename) => {const middleware = createImageAuthorizationMiddleware({}, deps);await middleware(- createRequest(`/images/${VIEWER_ID}/..%2F..%2Fetc%2Fpasswd`, `refreshToken=${token}`),+ createRequest(`/images/${VIEWER_ID}/${filename}`, `refreshToken=${signUser(VIEWER_ID)}`),response,next,);expect(next).not.toHaveBeenCalled();expect(response.status).toHaveBeenCalledWith(403);+ expect(deps.getUserById).not.toHaveBeenCalled();expect(deps.getAgent).not.toHaveBeenCalled();expect(deps.getAssistant).not.toHaveBeenCalled();});++ it('forwards the authorized pathname with filename delimiters still encoded', async () => {+ const req = createRequest(+ `/images//${VIEWER_ID}/profile%3Fdraft%23one%252F.png?manual=true`,+ `refreshToken=${signUser(VIEWER_ID)}`,+ );+ const middleware = createImageAuthorizationMiddleware({}, deps);++ await middleware(req, response, next);++ expect(next).toHaveBeenCalledTimes(1);+ expect(req.url).toBe(`/${VIEWER_ID}/profile%3Fdraft%23one%252F.png`);+ });++ describe.each([true, false])('HTTP image serving, skipGzipScan=%s', (skipGzipScan) => {+ const privateBytes = Buffer.from('VICTIM_PRIVATE_BYTES');+ const ownerBytes = Buffer.from('OWNER_IMAGE_BYTES');+ const publicBytes = Buffer.from('PUBLIC_AVATAR_BYTES');+ const assistantFilenames = ['company logo.png', '会社.png', 'company+logo.png'];+ let imageRoot: string;++ beforeAll(() => {+ imageRoot = mkdtempSync(join(tmpdir(), 'image-authorization-'));+ for (const id of [VIEWER_ID, OWNER_ID, VICTIM_ID]) {+ mkdirSync(join(imageRoot, id));+ }+ const files = [+ [`${VICTIM_ID}/secret.png`, privateBytes],+ [`${OWNER_ID}/${AGENT_PATH.split('/').pop()}`, publicBytes],+ [`${VIEWER_ID}/profile.png`, ownerBytes],+ [`${VIEWER_ID}/profile?draft.png`, ownerBytes],+ [`${VIEWER_ID}/profile#draft.png`, ownerBytes],+ [`${VIEWER_ID}/profile with spaces.png`, ownerBytes],+ [`${VIEWER_ID}/profile%2F.png`, ownerBytes],+ [`${OWNER_ID}/${AGENT_PATH.split('/').pop()}?private.png`, privateBytes],+ [`${OWNER_ID}/${AGENT_PATH.split('/').pop()}?manual=true`, privateBytes],+ ...assistantFilenames.map((filename) => [`${OWNER_ID}/${filename}`, publicBytes] as const),+ [`${OWNER_ID}/company logo.png?manual=true`, privateBytes],+ [`${OWNER_ID}/company logo.png#private`, privateBytes],+ [`${OWNER_ID}/company%20logo.png`, privateBytes],+ ] as const;+ for (const [filename, bytes] of files) {+ writeFileSync(join(imageRoot, filename), bytes);+ writeFileSync(join(imageRoot, `${filename}.gz`), gzipSync(bytes));+ }+ });++ afterAll(() => {+ rmSync(imageRoot, { recursive: true, force: true });+ });++ describe.each(['', '/chat'])('base path "%s"', (basePath) => {+ let app: Express;++ beforeEach(() => {+ jest.mocked(deps.getBasePath).mockReturnValue(basePath);+ jest.mocked(deps.getUserById).mockImplementation(async (id) => ({+ role: 'USER',+ tenantId: id === VICTIM_ID ? 'tenant-b' : 'tenant-a',+ }));+ jest+ .mocked(deps.getAgent)+ .mockImplementation(async (query) =>+ query.id === 'agent_abc123' &&+ query['avatar.filepath']?.$in?.includes(`${AGENT_PATH}?manual=true`)+ ? { _id: new Types.ObjectId(AGENT_DB_ID) }+ : null,+ );+ jest+ .mocked(deps.hasPermission)+ .mockImplementation(+ async (principals, resourceType, resourceId, permission) =>+ principals.length === 1 &&+ principals[0].principalType === 'public' &&+ resourceType === 'agent' &&+ resourceId.toString() === AGENT_DB_ID &&+ permission === 1,+ );+ app = express();+ const router = express.Router();+ router.use(staticCache(imageRoot, { skipGzipScan }) as RequestHandler);+ app.use(+ `${basePath}/images`,+ createImageAuthorizationMiddleware(+ { assistantEndpoints: [{ endpoint: 'assistants', privateAssistants: false }] },+ deps,+ ),+ router,+ );+ });++ it('denies direct victim requests with and without an active session', async () => {+ const path = `${basePath}/images/${VICTIM_ID}/secret.png`;+ const anonymous = await request(app).get(path);+ const authenticated = await request(app)+ .get(path)+ .set('Cookie', `refreshToken=${signUser(VIEWER_ID)}`);+ expect(anonymous.status).toBe(401);+ expect(authenticated.status).toBe(403);+ });++ it.each(['%3F', '%23'])('rejects an owner-prefix %s traversal', async (delimiter) => {+ const response = await request(app)+ .get(`${basePath}/images//${VIEWER_ID}/x${delimiter}%2F..%2F..%2F${VICTIM_ID}/secret.png`)+ .set('Cookie', `refreshToken=${signUser(VIEWER_ID)}`);+ expect(response.body).not.toEqual(privateBytes);+ expect(response.status).toBe(403);+ expect(deps.getUserById).not.toHaveBeenCalled();+ });++ it.each(['%3F', '%23'])(+ 'rejects an anonymous public-avatar %s traversal',+ async (delimiter) => {+ const response = await request(app).get(+ `${basePath}${AGENT_PATH}${delimiter}%2F..%2F..%2F${VICTIM_ID}/secret.png`,+ );+ expect(response.body).not.toEqual(privateBytes);+ expect(response.status).toBe(401);+ expect(deps.getAgent).not.toHaveBeenCalled();+ },+ );++ it.each([+ 'profile.png?manual=true&ignored=%ZZ',+ 'profile%3Fdraft.png',+ 'profile%23draft.png',+ 'profile%20with%20spaces.png',+ 'profile%252F.png',+ ])('serves only the authorized owner file for %s', async (filename) => {+ const response = await request(app)+ .get(`${basePath}/images//${VIEWER_ID}/${filename}`)+ .set('Cookie', `refreshToken=${signUser(VIEWER_ID)}`)+ .set('Accept-Encoding', 'gzip')+ .expect(200);+ expect(response.body).toEqual(ownerBytes);+ expect(response.headers['cache-control']).toBe('private, no-store');+ expect(response.headers['content-encoding']).toBe(skipGzipScan ? undefined : 'gzip');+ });++ describe.each(['raw', 'encoded'])('stored assistant paths: %s', (representation) => {+ it.each(assistantFilenames)(+ 'serves shared assistant avatar %s to a non-owner',+ async (filename) => {+ const storedPath = `/images/${OWNER_ID}/${+ representation === 'raw' ? filename : encodeURIComponent(filename)+ }`;+ for (const suffix of ['', '?manual=false', '?manual=true']) {+ jest.mocked(deps.getAssistant).mockImplementation(async (query) =>+ query.avatarFilepath?.includes(`${storedPath}${suffix}`)+ ? {+ _id: new Types.ObjectId(AGENT_DB_ID),+ assistant_id: 'asst_shared',+ endpoint: 'assistants',+ }+ : null,+ );+ const result = await request(app)+ .get(`${basePath}/images/${OWNER_ID}/${encodeURIComponent(filename)}`)+ .set('Cookie', `refreshToken=${signUser(VIEWER_ID)}`)+ .set('Accept-Encoding', 'gzip');+ expect(result.status).toBe(200);+ expect(result.body).toEqual(publicBytes);+ expect(result.headers['cache-control']).toBe('private, no-store');+ }+ },+ );+ });++ it.each(['%3Fmanual=true', '%23private', '%2520logo.png'])(+ 'does not alias an assistant filename suffix %s to a stored URL',+ async (suffix) => {+ const storedPath = `/images/${OWNER_ID}/${+ suffix === '%2520logo.png' ? 'company%20logo.png' : 'company logo.png'+ }?manual=true`;+ jest.mocked(deps.getAssistant).mockImplementation(async (query) =>+ query.avatarFilepath?.includes(storedPath)+ ? {+ _id: new Types.ObjectId(AGENT_DB_ID),+ assistant_id: 'asst_shared',+ endpoint: 'assistants',+ }+ : null,+ );+ const filename =+ suffix === '%2520logo.png' ? `company${suffix}` : `company%20logo.png${suffix}`;+ const result = await request(app)+ .get(`${basePath}/images/${OWNER_ID}/${filename}`)+ .set('Cookie', `refreshToken=${signUser(VIEWER_ID)}`);+ expect(result.status).toBe(403);+ expect(result.body).not.toEqual(privateBytes);+ },+ );++ it('serves the exact PUBLIC avatar but not a filename with an encoded delimiter', async () => {+ const response = await request(app)+ .get(`${basePath}${AGENT_PATH}?manual=false`)+ .set('Accept-Encoding', 'gzip')+ .expect(200);+ expect(response.body).toEqual(publicBytes);+ expect(response.headers['cache-control']).toBe('private, no-store');+ await request(app).get(`${basePath}${AGENT_PATH}%3Fprivate.png`).expect(401);+ await request(app).get(`${basePath}${AGENT_PATH}%3Fmanual=true`).expect(401);+ });+ });+ });});diff --git a/packages/api/src/images/authorization.ts b/packages/api/src/images/authorization.tsindex 78170b9a81..f54f19287f 100644--- a/packages/api/src/images/authorization.ts+++ b/packages/api/src/images/authorization.ts@@ -127,18 +127,18 @@ function parseImagePath(originalUrl: string, basePath: string): ImagePath | nullreturn null;}- let decodedUrl: string;+ const rawPath = originalUrl.split(/[?#]/, 1)[0];+ let decodedPath: string;try {- decodedUrl = decodeURIComponent(originalUrl);+ decodedPath = decodeURIComponent(rawPath);} catch {return null;}- if (decodedUrl.includes('\0')) {+ if (decodedPath.includes('\0')) {return null;}- const cleanPath = decodedUrl.split(/[?#]/, 1)[0];let decodedBasePath: string;try {decodedBasePath = decodeURIComponent(basePath);@@ -147,9 +147,9 @@ function parseImagePath(originalUrl: string, basePath: string): ImagePath | null}const imagesPath = `${decodedBasePath}/images`;const imagesPrefix = `${imagesPath}/`;- const normalizedPath = cleanPath.startsWith(imagesPrefix)- ? `${imagesPrefix}${cleanPath.slice(imagesPrefix.length).replace(/^\/+/, '')}`- : cleanPath;+ const normalizedPath = decodedPath.startsWith(imagesPrefix)+ ? `${imagesPrefix}${decodedPath.slice(imagesPrefix.length).replace(/^\/+/, '')}`+ : decodedPath;const match = normalizedPath.match(new RegExp(`^${escapeRegExp(imagesPath)}/([a-f0-9]{24})/([^/]+)$`, 'i'),);@@ -164,7 +164,7 @@ function parseImagePath(originalUrl: string, basePath: string): ImagePath | nullreturn {ownerId,filename,- canonicalPath: `/images/${ownerId}/${filename}`,+ canonicalPath: `/images/${ownerId}/${encodeURIComponent(filename)}`,agentId: filename.match(AGENT_AVATAR_PATTERN)?.[1],};}@@ -221,8 +221,19 @@ function getSignedOpenIdUserId(}}-function getStoredPathCandidates(canonicalPath: string): string[] {- return [canonicalPath, `${canonicalPath}?manual=false`, `${canonicalPath}?manual=true`];+function getStoredPathCandidates(imagePath: ImagePath): string[] {+ const { canonicalPath, ownerId, filename } = imagePath;+ const candidates = [+ canonicalPath,+ `${canonicalPath}?manual=false`,+ `${canonicalPath}?manual=true`,+ ];+ const storedPath = `/images/${ownerId}/${filename}`;+ // Legacy raw filenames are aliases only when URL parsing cannot change their identity.+ if (storedPath !== canonicalPath && !/[?#%]/.test(filename)) {+ candidates.push(storedPath, `${storedPath}?manual=false`, `${storedPath}?manual=true`);+ }+ return candidates;}async function authenticateRequest(@@ -316,7 +327,7 @@ async function canViewAgentAvatar(const agent = await deps.getAgent({id: imagePath.agentId,- 'avatar.filepath': { $in: getStoredPathCandidates(imagePath.canonicalPath) },+ 'avatar.filepath': { $in: getStoredPathCandidates(imagePath) },},{ _id: 1 },);@@ -359,7 +370,7 @@ async function canViewAssistantAvatar(deps: ImageAuthorizationDeps,): Promise<boolean> {const assistant = await deps.getAssistant(- { avatarFilepath: getStoredPathCandidates(imagePath.canonicalPath) },+ { avatarFilepath: getStoredPathCandidates(imagePath) },{ _id: 1, assistant_id: 1, endpoint: 1 },);if (!assistant) {@@ -486,6 +497,8 @@ export function createImageAuthorizationMiddleware(return;}+ // Static serving must receive the same single-decoded pathname that was authorized.+ req.url = imagePath.canonicalPath.slice('/images'.length);res.locals.privateImageCache = true;let auth = await authPromise;let viewer: ImageUser | null = null;diff --git a/packages/api/tsconfig.json b/packages/api/tsconfig.jsonindex 7ed6308871..9bbd1c335c 100644--- a/packages/api/tsconfig.json+++ b/packages/api/tsconfig.json@@ -22,6 +22,7 @@"rootDir": "../..","types": ["node", "jest", "multer", "passport", "bun"],"paths": {+ "~/api/*": ["../../api/*"],"~/*": ["./src/*"],// @librechat/agents ships declaration files that import its internal "@/" alias, which// package exports cannot map; resolve them into its published types until the SDK