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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
import { Request, Response, NextFunction } from 'express';
import {
  Permissions,
  PermissionTypes,
  EModelEndpoint,
  EndpointURLs,
} from 'librechat-data-provider';
import type { IRole, IUser } from '@librechat/data-schemas';
import { checkAccess, generateCheckAccess, skipAgentCheck } from './access';

// Mock logger
jest.mock('@librechat/data-schemas', () => ({
  logger: {
    warn: jest.fn(),
    error: jest.fn(),
    debug: jest.fn(),
  },
}));

describe('access middleware', () => {
  let mockReq: Partial<Request>;
  let mockRes: Partial<Response>;
  let mockNext: jest.MockedFunction<NextFunction>;
  let mockGetRoleByName: jest.Mock;

  beforeEach(() => {
    mockReq = {
      user: {
        id: 'user123',
        role: 'user',
        email: 'test@example.com',
        emailVerified: true,
        provider: 'local',
      } as IUser,
      body: {},
      originalUrl: '/api/test',
      method: 'POST',
    } as Partial<Request>;

    mockRes = {
      status: jest.fn().mockReturnThis(),
      json: jest.fn().mockReturnThis(),
    };

    mockNext = jest.fn() as jest.MockedFunction<NextFunction>;
    mockGetRoleByName = jest.fn();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('skipAgentCheck', () => {
    it('should return false when req is undefined', () => {
      expect(skipAgentCheck(undefined)).toBe(false);
    });

    it('should return false when req.body.endpoint is not present', () => {
      expect(skipAgentCheck(mockReq as Request)).toBe(false);
    });

    it('should return false when method is not POST', () => {
      mockReq.method = 'GET';
      mockReq.body = { endpoint: 'gpt-4' };
      expect(skipAgentCheck(mockReq as Request)).toBe(false);
    });

    it('should return false when URL does not include agents endpoint', () => {
      mockReq.body = { endpoint: 'gpt-4' };
      mockReq.originalUrl = '/api/messages';
      expect(skipAgentCheck(mockReq as Request)).toBe(false);
    });

    it('should return true when not an agents endpoint but URL includes agents', () => {
      mockReq.body = { endpoint: 'gpt-4' };
      mockReq.originalUrl = EndpointURLs[EModelEndpoint.agents];
      expect(skipAgentCheck(mockReq as Request)).toBe(true);
    });

    it('should return false when is an agents endpoint', () => {
      mockReq.body = { endpoint: EModelEndpoint.agents };
      mockReq.originalUrl = EndpointURLs[EModelEndpoint.agents];
      expect(skipAgentCheck(mockReq as Request)).toBe(false);
    });
  });

  describe('checkAccess', () => {
    const defaultParams = {
      user: {
        id: 'user123',
        role: 'user',
        email: 'test@example.com',
        emailVerified: true,
        provider: 'local',
      } as IUser,
      permissionType: PermissionTypes.AGENTS,
      permissions: [Permissions.USE],
      getRoleByName: jest.fn(),
    };

    it('should return true when skipCheck function returns true', async () => {
      const skipCheck = jest.fn().mockReturnValue(true);
      const result = await checkAccess({
        ...defaultParams,
        req: mockReq as Request,
        skipCheck,
      });
      expect(result).toBe(true);
      expect(skipCheck).toHaveBeenCalledWith(mockReq);
    });

    it('should return false when user is not provided', async () => {
      const result = await checkAccess({
        ...defaultParams,
        user: null as unknown as IUser,
      });
      expect(result).toBe(false);
    });

    it('should return false when user has no role', async () => {
      const result = await checkAccess({
        ...defaultParams,
        user: {
          id: 'user123',
          email: 'test@example.com',
          emailVerified: true,
          provider: 'local',
        } as IUser,
      });
      expect(result).toBe(false);
    });

    it('should return true when user has required permissions', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.USE]: true,
          },
        },
      } as unknown as IRole;

      defaultParams.getRoleByName.mockResolvedValue(mockRole);

      const result = await checkAccess(defaultParams);
      expect(result).toBe(true);
      expect(defaultParams.getRoleByName).toHaveBeenCalledWith('user');
    });

    it('should return false when user lacks required permissions', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.USE]: false,
          },
        },
      } as unknown as IRole;

      defaultParams.getRoleByName.mockResolvedValue(mockRole);

      const result = await checkAccess(defaultParams);
      expect(result).toBe(false);
    });

    it('should check multiple permissions with AND logic', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.USE]: true,
            [Permissions.CREATE]: true,
          },
        },
      } as unknown as IRole;

      defaultParams.getRoleByName.mockResolvedValue(mockRole);

      const result = await checkAccess({
        ...defaultParams,
        permissions: [Permissions.USE, Permissions.CREATE],
      });
      expect(result).toBe(true);
    });

    it('should return false when user has only some of the required permissions', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.USE]: true,
            [Permissions.CREATE]: false,
          },
        },
      } as unknown as IRole;

      defaultParams.getRoleByName.mockResolvedValue(mockRole);

      const result = await checkAccess({
        ...defaultParams,
        permissions: [Permissions.USE, Permissions.CREATE],
      });
      expect(result).toBe(false);
    });

    it('should check bodyProps when permission is not directly granted', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.USE]: true,
            [Permissions.SHARED_GLOBAL]: false,
          },
        },
      } as unknown as IRole;

      defaultParams.getRoleByName.mockResolvedValue(mockRole);

      const checkObject = {
        projectIds: ['project1'],
        removeProjectIds: ['project2'],
      };

      const result = await checkAccess({
        ...defaultParams,
        permissions: [Permissions.USE, Permissions.SHARED_GLOBAL],
        bodyProps: {
          [Permissions.SHARED_GLOBAL]: ['projectIds', 'removeProjectIds'],
        } as Record<Permissions, string[]>,
        checkObject,
      });
      expect(result).toBe(true);
    });

    it('should return false when bodyProps requirements are not met', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.SHARED_GLOBAL]: false,
          },
        },
      } as unknown as IRole;

      defaultParams.getRoleByName.mockResolvedValue(mockRole);

      const checkObject = {
        projectIds: ['project1'],
        // missing removeProjectIds
      };

      const result = await checkAccess({
        ...defaultParams,
        permissions: [Permissions.SHARED_GLOBAL],
        bodyProps: {
          [Permissions.SHARED_GLOBAL]: ['projectIds', 'removeProjectIds'],
        } as Record<Permissions, string[]>,
        checkObject,
      });
      expect(result).toBe(false);
    });

    it('should handle role without permissions object', async () => {
      const mockRole = {
        name: 'user',
      } as unknown as IRole;

      defaultParams.getRoleByName.mockResolvedValue(mockRole);

      const result = await checkAccess(defaultParams);
      expect(result).toBe(false);
    });

    it('should handle getRoleByName returning null', async () => {
      defaultParams.getRoleByName.mockResolvedValue(null);

      const result = await checkAccess(defaultParams);
      expect(result).toBe(false);
    });
  });

  describe('generateCheckAccess', () => {
    it('should create middleware that allows access when user has permissions', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.MEMORIES]: {
            [Permissions.USE]: true,
            [Permissions.READ]: true,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);

      const middleware = generateCheckAccess({
        permissionType: PermissionTypes.MEMORIES,
        permissions: [Permissions.USE, Permissions.READ],
        getRoleByName: mockGetRoleByName,
      });

      await middleware(mockReq as Request, mockRes as Response, mockNext);

      expect(mockNext).toHaveBeenCalled();
      expect(mockRes.status).not.toHaveBeenCalled();
    });

    it('should create middleware that denies access when user lacks permissions', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.MEMORIES]: {
            [Permissions.USE]: false,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);

      const middleware = generateCheckAccess({
        permissionType: PermissionTypes.MEMORIES,
        permissions: [Permissions.USE],
        getRoleByName: mockGetRoleByName,
      });

      await middleware(mockReq as Request, mockRes as Response, mockNext);

      expect(mockNext).not.toHaveBeenCalled();
      expect(mockRes.status).toHaveBeenCalledWith(403);
      expect(mockRes.json).toHaveBeenCalledWith({ message: 'Forbidden: Insufficient permissions' });
    });

    it('should handle bodyProps in middleware', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.USE]: true,
            [Permissions.CREATE]: true,
            [Permissions.SHARED_GLOBAL]: false,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);
      mockReq.body = {
        projectIds: ['project1'],
        removeProjectIds: ['project2'],
      };

      const middleware = generateCheckAccess({
        permissionType: PermissionTypes.AGENTS,
        permissions: [Permissions.USE, Permissions.CREATE, Permissions.SHARED_GLOBAL],
        bodyProps: {
          [Permissions.SHARED_GLOBAL]: ['projectIds', 'removeProjectIds'],
        } as Record<Permissions, string[]>,
        getRoleByName: mockGetRoleByName,
      });

      await middleware(mockReq as Request, mockRes as Response, mockNext);

      expect(mockNext).toHaveBeenCalled();
      expect(mockRes.status).not.toHaveBeenCalled();
    });

    it('should use skipCheck function when provided', async () => {
      const skipCheck = jest.fn().mockReturnValue(true);

      const middleware = generateCheckAccess({
        permissionType: PermissionTypes.AGENTS,
        permissions: [Permissions.USE],
        skipCheck,
        getRoleByName: mockGetRoleByName,
      });

      await middleware(mockReq as Request, mockRes as Response, mockNext);

      expect(skipCheck).toHaveBeenCalledWith(mockReq);
      expect(mockNext).toHaveBeenCalled();
      expect(mockGetRoleByName).not.toHaveBeenCalled();
    });

    it('should handle errors and return 500 status', async () => {
      const error = new Error('Database error');
      mockGetRoleByName.mockRejectedValue(error);

      const middleware = generateCheckAccess({
        permissionType: PermissionTypes.AGENTS,
        permissions: [Permissions.USE],
        getRoleByName: mockGetRoleByName,
      });

      await middleware(mockReq as Request, mockRes as Response, mockNext);

      expect(mockRes.status).toHaveBeenCalledWith(500);
      expect(mockRes.json).toHaveBeenCalledWith({
        message: 'Server error: Database error',
      });
    });

    it('should handle non-Error objects in catch block', async () => {
      mockGetRoleByName.mockRejectedValue('String error');

      const middleware = generateCheckAccess({
        permissionType: PermissionTypes.AGENTS,
        permissions: [Permissions.USE],
        getRoleByName: mockGetRoleByName,
      });

      await middleware(mockReq as Request, mockRes as Response, mockNext);

      expect(mockRes.status).toHaveBeenCalledWith(500);
      expect(mockRes.json).toHaveBeenCalledWith({
        message: 'Server error: Unknown error',
      });
    });
  });

  describe('Real-world usage patterns', () => {
    it('should handle memory access patterns', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.MEMORIES]: {
            [Permissions.USE]: true,
            [Permissions.CREATE]: true,
            [Permissions.UPDATE]: true,
            [Permissions.READ]: true,
            [Permissions.OPT_OUT]: true,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);

      // Test memory read access
      const checkMemoryRead = generateCheckAccess({
        permissionType: PermissionTypes.MEMORIES,
        permissions: [Permissions.USE, Permissions.READ],
        getRoleByName: mockGetRoleByName,
      });

      await checkMemoryRead(mockReq as Request, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenCalled();

      // Test memory create access
      mockNext.mockClear();
      const checkMemoryCreate = generateCheckAccess({
        permissionType: PermissionTypes.MEMORIES,
        permissions: [Permissions.USE, Permissions.CREATE],
        getRoleByName: mockGetRoleByName,
      });

      await checkMemoryCreate(mockReq as Request, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenCalled();
    });

    it('should handle agent access patterns with skipCheck', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.AGENTS]: {
            [Permissions.USE]: true,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);
      mockReq.body = { endpoint: 'gpt-4' };
      mockReq.originalUrl = EndpointURLs[EModelEndpoint.agents];

      const checkAgentAccess = generateCheckAccess({
        permissionType: PermissionTypes.AGENTS,
        permissions: [Permissions.USE],
        skipCheck: skipAgentCheck,
        getRoleByName: mockGetRoleByName,
      });

      await checkAgentAccess(mockReq as Request, mockRes as Response, mockNext);

      // Should skip check because endpoint is not agents
      expect(mockNext).toHaveBeenCalled();
      expect(mockGetRoleByName).not.toHaveBeenCalled();
    });

    it('should handle prompt access patterns', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.PROMPTS]: {
            [Permissions.USE]: true,
            [Permissions.CREATE]: true,
            [Permissions.SHARED_GLOBAL]: false,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);

      const checkPromptAccess = generateCheckAccess({
        permissionType: PermissionTypes.PROMPTS,
        permissions: [Permissions.USE],
        getRoleByName: mockGetRoleByName,
      });

      await checkPromptAccess(mockReq as Request, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenCalled();
    });

    it('should handle bookmark access patterns', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.BOOKMARKS]: {
            [Permissions.USE]: true,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);

      const checkBookmarkAccess = generateCheckAccess({
        permissionType: PermissionTypes.BOOKMARKS,
        permissions: [Permissions.USE],
        getRoleByName: mockGetRoleByName,
      });

      await checkBookmarkAccess(mockReq as Request, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenCalled();
    });

    it('should handle tool access patterns', async () => {
      const mockRole = {
        name: 'user',
        permissions: {
          [PermissionTypes.RUN_CODE]: {
            [Permissions.USE]: true,
          },
        },
      } as unknown as IRole;

      mockGetRoleByName.mockResolvedValue(mockRole);

      const result = await checkAccess({
        user: mockReq.user as IUser,
        permissionType: PermissionTypes.RUN_CODE,
        permissions: [Permissions.USE],
        getRoleByName: mockGetRoleByName,
      });

      expect(result).toBe(true);
    });
  });
});