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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
const mongoose = require('mongoose');
const { ResourceType, PrincipalType, PrincipalModel } = require('librechat-data-provider');
const { MongoMemoryServer } = require('mongodb-memory-server');
const { fileAccess } = require('./fileAccess');
const { User, Role, AclEntry } = require('~/db/models');
const { createAgent } = require('~/models/Agent');
const { createFile } = require('~/models/File');

describe('fileAccess middleware', () => {
  let mongoServer;
  let req, res, next;
  let testUser, otherUser, thirdUser;

  beforeAll(async () => {
    mongoServer = await MongoMemoryServer.create();
    const mongoUri = mongoServer.getUri();
    await mongoose.connect(mongoUri);
  });

  afterAll(async () => {
    await mongoose.disconnect();
    await mongoServer.stop();
  });

  beforeEach(async () => {
    await mongoose.connection.dropDatabase();

    // Create test role
    await Role.create({
      name: 'test-role',
      permissions: {
        AGENTS: {
          USE: true,
          CREATE: true,
          SHARED_GLOBAL: false,
        },
      },
    });

    // Create test users
    testUser = await User.create({
      email: 'test@example.com',
      name: 'Test User',
      username: 'testuser',
      role: 'test-role',
    });

    otherUser = await User.create({
      email: 'other@example.com',
      name: 'Other User',
      username: 'otheruser',
      role: 'test-role',
    });

    thirdUser = await User.create({
      email: 'third@example.com',
      name: 'Third User',
      username: 'thirduser',
      role: 'test-role',
    });

    // Setup request/response objects
    req = {
      user: { id: testUser._id.toString(), role: testUser.role },
      params: {},
    };
    res = {
      status: jest.fn().mockReturnThis(),
      json: jest.fn(),
    };
    next = jest.fn();

    jest.clearAllMocks();
  });

  describe('basic file access', () => {
    test('should allow access when user owns the file', async () => {
      // Create a file owned by testUser
      await createFile({
        user: testUser._id.toString(),
        file_id: 'file_owned_by_user',
        filepath: '/test/file.txt',
        filename: 'file.txt',
        type: 'text/plain',
        size: 100,
      });

      req.params.file_id = 'file_owned_by_user';
      await fileAccess(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(req.fileAccess).toBeDefined();
      expect(req.fileAccess.file).toBeDefined();
      expect(res.status).not.toHaveBeenCalled();
    });

    test('should deny access when user does not own the file and no agent access', async () => {
      // Create a file owned by otherUser
      await createFile({
        user: otherUser._id.toString(),
        file_id: 'file_owned_by_other',
        filepath: '/test/file.txt',
        filename: 'file.txt',
        type: 'text/plain',
        size: 100,
      });

      req.params.file_id = 'file_owned_by_other';
      await fileAccess(req, res, next);

      expect(next).not.toHaveBeenCalled();
      expect(res.status).toHaveBeenCalledWith(403);
      expect(res.json).toHaveBeenCalledWith({
        error: 'Forbidden',
        message: 'Insufficient permissions to access this file',
      });
    });

    test('should return 404 when file does not exist', async () => {
      req.params.file_id = 'non_existent_file';
      await fileAccess(req, res, next);

      expect(next).not.toHaveBeenCalled();
      expect(res.status).toHaveBeenCalledWith(404);
      expect(res.json).toHaveBeenCalledWith({
        error: 'Not Found',
        message: 'File not found',
      });
    });

    test('should return 400 when file_id is missing', async () => {
      // Don't set file_id in params
      await fileAccess(req, res, next);

      expect(next).not.toHaveBeenCalled();
      expect(res.status).toHaveBeenCalledWith(400);
      expect(res.json).toHaveBeenCalledWith({
        error: 'Bad Request',
        message: 'file_id is required',
      });
    });

    test('should return 401 when user is not authenticated', async () => {
      req.user = null;
      req.params.file_id = 'some_file';

      await fileAccess(req, res, next);

      expect(next).not.toHaveBeenCalled();
      expect(res.status).toHaveBeenCalledWith(401);
      expect(res.json).toHaveBeenCalledWith({
        error: 'Unauthorized',
        message: 'Authentication required',
      });
    });
  });

  describe('agent-based file access', () => {
    beforeEach(async () => {
      // Create a file owned by otherUser (not testUser)
      await createFile({
        user: otherUser._id.toString(),
        file_id: 'shared_file_via_agent',
        filepath: '/test/shared.txt',
        filename: 'shared.txt',
        type: 'text/plain',
        size: 100,
      });
    });

    test('should allow access when user is author of agent with file', async () => {
      // Create agent owned by testUser with the file
      await createAgent({
        id: `agent_${Date.now()}`,
        name: 'Test Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: testUser._id,
        tool_resources: {
          file_search: {
            file_ids: ['shared_file_via_agent'],
          },
        },
      });

      req.params.file_id = 'shared_file_via_agent';
      await fileAccess(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(req.fileAccess).toBeDefined();
      expect(req.fileAccess.file).toBeDefined();
    });

    test('should allow access when user has VIEW permission on agent with file', async () => {
      // Create agent owned by otherUser
      const agent = await createAgent({
        id: `agent_${Date.now()}`,
        name: 'Shared Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: otherUser._id,
        tool_resources: {
          execute_code: {
            file_ids: ['shared_file_via_agent'],
          },
        },
      });

      // Grant VIEW permission to testUser
      await AclEntry.create({
        principalType: PrincipalType.USER,
        principalId: testUser._id,
        principalModel: PrincipalModel.USER,
        resourceType: ResourceType.AGENT,
        resourceId: agent._id,
        permBits: 1, // VIEW permission
        grantedBy: otherUser._id,
      });

      req.params.file_id = 'shared_file_via_agent';
      await fileAccess(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(req.fileAccess).toBeDefined();
    });

    test('should check file in ocr tool_resources', async () => {
      await createAgent({
        id: `agent_ocr_${Date.now()}`,
        name: 'OCR Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: testUser._id,
        tool_resources: {
          ocr: {
            file_ids: ['shared_file_via_agent'],
          },
        },
      });

      req.params.file_id = 'shared_file_via_agent';
      await fileAccess(req, res, next);

      expect(next).toHaveBeenCalled();
      expect(req.fileAccess).toBeDefined();
    });

    test('should deny access when user has no permission on agent with file', async () => {
      // Create agent owned by otherUser without granting permission to testUser
      const agent = await createAgent({
        id: `agent_${Date.now()}`,
        name: 'Private Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: otherUser._id,
        tool_resources: {
          file_search: {
            file_ids: ['shared_file_via_agent'],
          },
        },
      });

      // Create ACL entry for otherUser only (owner)
      await AclEntry.create({
        principalType: PrincipalType.USER,
        principalId: otherUser._id,
        principalModel: PrincipalModel.USER,
        resourceType: ResourceType.AGENT,
        resourceId: agent._id,
        permBits: 15, // All permissions
        grantedBy: otherUser._id,
      });

      req.params.file_id = 'shared_file_via_agent';
      await fileAccess(req, res, next);

      expect(next).not.toHaveBeenCalled();
      expect(res.status).toHaveBeenCalledWith(403);
    });
  });

  describe('multiple agents with same file', () => {
    /**
     * This test suite verifies that when multiple agents have the same file,
     * all agents are checked for permissions, not just the first one found.
     * This ensures users can access files through any agent they have permission for.
     */

    test('should check ALL agents with file, not just first one', async () => {
      // Create a file owned by someone else
      await createFile({
        user: otherUser._id.toString(),
        file_id: 'multi_agent_file',
        filepath: '/test/multi.txt',
        filename: 'multi.txt',
        type: 'text/plain',
        size: 100,
      });

      // Create first agent (owned by otherUser, no access for testUser)
      const agent1 = await createAgent({
        id: 'agent_no_access',
        name: 'No Access Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: otherUser._id,
        tool_resources: {
          file_search: {
            file_ids: ['multi_agent_file'],
          },
        },
      });

      // Create ACL for agent1 - only otherUser has access
      await AclEntry.create({
        principalType: PrincipalType.USER,
        principalId: otherUser._id,
        principalModel: PrincipalModel.USER,
        resourceType: ResourceType.AGENT,
        resourceId: agent1._id,
        permBits: 15,
        grantedBy: otherUser._id,
      });

      // Create second agent (owned by thirdUser, but testUser has VIEW access)
      const agent2 = await createAgent({
        id: 'agent_with_access',
        name: 'Accessible Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: thirdUser._id,
        tool_resources: {
          file_search: {
            file_ids: ['multi_agent_file'],
          },
        },
      });

      // Grant testUser VIEW access to agent2
      await AclEntry.create({
        principalType: PrincipalType.USER,
        principalId: testUser._id,
        principalModel: PrincipalModel.USER,
        resourceType: ResourceType.AGENT,
        resourceId: agent2._id,
        permBits: 1, // VIEW permission
        grantedBy: thirdUser._id,
      });

      req.params.file_id = 'multi_agent_file';
      await fileAccess(req, res, next);

      /**
       * Should succeed because testUser has access to agent2,
       * even though they don't have access to agent1.
       * The fix ensures all agents are checked, not just the first one.
       */
      expect(next).toHaveBeenCalled();
      expect(req.fileAccess).toBeDefined();
      expect(res.status).not.toHaveBeenCalled();
    });

    test('should find file in any agent tool_resources type', async () => {
      // Create a file
      await createFile({
        user: otherUser._id.toString(),
        file_id: 'multi_tool_file',
        filepath: '/test/tool.txt',
        filename: 'tool.txt',
        type: 'text/plain',
        size: 100,
      });

      // Agent 1: file in file_search (no access for testUser)
      await createAgent({
        id: 'agent_file_search',
        name: 'File Search Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: otherUser._id,
        tool_resources: {
          file_search: {
            file_ids: ['multi_tool_file'],
          },
        },
      });

      // Agent 2: same file in execute_code (testUser has access)
      await createAgent({
        id: 'agent_execute_code',
        name: 'Execute Code Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: thirdUser._id,
        tool_resources: {
          execute_code: {
            file_ids: ['multi_tool_file'],
          },
        },
      });

      // Agent 3: same file in ocr (testUser also has access)
      await createAgent({
        id: 'agent_ocr',
        name: 'OCR Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: testUser._id, // testUser owns this one
        tool_resources: {
          ocr: {
            file_ids: ['multi_tool_file'],
          },
        },
      });

      req.params.file_id = 'multi_tool_file';
      await fileAccess(req, res, next);

      /**
       * Should succeed because testUser owns agent3,
       * even if other agents with the file are found first.
       */
      expect(next).toHaveBeenCalled();
      expect(req.fileAccess).toBeDefined();
    });
  });

  describe('edge cases', () => {
    test('should handle agent with empty tool_resources', async () => {
      await createFile({
        user: otherUser._id.toString(),
        file_id: 'orphan_file',
        filepath: '/test/orphan.txt',
        filename: 'orphan.txt',
        type: 'text/plain',
        size: 100,
      });

      // Create agent with no files in tool_resources
      await createAgent({
        id: `agent_empty_${Date.now()}`,
        name: 'Empty Resources Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: testUser._id,
        tool_resources: {},
      });

      req.params.file_id = 'orphan_file';
      await fileAccess(req, res, next);

      expect(next).not.toHaveBeenCalled();
      expect(res.status).toHaveBeenCalledWith(403);
    });

    test('should handle agent with null tool_resources', async () => {
      await createFile({
        user: otherUser._id.toString(),
        file_id: 'another_orphan_file',
        filepath: '/test/orphan2.txt',
        filename: 'orphan2.txt',
        type: 'text/plain',
        size: 100,
      });

      // Create agent with null tool_resources
      await createAgent({
        id: `agent_null_${Date.now()}`,
        name: 'Null Resources Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: testUser._id,
        tool_resources: null,
      });

      req.params.file_id = 'another_orphan_file';
      await fileAccess(req, res, next);

      expect(next).not.toHaveBeenCalled();
      expect(res.status).toHaveBeenCalledWith(403);
    });
  });
});