1 import {
2 createRbacPoliciesWorkflow,
3 createRbacRolesWorkflow,
4 } from "@medusajs/core-flows"
5 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
6 import { IRbacModuleService, MedusaContainer } from "@medusajs/types"
7 import {
8 ContainerRegistrationKeys,
9 definePolicies,
10 Modules,
11 Policy,
12 } from "@medusajs/utils"
13
14 jest.setTimeout(60000)
15
16 function clearPolicies() {
17 for (const policy of Object.keys(Policy)) {
18 delete Policy[policy]
19 }
20 }
21
22 medusaIntegrationTestRunner({
23 env: { MEDUSA_FF_RBAC: true },
24 testSuite: ({ getContainer }) => {
25 describe("Workflows: RBAC", () => {
26 let appContainer: MedusaContainer
27 let rbacService: IRbacModuleService
28
29 beforeAll(async () => {
30 appContainer = getContainer()
31 rbacService = appContainer.resolve(Modules.RBAC) as IRbacModuleService
32 })
33
34 describe("Role Parent and Policy Management", () => {
35 it("should create roles with parent and policies, then list all inherited policies", async () => {
36 // Step 1: Create base policies
37 const policiesWorkflow = createRbacPoliciesWorkflow(appContainer)
38 const { result: createdPolicies } = await policiesWorkflow.run({
39 input: {
40 policies: [
41 {
42 key: "read:products",
43 resource: "product",
44 operation: "read",
45 name: "Read Products",
46 description: "Permission to read products",
47 },
48 {
49 key: "write:products",
50 resource: "product",
51 operation: "write",
52 name: "Write Products",
53 description: "Permission to write products",
54 },
55 {
56 key: "read:orders",
57 resource: "order",
58 operation: "read",
59 name: "Read Orders",
60 description: "Permission to read orders",
61 },
62 {
63 key: "write:orders",
64 resource: "order",
65 operation: "write",
66 name: "Write Orders",
67 description: "Permission to write orders",
68 },
69 {
70 key: "delete:users",
71 resource: "user",
72 operation: "delete",
73 name: "Delete Users",
74 description: "Permission to delete users",
75 },
76 ],
77 },
78 })
79
80 expect(createdPolicies).toHaveLength(5)
81
82 // Step 2: Create base roles with their policies
83 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
84
85 // Create "Viewer" role with read permissions
86 const { result: viewerRoles } = await rolesWorkflow.run({
87 input: {
88 roles: [
89 {
90 name: "Viewer",
91 description: "Can view products and orders",
92 policy_ids: [
93 createdPolicies[0].id, // read:products
94 createdPolicies[2].id, // read:orders
95 ],
96 },
97 ],
98 },
99 })
100
101 expect(viewerRoles).toHaveLength(1)
102 const viewerRole = viewerRoles[0]
103
104 // Create "Editor" role with write permissions
105 const { result: editorRoles } = await rolesWorkflow.run({
106 input: {
107 roles: [
108 {
109 name: "Editor",
110 description: "Can write products and orders",
111 policy_ids: [
112 createdPolicies[1].id, // write:products
113 createdPolicies[3].id, // write:orders
114 ],
115 },
116 ],
117 },
118 })
119
120 expect(editorRoles).toHaveLength(1)
121 const editorRole = editorRoles[0]
122
123 // Step 3: Create "Admin" role that inherits from both Viewer and Editor, plus additional permissions
124 const { result: adminRoles } = await rolesWorkflow.run({
125 input: {
126 roles: [
127 {
128 name: "Admin",
129 description:
130 "Inherits from Viewer and Editor, plus can delete users",
131 parent_ids: [viewerRole.id, editorRole.id],
132 policy_ids: [
133 createdPolicies[4].id, // delete:users
134 ],
135 },
136 ],
137 },
138 })
139
140 expect(adminRoles).toHaveLength(1)
141 const adminRole = adminRoles[0]
142
143 // Step 4: Verify role parent was created
144 const parents = await rbacService.listRbacRoleParents({
145 role_id: adminRole.id,
146 })
147
148 expect(parents).toHaveLength(2)
149 expect(parents).toEqual(
150 expect.arrayContaining([
151 expect.objectContaining({
152 role_id: adminRole.id,
153 parent_id: viewerRole.id,
154 }),
155 expect.objectContaining({
156 role_id: adminRole.id,
157 parent_id: editorRole.id,
158 }),
159 ])
160 )
161
162 // Step 5: Verify direct policies for Admin role
163 const adminDirectPolicies = await rbacService.listRbacRolePolicies({
164 role_id: adminRole.id,
165 })
166
167 expect(adminDirectPolicies).toHaveLength(1)
168 expect(adminDirectPolicies[0]).toEqual(
169 expect.objectContaining({
170 role_id: adminRole.id,
171 policy_id: createdPolicies[4].id, // delete:users
172 })
173 )
174
175 // Step 6: List ALL policies for Admin role (including inherited)
176 const allAdminPolicies = await rbacService.listPoliciesForRole(
177 adminRole.id
178 )
179
180 // Admin should have:
181 // - read:products (from Viewer)
182 // - read:orders (from Viewer)
183 // - write:products (from Editor)
184 // - write:orders (from Editor)
185 // - delete:users (direct)
186 expect(allAdminPolicies).toHaveLength(5)
187
188 const policyKeys = allAdminPolicies.map((p) => p.key).sort()
189 expect(policyKeys).toEqual([
190 "delete:users",
191 "read:orders",
192 "read:products",
193 "write:orders",
194 "write:products",
195 ])
196
197 // Verify each policy has correct details
198 expect(allAdminPolicies).toEqual(
199 expect.arrayContaining([
200 expect.objectContaining({
201 key: "read:products",
202 resource: "product",
203 operation: "read",
204 }),
205 expect.objectContaining({
206 key: "write:products",
207 resource: "product",
208 operation: "write",
209 }),
210 expect.objectContaining({
211 key: "read:orders",
212 resource: "order",
213 operation: "read",
214 }),
215 expect.objectContaining({
216 key: "write:orders",
217 resource: "order",
218 operation: "write",
219 }),
220 expect.objectContaining({
221 key: "delete:users",
222 resource: "user",
223 operation: "delete",
224 }),
225 ])
226 )
227
228 // Step 7: Verify Viewer role only has its direct policies
229 const viewerPolicies = await rbacService.listPoliciesForRole(
230 viewerRole.id
231 )
232
233 expect(viewerPolicies).toHaveLength(2)
234 expect(viewerPolicies).toEqual(
235 expect.arrayContaining([
236 expect.objectContaining({
237 key: "read:products",
238 }),
239 expect.objectContaining({
240 key: "read:orders",
241 }),
242 ])
243 )
244
245 // Step 8: Verify Editor role only has its direct policies
246 const editorPolicies = await rbacService.listPoliciesForRole(
247 editorRole.id
248 )
249
250 expect(editorPolicies).toHaveLength(2)
251 expect(editorPolicies).toEqual(
252 expect.arrayContaining([
253 expect.objectContaining({
254 key: "write:products",
255 }),
256 expect.objectContaining({
257 key: "write:orders",
258 }),
259 ])
260 )
261 })
262
263 it("should handle multi-level role parent", async () => {
264 // Create policies
265 const policiesWorkflow = createRbacPoliciesWorkflow(appContainer)
266 const { result: policies } = await policiesWorkflow.run({
267 input: {
268 policies: [
269 {
270 key: "read:catalog",
271 resource: "catalog",
272 operation: "read",
273 name: "Read Catalog",
274 },
275 {
276 key: "write:catalog",
277 resource: "catalog",
278 operation: "write",
279 name: "Write Catalog",
280 },
281 {
282 key: "admin:system",
283 resource: "system",
284 operation: "admin",
285 name: "System Admin",
286 },
287 ],
288 },
289 })
290
291 // Create role hierarchy: Basic -> Manager -> SuperAdmin
292 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
293
294 // Level 1: Basic role
295 const { result: basicRoles } = await rolesWorkflow.run({
296 input: {
297 roles: [
298 {
299 name: "Basic User",
300 description: "Basic read access",
301 policy_ids: [policies[0].id], // read:catalog
302 },
303 ],
304 },
305 })
306 const basicRole = basicRoles[0]
307
308 // Level 2: Manager inherits from Basic
309 const { result: managerRoles } = await rolesWorkflow.run({
310 input: {
311 roles: [
312 {
313 name: "Manager",
314 description: "Manager with write access",
315 parent_ids: [basicRole.id],
316 policy_ids: [policies[1].id], // write:catalog
317 },
318 ],
319 },
320 })
321 const managerRole = managerRoles[0]
322
323 // Level 3: SuperAdmin inherits from Manager
324 const { result: superAdminRoles } = await rolesWorkflow.run({
325 input: {
326 roles: [
327 {
328 name: "SuperAdmin",
329 description: "Super admin with all access",
330 parent_ids: [managerRole.id],
331 policy_ids: [policies[2].id], // admin:system
332 },
333 ],
334 },
335 })
336 const superAdminRole = superAdminRoles[0]
337
338 // Verify SuperAdmin has all policies through parent chain
339 const superAdminPolicies = await rbacService.listPoliciesForRole(
340 superAdminRole.id
341 )
342
343 expect(superAdminPolicies).toHaveLength(3)
344 expect(superAdminPolicies.map((p) => p.key).sort()).toEqual([
345 "admin:system",
346 "read:catalog",
347 "write:catalog",
348 ])
349
350 // Verify Manager has policies from Basic + its own
351 const managerPolicies = await rbacService.listPoliciesForRole(
352 managerRole.id
353 )
354
355 expect(managerPolicies).toHaveLength(2)
356 expect(managerPolicies.map((p) => p.key).sort()).toEqual([
357 "read:catalog",
358 "write:catalog",
359 ])
360
361 // Verify Basic only has its own policy
362 const basicPolicies = await rbacService.listPoliciesForRole(
363 basicRole.id
364 )
365
366 expect(basicPolicies).toHaveLength(1)
367 expect(basicPolicies[0].key).toBe("read:catalog")
368 })
369
370 it("should propagate policy deletion from inherited role", async () => {
371 // Create policies
372 const policiesWorkflow = createRbacPoliciesWorkflow(appContainer)
373 const { result: policies } = await policiesWorkflow.run({
374 input: {
375 policies: [
376 {
377 key: "read:inventory",
378 resource: "inventory",
379 operation: "read",
380 name: "Read Inventory",
381 },
382 {
383 key: "write:inventory",
384 resource: "inventory",
385 operation: "write",
386 name: "Write Inventory",
387 },
388 {
389 key: "admin:inventory",
390 resource: "inventory",
391 operation: "admin",
392 name: "Admin Inventory",
393 },
394 ],
395 },
396 })
397
398 // Create role hierarchy: Basic -> Manager -> SuperAdmin
399 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
400
401 // Level 1: Basic role with read permission
402 const { result: basicRoles } = await rolesWorkflow.run({
403 input: {
404 roles: [
405 {
406 name: "Basic Inventory User",
407 description: "Basic inventory read access",
408 policy_ids: [policies[0].id], // read:inventory
409 },
410 ],
411 },
412 })
413 const basicRole = basicRoles[0]
414
415 // Level 2: Manager inherits from Basic + write permission
416 const { result: managerRoles } = await rolesWorkflow.run({
417 input: {
418 roles: [
419 {
420 name: "Inventory Manager",
421 description: "Manager with write access",
422 parent_ids: [basicRole.id],
423 policy_ids: [policies[1].id], // write:inventory
424 },
425 ],
426 },
427 })
428 const managerRole = managerRoles[0]
429
430 // Level 3: SuperAdmin inherits from Manager + admin permission
431 const { result: superAdminRoles } = await rolesWorkflow.run({
432 input: {
433 roles: [
434 {
435 name: "Inventory SuperAdmin",
436 description: "Super admin with all access",
437 parent_ids: [managerRole.id],
438 policy_ids: [policies[2].id], // admin:inventory
439 },
440 ],
441 },
442 })
443 const superAdminRole = superAdminRoles[0]
444
445 // Verify initial state: SuperAdmin has all 3 policies
446 let superAdminPolicies = await rbacService.listPoliciesForRole(
447 superAdminRole.id
448 )
449 expect(superAdminPolicies).toHaveLength(3)
450 expect(superAdminPolicies.map((p) => p.key).sort()).toEqual([
451 "admin:inventory",
452 "read:inventory",
453 "write:inventory",
454 ])
455
456 // Verify Manager has 2 policies (Basic's + its own)
457 let managerPolicies = await rbacService.listPoliciesForRole(
458 managerRole.id
459 )
460 expect(managerPolicies).toHaveLength(2)
461 expect(managerPolicies.map((p) => p.key).sort()).toEqual([
462 "read:inventory",
463 "write:inventory",
464 ])
465
466 // Delete the read:inventory policy from Basic role
467 const basicRolePolicies = await rbacService.listRbacRolePolicies({
468 role_id: basicRole.id,
469 })
470 const readPolicyAssociation = basicRolePolicies.find(
471 (rp) => rp.policy_id === policies[0].id
472 )
473 await rbacService.deleteRbacRolePolicies([readPolicyAssociation!.id])
474
475 // Verify Basic role no longer has the read policy
476 const basicPoliciesAfterDelete =
477 await rbacService.listPoliciesForRole(basicRole.id)
478 expect(basicPoliciesAfterDelete).toHaveLength(0)
479
480 // Verify Manager role no longer inherits the read policy
481 managerPolicies = await rbacService.listPoliciesForRole(
482 managerRole.id
483 )
484 expect(managerPolicies).toHaveLength(1)
485 expect(managerPolicies[0].key).toBe("write:inventory")
486
487 // Verify SuperAdmin role also lost the read policy through parent chain
488 superAdminPolicies = await rbacService.listPoliciesForRole(
489 superAdminRole.id
490 )
491 expect(superAdminPolicies).toHaveLength(2)
492 expect(superAdminPolicies.map((p) => p.key).sort()).toEqual([
493 "admin:inventory",
494 "write:inventory",
495 ])
496 })
497
498 it("should handle role with no inherited roles or policies", async () => {
499 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
500
501 const { result: emptyRoles } = await rolesWorkflow.run({
502 input: {
503 roles: [
504 {
505 name: "Empty Role",
506 description: "Role with no permissions",
507 },
508 ],
509 },
510 })
511
512 const emptyRole = emptyRoles[0]
513
514 // Verify no policies
515 const policies = await rbacService.listPoliciesForRole(emptyRole.id)
516 expect(policies).toHaveLength(0)
517
518 // Verify no parent
519 const parents = await rbacService.listRbacRoleParents({
520 role_id: emptyRole.id,
521 })
522 expect(parents).toHaveLength(0)
523 })
524 })
525
526 describe("Circular Dependency Prevention", () => {
527 it("should prevent creating a role parent relationship where role is its own parent", async () => {
528 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
529 const { result: roles } = await rolesWorkflow.run({
530 input: {
531 roles: [
532 {
533 name: "Test Role",
534 description: "Test role for self-reference check",
535 },
536 ],
537 },
538 })
539 const testRole = roles[0]
540
541 // Try to create a self-referencing parent relationship
542 await expect(
543 rbacService.createRbacRoleParents([
544 {
545 role_id: testRole.id,
546 parent_id: testRole.id,
547 },
548 ])
549 ).rejects.toThrow(/cannot be its own parent/)
550 })
551
552 it("should prevent creating a circular dependency (A -> B -> A)", async () => {
553 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
554 const { result: roles } = await rolesWorkflow.run({
555 input: {
556 roles: [
557 {
558 name: "Role A",
559 description: "First role",
560 },
561 {
562 name: "Role B",
563 description: "Second role",
564 },
565 ],
566 },
567 })
568 const roleA = roles[0]
569 const roleB = roles[1]
570
571 // Create A -> B (A inherits from B)
572 await rbacService.createRbacRoleParents([
573 {
574 role_id: roleA.id,
575 parent_id: roleB.id,
576 },
577 ])
578
579 // Try to create B -> A (would create a cycle)
580
581 let error: Error | undefined
582 try {
583 await rbacService.createRbacRoleParents([
584 {
585 role_id: roleB.id,
586 parent_id: roleA.id,
587 },
588 ])
589 } catch (e) {
590 error = e
591 }
592 expect(error).toBeDefined()
593 expect(error?.message).toContain("circular dependency")
594 })
595
596 it("should prevent creating a circular dependency (A -> B -> C -> A)", async () => {
597 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
598 const { result: roles } = await rolesWorkflow.run({
599 input: {
600 roles: [
601 {
602 name: "Role A",
603 description: "First role",
604 },
605 {
606 name: "Role B",
607 description: "Second role",
608 },
609 {
610 name: "Role C",
611 description: "Third role",
612 },
613 ],
614 },
615 })
616 const roleA = roles[0]
617 const roleB = roles[1]
618 const roleC = roles[2]
619
620 // Create A -> B (A inherits from B)
621 await rbacService.createRbacRoleParents([
622 {
623 role_id: roleA.id,
624 parent_id: roleB.id,
625 },
626 ])
627
628 // Create B -> C (B inherits from C)
629 await rbacService.createRbacRoleParents([
630 {
631 role_id: roleB.id,
632 parent_id: roleC.id,
633 },
634 ])
635
636 // Try to create C -> A (would create a cycle)
637 let error: Error | undefined
638 try {
639 await rbacService.createRbacRoleParents([
640 {
641 role_id: roleC.id,
642 parent_id: roleA.id,
643 },
644 ])
645 } catch (e) {
646 error = e
647 }
648 expect(error).toBeDefined()
649 expect(error?.message).toContain("circular dependency")
650 })
651
652 it("should prevent updating a role parent to create a circular dependency", async () => {
653 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
654 const { result: roles } = await rolesWorkflow.run({
655 input: {
656 roles: [
657 {
658 name: "Role X",
659 description: "First role",
660 },
661 {
662 name: "Role Y",
663 description: "Second role",
664 },
665 {
666 name: "Role Z",
667 description: "Third role",
668 },
669 ],
670 },
671 })
672 const roleX = roles[0]
673 const roleY = roles[1]
674 const roleZ = roles[2]
675
676 // Create X -> Y (X inherits from Y)
677 const [parentRelation] = await rbacService.createRbacRoleParents([
678 {
679 role_id: roleX.id,
680 parent_id: roleY.id,
681 },
682 ])
683
684 // Create Y -> Z (Y inherits from Z)
685 await rbacService.createRbacRoleParents([
686 {
687 role_id: roleY.id,
688 parent_id: roleZ.id,
689 },
690 ])
691
692 // Try to update X's parent to Z -> X (would create a cycle)
693 let error: Error | undefined
694 try {
695 await rbacService.updateRbacRoleParents([
696 {
697 id: parentRelation.id,
698 role_id: roleZ.id,
699 parent_id: roleX.id,
700 },
701 ])
702 } catch (e) {
703 error = e
704 }
705 expect(error).toBeDefined()
706 expect(error?.message).toContain("circular dependency")
707 })
708
709 it("should allow valid multi-level hierarchy without cycles", async () => {
710 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
711 const { result: roles } = await rolesWorkflow.run({
712 input: {
713 roles: [
714 {
715 name: "Junior",
716 description: "Junior role",
717 },
718 {
719 name: "Senior",
720 description: "Senior role",
721 },
722 {
723 name: "Lead",
724 description: "Lead role",
725 },
726 {
727 name: "Manager",
728 description: "Manager role",
729 },
730 ],
731 },
732 })
733 const junior = roles[0]
734 const senior = roles[1]
735 const lead = roles[2]
736 const manager = roles[3]
737
738 // Create valid hierarchy: Junior -> Senior -> Lead -> Manager
739 await rbacService.createRbacRoleParents([
740 {
741 role_id: junior.id,
742 parent_id: senior.id,
743 },
744 ])
745
746 await rbacService.createRbacRoleParents([
747 {
748 role_id: senior.id,
749 parent_id: lead.id,
750 },
751 ])
752
753 await rbacService.createRbacRoleParents([
754 {
755 role_id: lead.id,
756 parent_id: manager.id,
757 },
758 ])
759
760 // Verify the hierarchy was created successfully
761 const juniorParents = await rbacService.listRbacRoleParents({
762 role_id: junior.id,
763 })
764 expect(juniorParents).toHaveLength(1)
765 expect(juniorParents[0].parent_id).toBe(senior.id)
766
767 const seniorParents = await rbacService.listRbacRoleParents({
768 role_id: senior.id,
769 })
770 expect(seniorParents).toHaveLength(1)
771 expect(seniorParents[0].parent_id).toBe(lead.id)
772
773 const leadParents = await rbacService.listRbacRoleParents({
774 role_id: lead.id,
775 })
776 expect(leadParents).toHaveLength(1)
777 expect(leadParents[0].parent_id).toBe(manager.id)
778 })
779 })
780
781 describe("Permission Validation", () => {
782 it("should prevent user without roles from creating roles with policies", async () => {
783 const userModule = appContainer.resolve(Modules.USER)
784
785 // Create a user with no roles
786 const [user] = await userModule.createUsers([
787 {
788 email: "noroles@test.com",
789 first_name: "No",
790 last_name: "Roles",
791 },
792 ])
793
794 // Create a policy
795 const policiesWorkflow = createRbacPoliciesWorkflow(appContainer)
796 const { result: policies } = await policiesWorkflow.run({
797 input: {
798 policies: [
799 {
800 key: "read:test",
801 resource: "test",
802 operation: "read",
803 name: "Read Test",
804 },
805 ],
806 },
807 })
808
809 // Try to create a role with this policy as a user with no roles
810 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
811
812 let error: any
813 try {
814 await rolesWorkflow.run({
815 input: {
816 actor_id: user.id,
817 roles: [
818 {
819 name: "Test Role",
820 policy_ids: [policies[0].id],
821 },
822 ],
823 },
824 })
825 } catch (e) {
826 error = e
827 }
828
829 expect(error).toBeDefined()
830 expect(error.message).toContain("Forbidden")
831 })
832
833 it("should prevent user from assigning policies they don't have access to", async () => {
834 const userModule = appContainer.resolve(Modules.USER)
835 const remoteLink = appContainer.resolve(
836 ContainerRegistrationKeys.LINK
837 )
838
839 // Create policies
840 const policiesWorkflow = createRbacPoliciesWorkflow(appContainer)
841 const { result: policies } = await policiesWorkflow.run({
842 input: {
843 policies: [
844 {
845 key: "read:products",
846 resource: "product",
847 operation: "read",
848 name: "Read Products",
849 },
850 {
851 key: "write:products",
852 resource: "product",
853 operation: "write",
854 name: "Write Products",
855 },
856 {
857 key: "delete:products",
858 resource: "product",
859 operation: "delete",
860 name: "Delete Products",
861 },
862 ],
863 },
864 })
865
866 // Create a role with only read permission
867 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
868 const { result: limitedRoles } = await rolesWorkflow.run({
869 input: {
870 roles: [
871 {
872 name: "Limited Role",
873 policy_ids: [policies[0].id], // Only read:products
874 },
875 ],
876 },
877 })
878
879 // Create a user and assign the limited role
880 const [user] = await userModule.createUsers([
881 {
882 email: "limited@test.com",
883 first_name: "Limited",
884 last_name: "User",
885 },
886 ])
887
888 await remoteLink.create({
889 [Modules.USER]: {
890 user_id: user.id,
891 },
892 [Modules.RBAC]: {
893 rbac_role_id: limitedRoles[0].id,
894 },
895 })
896
897 // Try to create a role with write permission
898 let error: any
899 try {
900 await rolesWorkflow.run({
901 input: {
902 actor_id: user.id,
903 roles: [
904 {
905 name: "New Role",
906 policy_ids: [policies[1].id], // write:products - user doesn't have this
907 },
908 ],
909 },
910 })
911 } catch (e) {
912 error = e
913 }
914
915 expect(error).toBeDefined()
916 expect(error.message).toContain(
917 "You do not have access to some of the policies you are trying to assign."
918 )
919 })
920
921 it("should allow user to create roles with policies they have access to", async () => {
922 const userModule = appContainer.resolve(Modules.USER)
923 const remoteLink = appContainer.resolve(
924 ContainerRegistrationKeys.LINK
925 )
926
927 // Create policies
928 const policiesWorkflow = createRbacPoliciesWorkflow(appContainer)
929 const { result: policies } = await policiesWorkflow.run({
930 input: {
931 policies: [
932 {
933 key: "read:orders",
934 resource: "order",
935 operation: "read",
936 name: "Read Orders",
937 },
938 {
939 key: "write:orders",
940 resource: "order",
941 operation: "write",
942 name: "Write Orders",
943 },
944 ],
945 },
946 })
947
948 // Create an admin role with both permissions
949 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
950 const { result: adminRoles } = await rolesWorkflow.run({
951 input: {
952 roles: [
953 {
954 name: "Order Admin",
955 policy_ids: [policies[0].id, policies[1].id],
956 },
957 ],
958 },
959 })
960
961 // Create a user and assign the admin role
962 const [user] = await userModule.createUsers([
963 {
964 email: "admin@test.com",
965 first_name: "Admin",
966 last_name: "User",
967 },
968 ])
969
970 await remoteLink.create({
971 [Modules.USER]: {
972 user_id: user.id,
973 },
974 [Modules.RBAC]: {
975 rbac_role_id: adminRoles[0].id,
976 },
977 })
978
979 // User should be able to create a role with read permission (which they have)
980 const { result: newRoles } = await rolesWorkflow.run({
981 input: {
982 actor_id: user.id,
983 roles: [
984 {
985 name: "Order Viewer",
986 policy_ids: [policies[0].id], // read:orders - user has this
987 },
988 ],
989 },
990 })
991
992 expect(newRoles).toHaveLength(1)
993 expect(newRoles[0].name).toBe("Order Viewer")
994
995 // Verify the role was created with the correct policy
996 const newRolePolicies = await rbacService.listPoliciesForRole(
997 newRoles[0].id
998 )
999 expect(newRolePolicies).toHaveLength(1)
1000 expect(newRolePolicies[0].key).toBe("read:orders")
1001 })
1002
1003 it("should allow user with inherited permissions to create roles", async () => {
1004 const userModule = appContainer.resolve(Modules.USER)
1005 const remoteLink = appContainer.resolve(
1006 ContainerRegistrationKeys.LINK
1007 )
1008
1009 // Create policies
1010 const policiesWorkflow = createRbacPoliciesWorkflow(appContainer)
1011 const { result: policies } = await policiesWorkflow.run({
1012 input: {
1013 policies: [
1014 {
1015 key: "read:inventory",
1016 resource: "inventory",
1017 operation: "read",
1018 name: "Read Inventory",
1019 },
1020 {
1021 key: "write:inventory",
1022 resource: "inventory",
1023 operation: "write",
1024 name: "Write Inventory",
1025 },
1026 ],
1027 },
1028 })
1029
1030 // Create base role with read permission
1031 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
1032 const { result: baseRoles } = await rolesWorkflow.run({
1033 input: {
1034 roles: [
1035 {
1036 name: "Inventory Reader",
1037 policy_ids: [policies[0].id],
1038 },
1039 ],
1040 },
1041 })
1042
1043 // Create manager role that inherits from base + write permission
1044 const { result: managerRoles } = await rolesWorkflow.run({
1045 input: {
1046 roles: [
1047 {
1048 name: "Inventory Manager",
1049 parent_ids: [baseRoles[0].id],
1050 policy_ids: [policies[1].id],
1051 },
1052 ],
1053 },
1054 })
1055
1056 // Create a user and assign the manager role
1057 const [user] = await userModule.createUsers([
1058 {
1059 email: "manager@test.com",
1060 first_name: "Manager",
1061 last_name: "User",
1062 },
1063 ])
1064
1065 await remoteLink.create({
1066 [Modules.USER]: {
1067 user_id: user.id,
1068 },
1069 [Modules.RBAC]: {
1070 rbac_role_id: managerRoles[0].id,
1071 },
1072 })
1073
1074 // User should be able to create a role with read permission (inherited)
1075 const { result: newRoles } = await rolesWorkflow.run({
1076 input: {
1077 actor_id: user.id,
1078 roles: [
1079 {
1080 name: "New Reader",
1081 policy_ids: [policies[0].id], // read - user has via parent
1082 },
1083 ],
1084 },
1085 })
1086
1087 expect(newRoles).toHaveLength(1)
1088 expect(newRoles[0].name).toBe("New Reader")
1089 })
1090 })
1091
1092 describe("Policy Registration and Synchronization", () => {
1093 beforeEach(() => {
1094 // Clear global policy registries before each test
1095 clearPolicies()
1096 })
1097
1098 it("should register policies using definePolicies", () => {
1099 // Register policies
1100 definePolicies([
1101 {
1102 name: "ReadBrand",
1103 resource: "brand",
1104 operation: "read",
1105 description: "Read brand data",
1106 },
1107 {
1108 name: "WriteBrand",
1109 resource: "brand",
1110 operation: "write",
1111 description: "Write brand data",
1112 },
1113 {
1114 name: "ReadCategory",
1115 resource: "category",
1116 operation: "read",
1117 description: "Read category data",
1118 },
1119 ])
1120
1121 // Verify Policy object contains named policies
1122 expect(Object.keys(Policy).length).toBe(3)
1123 expect(Policy["ReadBrand"]).toEqual({
1124 resource: "brand",
1125 name: "ReadBrand",
1126 operation: "read",
1127 description: "Read brand data",
1128 })
1129 expect(Policy["WriteBrand"]).toEqual({
1130 resource: "brand",
1131 name: "WriteBrand",
1132 operation: "write",
1133 description: "Write brand data",
1134 })
1135 expect(Policy["ReadCategory"]).toEqual({
1136 resource: "category",
1137 name: "ReadCategory",
1138 operation: "read",
1139 description: "Read category data",
1140 })
1141 })
1142
1143 it("should sync registered policies to database on application start", async () => {
1144 // Register policies
1145 definePolicies([
1146 {
1147 name: "ReadProduct",
1148 resource: "product",
1149 operation: "read",
1150 },
1151 {
1152 name: "WriteProduct",
1153 resource: "product",
1154 operation: "write",
1155 },
1156 {
1157 name: "DeleteProduct",
1158 resource: "product",
1159 operation: "delete",
1160 },
1161 ])
1162
1163 // Trigger sync by calling onApplicationStart
1164 await rbacService.__hooks?.onApplicationStart?.()
1165
1166 // Verify policies were created in database
1167 const policies = await rbacService.listRbacPolicies({
1168 key: ["product:read", "product:write", "product:delete"],
1169 })
1170
1171 expect(policies).toHaveLength(3)
1172
1173 const policyMap = new Map(policies.map((p) => [p.key, p]))
1174 expect(policyMap.get("product:read")).toMatchObject({
1175 name: "ReadProduct",
1176 resource: "product",
1177 operation: "read",
1178 })
1179 expect(policyMap.get("product:write")).toMatchObject({
1180 name: "WriteProduct",
1181 resource: "product",
1182 operation: "write",
1183 })
1184 expect(policyMap.get("product:delete")).toMatchObject({
1185 name: "DeleteProduct",
1186 resource: "product",
1187 operation: "delete",
1188 })
1189 })
1190
1191 it("should soft delete policies that are no longer registered", async () => {
1192 // First sync: Register 3 policies
1193 definePolicies([
1194 {
1195 name: "ReadOrder",
1196 resource: "order",
1197 operation: "read",
1198 },
1199 {
1200 name: "WriteOrder",
1201 resource: "order",
1202 operation: "write",
1203 },
1204 {
1205 name: "DeleteOrder",
1206 resource: "order",
1207 operation: "delete",
1208 },
1209 ])
1210
1211 await rbacService.__hooks?.onApplicationStart?.()
1212
1213 let policies = await rbacService.listRbacPolicies({
1214 key: ["order:read", "order:write", "order:delete"],
1215 })
1216 expect(policies).toHaveLength(3)
1217
1218 // Second sync: Remove one policy from code
1219
1220 clearPolicies()
1221 definePolicies([
1222 {
1223 name: "ReadOrder",
1224 resource: "order",
1225 operation: "read",
1226 },
1227 {
1228 name: "WriteOrder",
1229 resource: "order",
1230 operation: "write",
1231 },
1232 ])
1233
1234 await rbacService.__hooks?.onApplicationStart?.()
1235
1236 // Verify the removed policy is soft-deleted
1237 policies = await rbacService.listRbacPolicies({
1238 key: ["order:read", "order:write", "order:delete"],
1239 })
1240 expect(policies).toHaveLength(2) // Only active policies
1241
1242 // Verify soft-deleted policy exists with deleted_at
1243 const allPolicies = await rbacService.listRbacPolicies(
1244 { key: "order:delete" },
1245 { withDeleted: true }
1246 )
1247 expect(allPolicies).toHaveLength(1)
1248 expect(allPolicies[0].deleted_at).toBeTruthy()
1249 })
1250
1251 it("should restore soft-deleted policies when they are re-registered", async () => {
1252 // First sync: Register policies
1253 definePolicies([
1254 {
1255 name: "ReadCustomer",
1256 resource: "customer",
1257 operation: "read",
1258 },
1259 {
1260 name: "WriteCustomer",
1261 resource: "customer",
1262 operation: "write",
1263 },
1264 ])
1265
1266 await rbacService.__hooks?.onApplicationStart?.()
1267
1268 let policies = await rbacService.listRbacPolicies({
1269 resource: "customer",
1270 })
1271 expect(policies).toHaveLength(2)
1272 const originalWritePolicy = policies.find(
1273 (p) => p.operation === "write"
1274 )
1275
1276 // Second sync: Remove WriteCustomer
1277 clearPolicies()
1278
1279 definePolicies({
1280 name: "ReadCustomer",
1281 resource: "customer",
1282 operation: "read",
1283 })
1284
1285 await rbacService.__hooks?.onApplicationStart?.()
1286
1287 policies = await rbacService.listRbacPolicies({
1288 resource: "customer",
1289 })
1290 expect(policies).toHaveLength(1)
1291
1292 // Third sync: Re-add WriteCustomer
1293 clearPolicies()
1294
1295 definePolicies([
1296 {
1297 name: "ReadCustomer",
1298 resource: "customer",
1299 operation: "read",
1300 },
1301 {
1302 name: "WriteCustomer",
1303 resource: "customer",
1304 operation: "write",
1305 },
1306 ])
1307
1308 await rbacService.__hooks?.onApplicationStart?.()
1309
1310 // Verify policy was restored (same ID)
1311 policies = await rbacService.listRbacPolicies({
1312 resource: "customer",
1313 })
1314 expect(policies).toHaveLength(2)
1315
1316 const restoredWritePolicy = policies.find(
1317 (p) => p.operation === "write"
1318 )
1319 expect(restoredWritePolicy!.id).toBe(originalWritePolicy!.id)
1320 expect(restoredWritePolicy!.deleted_at).toBeNull()
1321 })
1322
1323 it("should update policy name if it changes in code", async () => {
1324 // First sync: Register with original name
1325 definePolicies({
1326 name: "ReadInventory",
1327 resource: "inventory",
1328 operation: "read",
1329 })
1330
1331 await rbacService.__hooks?.onApplicationStart?.()
1332
1333 let policies = await rbacService.listRbacPolicies({
1334 key: "inventory:read",
1335 })
1336 expect(policies).toHaveLength(1)
1337 expect(policies[0].name).toBe("ReadInventory")
1338 const policyId = policies[0].id
1339
1340 // Second sync: Change the name
1341 clearPolicies()
1342
1343 definePolicies({
1344 name: "ViewInventory",
1345 resource: "inventory",
1346 operation: "read",
1347 })
1348
1349 await rbacService.__hooks?.onApplicationStart?.()
1350
1351 // Verify name was updated but ID remains the same
1352 policies = await rbacService.listRbacPolicies({
1353 key: "inventory:read",
1354 })
1355 expect(policies).toHaveLength(1)
1356 expect(policies[0].id).toBe(policyId)
1357 expect(policies[0].name).toBe("ViewInventory")
1358 })
1359
1360 it("should preserve role associations when policy is soft-deleted and restored", async () => {
1361 // Register and sync policies
1362 definePolicies([
1363 {
1364 name: "ReadStore",
1365 resource: "store",
1366 operation: "read",
1367 },
1368 {
1369 name: "WriteStore",
1370 resource: "store",
1371 operation: "write",
1372 },
1373 ])
1374
1375 await rbacService.__hooks?.onApplicationStart?.()
1376
1377 const policies = await rbacService.listRbacPolicies({
1378 resource: "store",
1379 })
1380 expect(policies).toHaveLength(2)
1381
1382 // Create a role with these policies
1383 const rolesWorkflow = createRbacRolesWorkflow(appContainer)
1384 const { result: roles } = await rolesWorkflow.run({
1385 input: {
1386 roles: [
1387 {
1388 name: "Store Manager",
1389 policy_ids: policies.map((p) => p.id),
1390 },
1391 ],
1392 },
1393 })
1394
1395 const storeManagerRole = roles[0]
1396
1397 // Verify role has both policies
1398 let roleWithPolicies = await rbacService.listRbacRoles(
1399 { id: storeManagerRole.id },
1400 { relations: ["policies"] }
1401 )
1402 expect(roleWithPolicies[0].policies).toHaveLength(2)
1403
1404 // Soft delete WriteStore policy
1405 clearPolicies()
1406
1407 definePolicies({
1408 name: "ReadStore",
1409 resource: "store",
1410 operation: "read",
1411 })
1412
1413 await rbacService.__hooks?.onApplicationStart?.()
1414
1415 // Role should now have only 1 active policy
1416 roleWithPolicies = await rbacService.listRbacRoles(
1417 { id: storeManagerRole.id },
1418 { relations: ["policies"] }
1419 )
1420 expect(roleWithPolicies[0].policies).toHaveLength(1)
1421
1422 // Restore WriteStore policy
1423 clearPolicies()
1424
1425 definePolicies([
1426 {
1427 name: "ReadStore",
1428 resource: "store",
1429 operation: "read",
1430 },
1431 {
1432 name: "WriteStore",
1433 resource: "store",
1434 operation: "write",
1435 },
1436 ])
1437
1438 await rbacService.__hooks?.onApplicationStart?.()
1439
1440 // Role should have both policies again (association preserved)
1441 roleWithPolicies = await rbacService.listRbacRoles(
1442 { id: storeManagerRole.id },
1443 { relations: ["policies"] }
1444 )
1445 expect(roleWithPolicies[0].policies).toHaveLength(2)
1446 })
1447 })
1448 })
1449 },
1450 })