@flusys/nestjs-iam 6.0.2 → 6.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/cjs/controllers/action.controller.spec.js +79 -0
  2. package/cjs/controllers/company-action-permission.controller.js +1 -1
  3. package/cjs/controllers/company-action-permission.controller.spec.js +65 -0
  4. package/cjs/controllers/my-permission.controller.spec.js +56 -0
  5. package/cjs/controllers/role-permission.controller.spec.js +140 -0
  6. package/cjs/controllers/role.controller.spec.js +86 -0
  7. package/cjs/controllers/user-action-permission.controller.js +1 -1
  8. package/cjs/controllers/user-action-permission.controller.spec.js +68 -0
  9. package/cjs/docs/iam-swagger.config.spec.js +99 -0
  10. package/cjs/dtos/permission.dto.js +7 -0
  11. package/cjs/entities/index.spec.js +56 -0
  12. package/cjs/entities/permission-base.entity.js +1 -10
  13. package/cjs/entities/permission-with-company.entity.js +0 -3
  14. package/cjs/entities/user-iam-permission.entity.js +0 -3
  15. package/cjs/helpers/company-access.helper.spec.js +68 -0
  16. package/cjs/helpers/permission-mode.helper.spec.js +54 -0
  17. package/cjs/modules/iam.module.js +2 -2
  18. package/cjs/modules/iam.module.spec.js +293 -0
  19. package/cjs/services/action.service.js +4 -4
  20. package/cjs/services/action.service.spec.js +314 -0
  21. package/cjs/services/iam-config.service.spec.js +110 -0
  22. package/cjs/services/iam-datasource.service.spec.js +117 -0
  23. package/cjs/services/permission-cache.service.js +363 -52
  24. package/cjs/services/permission-cache.service.spec.js +699 -0
  25. package/cjs/services/permission.service.js +92 -396
  26. package/cjs/services/permission.service.spec.js +692 -0
  27. package/cjs/services/role.service.js +1 -1
  28. package/cjs/services/role.service.spec.js +309 -0
  29. package/dtos/permission.dto.d.ts +1 -0
  30. package/entities/permission-base.entity.d.ts +0 -1
  31. package/fesm/controllers/action.controller.spec.js +75 -0
  32. package/fesm/controllers/company-action-permission.controller.js +1 -1
  33. package/fesm/controllers/company-action-permission.controller.spec.js +61 -0
  34. package/fesm/controllers/my-permission.controller.spec.js +52 -0
  35. package/fesm/controllers/role-permission.controller.spec.js +136 -0
  36. package/fesm/controllers/role.controller.spec.js +82 -0
  37. package/fesm/controllers/user-action-permission.controller.js +1 -1
  38. package/fesm/controllers/user-action-permission.controller.spec.js +64 -0
  39. package/fesm/docs/iam-swagger.config.spec.js +95 -0
  40. package/fesm/dtos/permission.dto.js +7 -0
  41. package/fesm/entities/index.spec.js +52 -0
  42. package/fesm/entities/permission-base.entity.js +1 -10
  43. package/fesm/entities/permission-with-company.entity.js +0 -3
  44. package/fesm/entities/user-iam-permission.entity.js +0 -3
  45. package/fesm/helpers/company-access.helper.spec.js +64 -0
  46. package/fesm/helpers/permission-mode.helper.spec.js +50 -0
  47. package/fesm/modules/iam.module.js +4 -4
  48. package/fesm/modules/iam.module.spec.js +289 -0
  49. package/fesm/services/action.service.js +4 -4
  50. package/fesm/services/action.service.spec.js +310 -0
  51. package/fesm/services/iam-config.service.spec.js +106 -0
  52. package/fesm/services/iam-datasource.service.spec.js +113 -0
  53. package/fesm/services/permission-cache.service.js +365 -51
  54. package/fesm/services/permission-cache.service.spec.js +695 -0
  55. package/fesm/services/permission.service.js +92 -396
  56. package/fesm/services/permission.service.spec.js +688 -0
  57. package/fesm/services/role.service.js +1 -1
  58. package/fesm/services/role.service.spec.js +305 -0
  59. package/package.json +3 -3
  60. package/services/permission-cache.service.d.ts +20 -3
  61. package/services/permission.service.d.ts +2 -16
@@ -0,0 +1,692 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ const _testing = require("@nestjs/testing");
6
+ const _repositorymock = require("@test-utils/mocks/repository.mock");
7
+ const _config = require("../config");
8
+ const _permissiondto = require("../dtos/permission.dto");
9
+ const _actionentity = require("../entities/action.entity");
10
+ const _roleentity = require("../entities/role.entity");
11
+ const _rolewithcompanyentity = require("../entities/role-with-company.entity");
12
+ const _actiontypeenum = require("../enums/action-type.enum");
13
+ const _iamentitytypeenum = require("../enums/iam-entity-type.enum");
14
+ const _iampermissiontypeenum = require("../enums/iam-permission-type.enum");
15
+ const _permissiontypeenum = require("../enums/permission-type.enum");
16
+ const _iamconfigservice = require("./iam-config.service");
17
+ const _iamdatasourceservice = require("./iam-datasource.service");
18
+ const _permissioncacheservice = require("./permission-cache.service");
19
+ const _permissionservice = require("./permission.service");
20
+ function buildPermissionRow(overrides = {}) {
21
+ const row = {
22
+ id: 'perm-uuid-1',
23
+ permissionType: _iampermissiontypeenum.IamPermissionType.USER_ACTION,
24
+ sourceType: _iamentitytypeenum.IamEntityType.USER,
25
+ sourceId: 'user-1',
26
+ targetType: _iamentitytypeenum.IamEntityType.ACTION,
27
+ targetId: 'action-1',
28
+ companyId: null,
29
+ branchId: null,
30
+ validFrom: null,
31
+ validUntil: null,
32
+ reason: null,
33
+ createdAt: new Date(),
34
+ ...overrides
35
+ };
36
+ row.isValid = (now = new Date())=>{
37
+ if (row.validFrom && now < row.validFrom) return false;
38
+ if (row.validUntil && now > row.validUntil) return false;
39
+ return true;
40
+ };
41
+ return row;
42
+ }
43
+ function buildDeleteResult(affected) {
44
+ return {
45
+ affected,
46
+ raw: []
47
+ };
48
+ }
49
+ function mockRawMany(repo, rows) {
50
+ const builder = {
51
+ select: jest.fn().mockReturnThis(),
52
+ addSelect: jest.fn().mockReturnThis(),
53
+ where: jest.fn().mockReturnThis(),
54
+ andWhere: jest.fn().mockReturnThis(),
55
+ getRawMany: jest.fn().mockResolvedValue(rows)
56
+ };
57
+ repo.createQueryBuilder.mockReturnValue(builder);
58
+ return builder;
59
+ }
60
+ function buildAction(overrides = {}) {
61
+ return {
62
+ id: 'action-1',
63
+ name: 'View Users',
64
+ code: 'user.view',
65
+ description: null,
66
+ actionType: _actiontypeenum.ActionType.BACKEND,
67
+ parentId: null,
68
+ isActive: true,
69
+ ...overrides
70
+ };
71
+ }
72
+ describe('PermissionService', ()=>{
73
+ let service;
74
+ let mockPermissionRepo;
75
+ let mockActionRepo;
76
+ let mockRoleRepo;
77
+ let mockIamConfigService;
78
+ let mockPermissionCacheService;
79
+ let mockDataSourceProvider;
80
+ beforeEach(async ()=>{
81
+ mockPermissionRepo = (0, _repositorymock.createMockRepository)();
82
+ mockActionRepo = (0, _repositorymock.createMockRepository)();
83
+ mockRoleRepo = (0, _repositorymock.createMockRepository)();
84
+ mockDataSourceProvider = {
85
+ getRepository: jest.fn((entity)=>{
86
+ if (entity === _actionentity.Action) return Promise.resolve(mockActionRepo);
87
+ if (entity === _roleentity.Role || entity === _rolewithcompanyentity.RoleWithCompany) return Promise.resolve(mockRoleRepo);
88
+ return Promise.resolve(mockPermissionRepo);
89
+ }),
90
+ getDataSource: jest.fn()
91
+ };
92
+ mockIamConfigService = {
93
+ isCompanyFeatureEnabled: jest.fn().mockReturnValue(false),
94
+ isDirectPermissionEnabled: jest.fn().mockReturnValue(true),
95
+ isRbacEnabled: jest.fn().mockReturnValue(true),
96
+ getPermissionMode: jest.fn().mockReturnValue(_permissiontypeenum.IAMPermissionMode.FULL)
97
+ };
98
+ mockPermissionCacheService = {
99
+ invalidateUser: jest.fn(),
100
+ invalidateUsers: jest.fn(),
101
+ invalidateRoleMembersCache: jest.fn(),
102
+ invalidateCompanyMembersCache: jest.fn(),
103
+ getMyPermissionsResponse: jest.fn()
104
+ };
105
+ const module = await _testing.Test.createTestingModule({
106
+ providers: [
107
+ _permissionservice.PermissionService,
108
+ {
109
+ provide: _permissioncacheservice.PermissionCacheService,
110
+ useValue: mockPermissionCacheService
111
+ },
112
+ {
113
+ provide: _iamconfigservice.IAMConfigService,
114
+ useValue: mockIamConfigService
115
+ },
116
+ {
117
+ provide: _iamdatasourceservice.IAMDataSourceService,
118
+ useValue: mockDataSourceProvider
119
+ }
120
+ ]
121
+ }).compile();
122
+ service = await module.resolve(_permissionservice.PermissionService);
123
+ });
124
+ // ==================== User-Action Permissions ====================
125
+ describe('assignUserActions', ()=>{
126
+ const dto = {
127
+ userId: 'user-1',
128
+ items: [
129
+ {
130
+ id: 'action-1',
131
+ action: _permissiondto.PermissionAction.ADD
132
+ },
133
+ {
134
+ id: 'action-2',
135
+ action: _permissiondto.PermissionAction.ADD
136
+ },
137
+ {
138
+ id: 'action-3',
139
+ action: _permissiondto.PermissionAction.REMOVE
140
+ }
141
+ ]
142
+ };
143
+ it('throws BadRequestException when direct permissions are disabled (RBAC-only mode)', async ()=>{
144
+ mockIamConfigService.isDirectPermissionEnabled.mockReturnValue(false);
145
+ await expect(service.assignUserActions(dto)).rejects.toMatchObject({
146
+ response: expect.objectContaining({
147
+ messageKey: _config.IAM_MODE_MESSAGES.DIRECT_MODE_UNAVAILABLE
148
+ })
149
+ });
150
+ expect(mockPermissionRepo.find).not.toHaveBeenCalled();
151
+ });
152
+ it('adds only actions not already assigned, removes requested actions, and invalidates the user cache', async ()=>{
153
+ mockPermissionRepo.find.mockResolvedValue([
154
+ {
155
+ targetId: 'action-1'
156
+ }
157
+ ]);
158
+ mockPermissionRepo.save.mockResolvedValue([
159
+ {}
160
+ ]);
161
+ mockPermissionRepo.delete.mockResolvedValue(buildDeleteResult(1));
162
+ const result = await service.assignUserActions(dto);
163
+ expect(mockPermissionRepo.save).toHaveBeenCalledWith([
164
+ expect.objectContaining({
165
+ targetId: 'action-2',
166
+ companyId: null,
167
+ branchId: null
168
+ })
169
+ ]);
170
+ expect(result).toEqual({
171
+ added: 1,
172
+ removed: 1,
173
+ total: 3
174
+ });
175
+ expect(mockPermissionCacheService.invalidateUser).toHaveBeenCalledWith('user-1', null, []);
176
+ });
177
+ it('scopes new permissions and cache invalidation to the company/branch when the company feature is enabled', async ()=>{
178
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
179
+ mockPermissionRepo.find.mockResolvedValue([]);
180
+ mockPermissionRepo.save.mockResolvedValue([
181
+ {},
182
+ {}
183
+ ]);
184
+ mockPermissionRepo.delete.mockResolvedValue(buildDeleteResult(1));
185
+ await service.assignUserActions({
186
+ userId: 'user-1',
187
+ companyId: 'company-1',
188
+ branchId: 'branch-1',
189
+ items: dto.items
190
+ });
191
+ expect(mockPermissionRepo.find).toHaveBeenCalledWith(expect.objectContaining({
192
+ where: expect.objectContaining({
193
+ companyId: 'company-1',
194
+ branchId: 'branch-1'
195
+ })
196
+ }));
197
+ expect(mockPermissionRepo.save).toHaveBeenCalledWith([
198
+ expect.objectContaining({
199
+ companyId: 'company-1',
200
+ branchId: 'branch-1'
201
+ }),
202
+ expect.objectContaining({
203
+ companyId: 'company-1',
204
+ branchId: 'branch-1'
205
+ })
206
+ ]);
207
+ expect(mockPermissionCacheService.invalidateUser).toHaveBeenCalledWith('user-1', 'company-1', [
208
+ 'branch-1'
209
+ ]);
210
+ });
211
+ it('translates a duplicate-entry DB error into ConflictException', async ()=>{
212
+ mockPermissionRepo.find.mockResolvedValue([]);
213
+ mockPermissionRepo.save.mockRejectedValue({
214
+ code: 'ER_DUP_ENTRY'
215
+ });
216
+ await expect(service.assignUserActions(dto)).rejects.toMatchObject({
217
+ response: expect.objectContaining({
218
+ messageKey: _config.PERMISSION_OPERATION_MESSAGES.ALREADY_EXISTS
219
+ })
220
+ });
221
+ });
222
+ it('rethrows unknown errors from save as-is', async ()=>{
223
+ mockPermissionRepo.find.mockResolvedValue([]);
224
+ const unexpected = new Error('connection lost');
225
+ mockPermissionRepo.save.mockRejectedValue(unexpected);
226
+ await expect(service.assignUserActions(dto)).rejects.toBe(unexpected);
227
+ });
228
+ it('does nothing but still invalidates the cache when items is empty', async ()=>{
229
+ const result = await service.assignUserActions({
230
+ userId: 'user-1',
231
+ items: []
232
+ });
233
+ expect(result).toEqual({
234
+ added: 0,
235
+ removed: 0,
236
+ total: 0
237
+ });
238
+ expect(mockPermissionRepo.save).not.toHaveBeenCalled();
239
+ expect(mockPermissionRepo.delete).not.toHaveBeenCalled();
240
+ expect(mockPermissionCacheService.invalidateUser).toHaveBeenCalled();
241
+ });
242
+ });
243
+ describe('getUserActions', ()=>{
244
+ it('returns an empty array without querying actions when the user has no permissions', async ()=>{
245
+ mockPermissionRepo.find.mockResolvedValue([]);
246
+ const result = await service.getUserActions('user-1', undefined, undefined);
247
+ expect(result).toEqual([]);
248
+ expect(mockActionRepo.find).not.toHaveBeenCalled();
249
+ });
250
+ it('joins permissions with their actions and filters out permissions for deleted actions', async ()=>{
251
+ mockPermissionRepo.find.mockResolvedValue([
252
+ buildPermissionRow({
253
+ targetId: 'action-1'
254
+ }),
255
+ buildPermissionRow({
256
+ id: 'perm-2',
257
+ targetId: 'action-missing'
258
+ })
259
+ ]);
260
+ mockActionRepo.find.mockResolvedValue([
261
+ buildAction({
262
+ id: 'action-1'
263
+ })
264
+ ]);
265
+ const result = await service.getUserActions('user-1', undefined, undefined);
266
+ expect(result).toHaveLength(1);
267
+ expect(result[0]).toEqual(expect.objectContaining({
268
+ actionId: 'action-1',
269
+ actionCode: 'user.view'
270
+ }));
271
+ });
272
+ it('filters by companyId/branchId when the company feature is enabled', async ()=>{
273
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
274
+ mockPermissionRepo.find.mockResolvedValue([]);
275
+ await service.getUserActions('user-1', 'company-1', 'branch-1');
276
+ expect(mockPermissionRepo.find).toHaveBeenCalledWith({
277
+ where: expect.objectContaining({
278
+ companyId: 'company-1',
279
+ branchId: 'branch-1'
280
+ })
281
+ });
282
+ });
283
+ });
284
+ // ==================== Role-Action Permissions ====================
285
+ describe('assignRoleActions', ()=>{
286
+ const dto = {
287
+ roleId: 'role-1',
288
+ items: [
289
+ {
290
+ id: 'action-1',
291
+ action: _permissiondto.PermissionAction.ADD
292
+ },
293
+ {
294
+ id: 'action-2',
295
+ action: _permissiondto.PermissionAction.REMOVE
296
+ }
297
+ ]
298
+ };
299
+ it('throws BadRequestException when RBAC is disabled (DIRECT-only mode)', async ()=>{
300
+ mockIamConfigService.isRbacEnabled.mockReturnValue(false);
301
+ await expect(service.assignRoleActions(dto)).rejects.toMatchObject({
302
+ response: expect.objectContaining({
303
+ messageKey: _config.IAM_MODE_MESSAGES.RBAC_MODE_UNAVAILABLE
304
+ })
305
+ });
306
+ });
307
+ it('resolves the role company scope from the role repository when the company feature is enabled', async ()=>{
308
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
309
+ mockRoleRepo.findOne.mockResolvedValue({
310
+ id: 'role-1',
311
+ companyId: 'company-9'
312
+ });
313
+ mockPermissionRepo.find.mockResolvedValue([]);
314
+ mockPermissionRepo.save.mockResolvedValue([
315
+ {}
316
+ ]);
317
+ mockPermissionRepo.delete.mockResolvedValue(buildDeleteResult(1));
318
+ await service.assignRoleActions(dto);
319
+ expect(mockPermissionRepo.save).toHaveBeenCalledWith([
320
+ expect.objectContaining({
321
+ companyId: 'company-9'
322
+ })
323
+ ]);
324
+ });
325
+ it('translates duplicate role-action entries into ConflictException', async ()=>{
326
+ mockPermissionRepo.find.mockResolvedValue([]);
327
+ mockPermissionRepo.save.mockRejectedValue({
328
+ message: 'Duplicate entry for key'
329
+ });
330
+ await expect(service.assignRoleActions(dto)).rejects.toMatchObject({
331
+ response: expect.objectContaining({
332
+ messageKey: _config.PERMISSION_OPERATION_MESSAGES.ALREADY_EXISTS
333
+ })
334
+ });
335
+ });
336
+ it('removes role actions and reports counts and invalidates role member caches', async ()=>{
337
+ mockPermissionRepo.find.mockResolvedValue([]); // existing check for add
338
+ mockPermissionRepo.save.mockResolvedValue([
339
+ {}
340
+ ]);
341
+ mockPermissionRepo.delete.mockResolvedValue(buildDeleteResult(1));
342
+ const result = await service.assignRoleActions(dto);
343
+ expect(result).toEqual({
344
+ added: 1,
345
+ removed: 1,
346
+ total: 2
347
+ });
348
+ expect(mockPermissionCacheService.invalidateRoleMembersCache).toHaveBeenCalledWith('role-1');
349
+ });
350
+ });
351
+ describe('getRoleActions', ()=>{
352
+ it('returns an empty array when the role has no actions assigned', async ()=>{
353
+ mockPermissionRepo.find.mockResolvedValue([]);
354
+ const result = await service.getRoleActions('role-1');
355
+ expect(result).toEqual([]);
356
+ });
357
+ it('maps role-action permissions to their action details', async ()=>{
358
+ mockPermissionRepo.find.mockResolvedValue([
359
+ buildPermissionRow({
360
+ sourceId: 'role-1',
361
+ targetId: 'action-1'
362
+ })
363
+ ]);
364
+ mockActionRepo.find.mockResolvedValue([
365
+ buildAction({
366
+ id: 'action-1'
367
+ })
368
+ ]);
369
+ const result = await service.getRoleActions('role-1');
370
+ expect(result).toEqual([
371
+ expect.objectContaining({
372
+ roleId: 'role-1',
373
+ actionCode: 'user.view'
374
+ })
375
+ ]);
376
+ });
377
+ });
378
+ // ==================== Company-Action Permissions ====================
379
+ describe('assignCompanyActions', ()=>{
380
+ function mockTransaction() {
381
+ const fakeManager = {
382
+ getRepository: jest.fn((entity)=>{
383
+ if (entity === _roleentity.Role || entity === _rolewithcompanyentity.RoleWithCompany) return mockRoleRepo;
384
+ return mockPermissionRepo;
385
+ })
386
+ };
387
+ mockDataSourceProvider.getDataSource.mockResolvedValue({
388
+ transaction: jest.fn().mockImplementation((cb)=>cb(fakeManager))
389
+ });
390
+ return fakeManager;
391
+ }
392
+ it('adds new company-whitelisted actions inside a transaction, skipping duplicates', async ()=>{
393
+ mockTransaction();
394
+ mockPermissionRepo.find.mockResolvedValue([
395
+ {
396
+ targetId: 'action-1'
397
+ }
398
+ ]);
399
+ mockPermissionRepo.create.mockImplementation((data)=>data);
400
+ mockPermissionRepo.save.mockResolvedValue([
401
+ {}
402
+ ]);
403
+ const result = await service.assignCompanyActions({
404
+ companyId: 'company-1',
405
+ items: [
406
+ {
407
+ id: 'action-1',
408
+ action: _permissiondto.PermissionAction.ADD
409
+ },
410
+ {
411
+ id: 'action-2',
412
+ action: _permissiondto.PermissionAction.ADD
413
+ }
414
+ ]
415
+ });
416
+ expect(mockPermissionRepo.save).toHaveBeenCalledWith([
417
+ expect.objectContaining({
418
+ targetId: 'action-2',
419
+ sourceId: 'company-1'
420
+ })
421
+ ]);
422
+ expect(result.added).toBe(1);
423
+ expect(mockPermissionCacheService.invalidateCompanyMembersCache).toHaveBeenCalledWith('company-1');
424
+ });
425
+ it('cascades removal to role-action and user-action permissions for the company', async ()=>{
426
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
427
+ mockTransaction();
428
+ mockPermissionRepo.delete.mockResolvedValue(buildDeleteResult(2));
429
+ mockRoleRepo.find.mockResolvedValue([
430
+ {
431
+ id: 'role-1'
432
+ }
433
+ ]);
434
+ mockRawMany(mockPermissionRepo, []);
435
+ const result = await service.assignCompanyActions({
436
+ companyId: 'company-1',
437
+ items: [
438
+ {
439
+ id: 'action-1',
440
+ action: _permissiondto.PermissionAction.REMOVE
441
+ }
442
+ ]
443
+ });
444
+ expect(mockPermissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
445
+ permissionType: _iampermissiontypeenum.IamPermissionType.COMPANY_ACTION
446
+ }));
447
+ expect(mockPermissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
448
+ permissionType: _iampermissiontypeenum.IamPermissionType.ROLE_ACTION
449
+ }));
450
+ expect(mockPermissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
451
+ permissionType: _iampermissiontypeenum.IamPermissionType.USER_ACTION
452
+ }));
453
+ expect(result.removed).toBe(2);
454
+ });
455
+ });
456
+ describe('getCompanyActions / getCompanyActionIds', ()=>{
457
+ it('getCompanyActions returns an empty array when the company has no whitelist entries', async ()=>{
458
+ mockPermissionRepo.find.mockResolvedValue([]);
459
+ expect(await service.getCompanyActions('company-1')).toEqual([]);
460
+ });
461
+ it('getCompanyActions maps whitelist entries to action details', async ()=>{
462
+ mockPermissionRepo.find.mockResolvedValue([
463
+ buildPermissionRow({
464
+ sourceType: _iamentitytypeenum.IamEntityType.COMPANY,
465
+ sourceId: 'company-1',
466
+ targetId: 'action-1'
467
+ })
468
+ ]);
469
+ mockActionRepo.find.mockResolvedValue([
470
+ buildAction({
471
+ id: 'action-1'
472
+ })
473
+ ]);
474
+ const result = await service.getCompanyActions('company-1');
475
+ expect(result).toEqual([
476
+ expect.objectContaining({
477
+ companyId: 'company-1',
478
+ actionCode: 'user.view'
479
+ })
480
+ ]);
481
+ });
482
+ it('getCompanyActionIds returns just the whitelisted action ids', async ()=>{
483
+ mockPermissionRepo.find.mockResolvedValue([
484
+ {
485
+ targetId: 'action-1'
486
+ },
487
+ {
488
+ targetId: 'action-2'
489
+ }
490
+ ]);
491
+ const result = await service.getCompanyActions('company-1', true);
492
+ expect(result).toEqual([
493
+ 'action-1',
494
+ 'action-2'
495
+ ]);
496
+ });
497
+ });
498
+ // ==================== User-Role Permissions ====================
499
+ describe('assignUserRoles', ()=>{
500
+ const dto = {
501
+ userId: 'user-1',
502
+ items: [
503
+ {
504
+ id: 'role-1',
505
+ action: _permissiondto.PermissionAction.ADD
506
+ }
507
+ ]
508
+ };
509
+ it('throws BadRequestException when RBAC is disabled (DIRECT-only mode)', async ()=>{
510
+ mockIamConfigService.isRbacEnabled.mockReturnValue(false);
511
+ await expect(service.assignUserRoles(dto)).rejects.toMatchObject({
512
+ response: expect.objectContaining({
513
+ messageKey: _config.IAM_MODE_MESSAGES.ROLE_ASSIGNMENT_UNAVAILABLE
514
+ })
515
+ });
516
+ });
517
+ it('adds new role assignments and invalidates the user cache', async ()=>{
518
+ mockPermissionRepo.find.mockResolvedValue([]);
519
+ mockPermissionRepo.save.mockResolvedValue([
520
+ {}
521
+ ]);
522
+ const result = await service.assignUserRoles(dto);
523
+ expect(result).toEqual({
524
+ added: 1,
525
+ removed: 0,
526
+ total: 1
527
+ });
528
+ expect(mockPermissionCacheService.invalidateUser).toHaveBeenCalledWith('user-1', null, [
529
+ null
530
+ ]);
531
+ });
532
+ it('translates duplicate user-role entries into ConflictException', async ()=>{
533
+ mockPermissionRepo.find.mockResolvedValue([]);
534
+ mockPermissionRepo.save.mockRejectedValue({
535
+ code: 'ER_DUP_ENTRY'
536
+ });
537
+ await expect(service.assignUserRoles(dto)).rejects.toMatchObject({
538
+ response: expect.objectContaining({
539
+ messageKey: _config.PERMISSION_OPERATION_MESSAGES.ALREADY_EXISTS
540
+ })
541
+ });
542
+ });
543
+ });
544
+ describe('getUserRoles', ()=>{
545
+ it('returns an empty array when the user has no role assignments', async ()=>{
546
+ mockPermissionRepo.find.mockResolvedValue([]);
547
+ expect(await service.getUserRoles('user-1')).toEqual([]);
548
+ expect(mockRoleRepo.find).not.toHaveBeenCalled();
549
+ });
550
+ it('joins role permissions with role details and filters out permissions for deleted roles', async ()=>{
551
+ mockPermissionRepo.find.mockResolvedValue([
552
+ buildPermissionRow({
553
+ targetId: 'role-1',
554
+ targetType: _iamentitytypeenum.IamEntityType.ROLE
555
+ }),
556
+ buildPermissionRow({
557
+ id: 'perm-2',
558
+ targetId: 'role-missing',
559
+ targetType: _iamentitytypeenum.IamEntityType.ROLE
560
+ })
561
+ ]);
562
+ mockRoleRepo.find.mockResolvedValue([
563
+ {
564
+ id: 'role-1',
565
+ name: 'Manager'
566
+ }
567
+ ]);
568
+ const result = await service.getUserRoles('user-1');
569
+ expect(result).toHaveLength(1);
570
+ expect(result[0]).toEqual(expect.objectContaining({
571
+ roleId: 'role-1',
572
+ roleName: 'Manager'
573
+ }));
574
+ });
575
+ });
576
+ // ==================== My Permissions / permission-mode branching ====================
577
+ describe('getMyPermissions', ()=>{
578
+ it('delegates to the cache service and returns its response', async ()=>{
579
+ const response = {
580
+ frontendActions: [
581
+ {
582
+ id: 'action-1',
583
+ code: 'user.view',
584
+ name: 'View',
585
+ description: null
586
+ }
587
+ ],
588
+ cachedEndpoints: 1
589
+ };
590
+ mockPermissionCacheService.getMyPermissionsResponse.mockResolvedValue(response);
591
+ const result = await service.getMyPermissions('user-1', null, 'company-1', [
592
+ 'parent-code'
593
+ ]);
594
+ expect(mockPermissionCacheService.getMyPermissionsResponse).toHaveBeenCalledWith('user-1', null, 'company-1', [
595
+ 'parent-code'
596
+ ]);
597
+ expect(result).toBe(response);
598
+ });
599
+ });
600
+ describe('revokeCompanyPermissions', ()=>{
601
+ it('does nothing when the company feature is disabled', async ()=>{
602
+ await service.revokeCompanyPermissions('company-1');
603
+ expect(mockPermissionRepo.find).not.toHaveBeenCalled();
604
+ expect(mockRoleRepo.find).not.toHaveBeenCalled();
605
+ });
606
+ it('deletes company/role/user permissions transactionally and invalidates affected users', async ()=>{
607
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
608
+ mockRoleRepo.find.mockResolvedValue([
609
+ {
610
+ id: 'role-1'
611
+ }
612
+ ]);
613
+ mockPermissionRepo.find.mockResolvedValue([
614
+ {
615
+ sourceId: 'user-1'
616
+ }
617
+ ]);
618
+ const fakeTxRepo = {
619
+ delete: jest.fn().mockResolvedValue(buildDeleteResult(1))
620
+ };
621
+ const fakeTxRoleRepo = {
622
+ delete: jest.fn().mockResolvedValue(buildDeleteResult(1))
623
+ };
624
+ mockDataSourceProvider.getDataSource.mockResolvedValue({
625
+ transaction: jest.fn().mockImplementation((cb)=>cb({
626
+ getRepository: jest.fn((target)=>{
627
+ if (target === mockRoleRepo.target) return fakeTxRoleRepo;
628
+ return fakeTxRepo;
629
+ })
630
+ }))
631
+ });
632
+ await service.revokeCompanyPermissions('company-1');
633
+ expect(fakeTxRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
634
+ permissionType: _iampermissiontypeenum.IamPermissionType.COMPANY_ACTION
635
+ }));
636
+ expect(fakeTxRoleRepo.delete).toHaveBeenCalledWith([
637
+ 'role-1'
638
+ ]);
639
+ expect(mockPermissionCacheService.invalidateUsers).toHaveBeenCalledWith([
640
+ 'user-1'
641
+ ], 'company-1');
642
+ });
643
+ });
644
+ describe('revokeBranchPermissions', ()=>{
645
+ it('does nothing when the company feature is disabled', async ()=>{
646
+ await service.revokeBranchPermissions('branch-1', 'company-1');
647
+ expect(mockPermissionRepo.delete).not.toHaveBeenCalled();
648
+ });
649
+ it('deletes matching branch permissions and invalidates affected users', async ()=>{
650
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
651
+ mockPermissionRepo.find.mockResolvedValue([
652
+ {
653
+ sourceId: 'user-1'
654
+ }
655
+ ]);
656
+ mockPermissionRepo.delete.mockResolvedValue(buildDeleteResult(1));
657
+ await service.revokeBranchPermissions('branch-1', 'company-1');
658
+ expect(mockPermissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
659
+ branchId: 'branch-1',
660
+ companyId: 'company-1'
661
+ }));
662
+ expect(mockPermissionCacheService.invalidateUsers).toHaveBeenCalledWith([
663
+ 'user-1'
664
+ ], 'company-1', [
665
+ 'branch-1'
666
+ ]);
667
+ });
668
+ });
669
+ describe('revokeUserCompanyAccess', ()=>{
670
+ it('deletes user-role and user-action permissions for the company and invalidates the user cache', async ()=>{
671
+ await service.revokeUserCompanyAccess('user-1', 'company-1');
672
+ expect(mockPermissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
673
+ sourceId: 'user-1',
674
+ companyId: 'company-1'
675
+ }));
676
+ expect(mockPermissionCacheService.invalidateUser).toHaveBeenCalledWith('user-1', 'company-1');
677
+ });
678
+ });
679
+ describe('revokeUserBranchAccess', ()=>{
680
+ it('deletes branch-scoped permissions for the user and invalidates the user+branch cache', async ()=>{
681
+ await service.revokeUserBranchAccess('user-1', 'branch-1', 'company-1');
682
+ expect(mockPermissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
683
+ sourceId: 'user-1',
684
+ branchId: 'branch-1',
685
+ companyId: 'company-1'
686
+ }));
687
+ expect(mockPermissionCacheService.invalidateUser).toHaveBeenCalledWith('user-1', 'company-1', [
688
+ 'branch-1'
689
+ ]);
690
+ });
691
+ });
692
+ });