diff --git a/api/server/services/Files/Local/__tests__/crud-delete.spec.js b/api/server/services/Files/Local/__tests__/crud-delete.spec.js index 7a7a30340a..dacb477323 100644 --- a/api/server/services/Files/Local/__tests__/crud-delete.spec.js +++ b/api/server/services/Files/Local/__tests__/crud-delete.spec.js @@ -10,6 +10,7 @@ jest.mock('@librechat/data-schemas', () => ({ const fs = require('fs'); const os = require('os'); const path = require('path'); +const { deleteRagFile } = require('@librechat/api'); const { deleteLocalFile } = require('../crud'); /* The resolved promise of a delete is what `processDeleteRequest` reads to decide that a record may @@ -22,6 +23,7 @@ describe('deleteLocalFile failure reporting', () => { beforeEach(() => { jest.restoreAllMocks(); + jest.clearAllMocks(); tmpBase = fs.mkdtempSync(path.join(os.tmpdir(), 'crud-delete-')); fs.mkdirSync(path.join(tmpBase, 'uploads', userId), { recursive: true }); req = { @@ -39,10 +41,11 @@ describe('deleteLocalFile failure reporting', () => { fs.rmSync(tmpBase, { recursive: true, force: true }); }); - const uploadedFile = (filename) => { - const filepath = path.join(tmpBase, 'uploads', userId, filename); + const uploadedFile = (filename, ownerId = userId) => { + fs.mkdirSync(path.join(tmpBase, 'uploads', ownerId), { recursive: true }); + const filepath = path.join(tmpBase, 'uploads', ownerId, filename); fs.writeFileSync(filepath, 'contents'); - return { file_id: 'file-1', filepath: `/uploads/${userId}/${filename}` }; + return { file_id: 'file-1', filepath: `/uploads/${ownerId}/${filename}`, user: ownerId }; }; it('removes the file and resolves', async () => { @@ -67,4 +70,25 @@ describe('deleteLocalFile failure reporting', () => { await expect(deleteLocalFile(req, file)).rejects.toThrow('permission denied'); expect(fs.existsSync(path.join(tmpBase, 'uploads', userId, 'locked.txt'))).toBe(true); }); + + it("uses the recorded owner when a manager deletes another user's file", async () => { + const ownerId = 'user-2'; + const file = uploadedFile('managed.txt', ownerId); + req.user.id = 'manager-1'; + + await expect(deleteLocalFile(req, file)).resolves.toBeUndefined(); + + expect(deleteRagFile).toHaveBeenCalledWith({ userId: ownerId, file }); + expect(fs.existsSync(path.join(tmpBase, 'uploads', ownerId, 'managed.txt'))).toBe(false); + }); + + it('rejects a path outside the recorded owner namespace', async () => { + const file = uploadedFile('protected.txt', 'user-2'); + file.user = 'user-3'; + + await expect(deleteLocalFile(req, file)).rejects.toThrow('Invalid file path'); + + expect(deleteRagFile).not.toHaveBeenCalled(); + expect(fs.existsSync(path.join(tmpBase, 'uploads', 'user-2', 'protected.txt'))).toBe(true); + }); }); diff --git a/api/server/services/Files/Local/crud.js b/api/server/services/Files/Local/crud.js index 93d3efbb9f..ad93b07d12 100644 --- a/api/server/services/Files/Local/crud.js +++ b/api/server/services/Files/Local/crud.js @@ -154,16 +154,16 @@ async function getLocalFileURL({ fileName, basePath = 'images' }) { * Validates that a filepath is strictly contained within a subdirectory under a base path, * using path.relative to prevent prefix-collision bypasses. * - * @param {ServerRequest} req - The request object from Express. It should contain a `user` property with an `id`. * @param {string} base - The base directory path. * @param {string} subfolder - The subdirectory under the base path. + * @param {string} ownerId - The persisted owner whose storage namespace contains the file. * @param {string} filepath - The complete file path to be validated. * * @returns {boolean} * Returns true if the filepath is within the specified base and subfolder, false otherwise. */ -const isValidPath = (req, base, subfolder, filepath) => { - const normalizedBase = path.resolve(base, subfolder, req.user.id); +const isValidPath = (base, subfolder, ownerId, filepath) => { + const normalizedBase = path.resolve(base, subfolder, ownerId); const normalizedFilepath = path.resolve(filepath); const rel = path.relative(normalizedBase, normalizedFilepath); return !rel.startsWith('..') && !path.isAbsolute(rel) && !rel.includes(`..${path.sep}`); @@ -205,15 +205,15 @@ const unlinkFile = async (filepath) => { const deleteLocalFile = async (req, file) => { const appConfig = req.config; const { publicPath, uploads } = appConfig.paths; + const ownerId = file.user?.toString?.() || req.user.id; /** Filepath stripped of query parameters (e.g., ?manual=true, ?v=) */ const cleanFilepath = stripCacheBust(file.filepath); + const uploadPrefix = `/uploads/${ownerId}/`; - await deleteRagFile({ userId: req.user.id, file }); - - if (cleanFilepath.startsWith(`/uploads/${req.user.id}`)) { - const userUploadDir = path.join(uploads, req.user.id); - const basePath = cleanFilepath.split(`/uploads/${req.user.id}/`)[1]; + if (cleanFilepath.startsWith(uploadPrefix)) { + const userUploadDir = path.join(uploads, ownerId); + const basePath = cleanFilepath.slice(uploadPrefix.length); if (!basePath) { throw new Error(`Invalid file path: ${cleanFilepath}`); @@ -226,6 +226,7 @@ const deleteLocalFile = async (req, file) => { throw new Error(`Invalid file path: ${cleanFilepath}`); } + await deleteRagFile({ userId: ownerId, file }); await unlinkFile(filepath); return; } @@ -238,10 +239,11 @@ const deleteLocalFile = async (req, file) => { } const filepath = path.join(publicPath, cleanFilepath); - if (!isValidPath(req, publicPath, subfolder, filepath)) { + if (!isValidPath(publicPath, subfolder, ownerId, filepath)) { throw new Error('Invalid file path'); } + await deleteRagFile({ userId: ownerId, file }); await unlinkFile(filepath); };