1 import {
2 assignUserRolesWorkflow,
3 createRbacRolesWorkflow,
4 createUsersWorkflow,
5 getAssignableRolesWorkflow,
6 removeUserRolesWorkflow,
7 updateRbacRolesWorkflow,
8 } from "@medusajs/core-flows"
9 import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
10 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
11 import {
12 adminHeaders,
13 createAdminUser,
14 } from "../../../../helpers/create-admin-user"
15
16 jest.setTimeout(60000)
17
18 process.env.MEDUSA_FF_RBAC = "true"
19
20 const ensureRbacPolicy = async (
21 rbacModule,
22 params: {
23 key: string
24 resource: string
25 operation: string
26 name: string
27 description?: string
28 }
29 ) => {
30 const [existing] = await rbacModule.listRbacPolicies({
31 key: params.key,
32 })
33
34 if (existing) {
35 return existing
36 }
37
38 const [created] = await rbacModule.createRbacPolicies([params])
39 return created
40 }
41
42 medusaIntegrationTestRunner({
43 testSuite: ({ dbConnection, api, getContainer, dbUtils }) => {
44 let container
45
46 beforeAll(async () => {
47 container = getContainer()
48 await createAdminUser(dbConnection, adminHeaders, container)
49
50 await dbUtils.snapshot()
51 })
52
53 afterAll(async () => {
54 delete process.env.MEDUSA_FF_RBAC
55 })
56
57 describe("RBAC Roles - Admin API", () => {
58 describe("POST /admin/rbac/roles", () => {
59 it("should create a role", async () => {
60 const response = await api.post(
61 "/admin/rbac/roles",
62 {
63 name: "Viewer",
64 description: "Can view resources",
65 },
66 adminHeaders
67 )
68
69 expect(response.status).toEqual(200)
70 expect(response.data.role).toEqual(
71 expect.objectContaining({
72 id: expect.any(String),
73 name: "Viewer",
74 description: "Can view resources",
75 })
76 )
77 })
78
79 it("should create a role with metadata", async () => {
80 const response = await api.post(
81 "/admin/rbac/roles",
82 {
83 name: "Editor",
84 description: "Can edit resources",
85 metadata: { department: "sales" },
86 },
87 adminHeaders
88 )
89
90 expect(response.status).toEqual(200)
91 expect(response.data.role).toEqual(
92 expect.objectContaining({
93 name: "Editor",
94 metadata: { department: "sales" },
95 })
96 )
97 })
98
99 it("creates a role with attached policies in a single request", async () => {
100 // Seed two concrete policies for super-admin to attach.
101 const rbacModule = container.resolve(Modules.RBAC)
102 const readPolicy = await ensureRbacPolicy(rbacModule, {
103 key: "product:read",
104 resource: "product",
105 operation: "read",
106 name: "Read Products",
107 })
108 const createPolicy = await ensureRbacPolicy(rbacModule, {
109 key: "product:create",
110 resource: "product",
111 operation: "create",
112 name: "Create Products",
113 })
114
115 const response = await api.post(
116 "/admin/rbac/roles",
117 {
118 name: "Product Editor",
119 description: "Read and create products",
120 policy_ids: [readPolicy.id, createPolicy.id],
121 },
122 adminHeaders
123 )
124
125 expect(response.status).toEqual(200)
126 expect(response.data.role).toEqual(
127 expect.objectContaining({
128 id: expect.any(String),
129 name: "Product Editor",
130 })
131 )
132
133 // The role-policy join rows should exist
134 const rolePolicies = await rbacModule.listRbacRolePolicies({
135 role_id: response.data.role.id,
136 })
137 expect(rolePolicies.map((rp) => rp.policy_id)).toEqual(
138 expect.arrayContaining([readPolicy.id, createPolicy.id])
139 )
140 expect(rolePolicies).toHaveLength(2)
141 })
142
143 it("rejects creating a role with policies the actor doesn't hold", async () => {
144 // Build a scoped actor whose only grant is product:read, then try
145 // to create a role bundling product:read + customer:create.
146 const rbacModule = container.resolve(Modules.RBAC)
147
148 const productRead = await ensureRbacPolicy(rbacModule, {
149 key: "product:read",
150 resource: "product",
151 operation: "read",
152 name: "Read Products",
153 })
154 const customerCreate = await ensureRbacPolicy(rbacModule, {
155 key: "customer:create",
156 resource: "customer",
157 operation: "create",
158 name: "Create Customers",
159 })
160
161 const scopedRole = await rbacModule.createRbacRoles({
162 name: "Product Reader Only",
163 })
164 await rbacModule.createRbacRolePolicies([
165 { role_id: scopedRole.id, policy_id: productRead.id },
166 ])
167
168 const scopedActorHeaders = { headers: { ...adminHeaders.headers } }
169 await createAdminUser(dbConnection, scopedActorHeaders, container, {
170 email: "product-reader-only@medusa.js",
171 roles: [scopedRole.id],
172 })
173
174 const error = await api
175 .post(
176 "/admin/rbac/roles",
177 {
178 name: "Cannot Create",
179 policy_ids: [productRead.id, customerCreate.id],
180 },
181 scopedActorHeaders
182 )
183 .catch((e) => e)
184
185 expect(error.response.status).toEqual(403)
186 expect(error.response.data.message).toContain(
187 "You do not have access to some of the policies you are trying to assign."
188 )
189
190 // No role should have been persisted
191 const created = await rbacModule.listRbacRoles({
192 name: "Cannot Create",
193 })
194 expect(created).toHaveLength(0)
195 })
196 })
197
198 describe("GET /admin/rbac/roles", () => {
199 beforeEach(async () => {
200 await api.post(
201 "/admin/rbac/roles",
202 {
203 name: "Viewer",
204 description: "Can view resources",
205 },
206 adminHeaders
207 )
208
209 await api.post(
210 "/admin/rbac/roles",
211 {
212 name: "Editor",
213 description: "Can edit resources",
214 },
215 adminHeaders
216 )
217
218 await api.post(
219 "/admin/rbac/roles",
220 {
221 name: "Admin",
222 description: "Full access",
223 },
224 adminHeaders
225 )
226 })
227
228 it("should list all roles", async () => {
229 const response = await api.get("/admin/rbac/roles", adminHeaders)
230
231 expect(response.status).toEqual(200)
232 // 4 roles: Super Admin + 3 created in beforeEach
233 expect(response.data.count).toEqual(4)
234 expect(response.data.roles).toEqual(
235 expect.arrayContaining([
236 expect.objectContaining({
237 id: "role_super_admin",
238 name: "Super Admin",
239 }),
240 expect.objectContaining({
241 name: "Viewer",
242 description: "Can view resources",
243 }),
244 expect.objectContaining({
245 name: "Editor",
246 description: "Can edit resources",
247 }),
248 expect.objectContaining({
249 name: "Admin",
250 description: "Full access",
251 }),
252 ])
253 )
254 })
255
256 it("should filter roles by name", async () => {
257 const response = await api.get(
258 "/admin/rbac/roles?name=Viewer",
259 adminHeaders
260 )
261
262 expect(response.status).toEqual(200)
263 expect(response.data.count).toEqual(1)
264 expect(response.data.roles[0]).toEqual(
265 expect.objectContaining({
266 name: "Viewer",
267 })
268 )
269 })
270 })
271
272 describe("GET /admin/rbac/roles/:id", () => {
273 it("should retrieve a role by id", async () => {
274 const createResponse = await api.post(
275 "/admin/rbac/roles",
276 {
277 name: "Manager",
278 description: "Can manage resources",
279 },
280 adminHeaders
281 )
282
283 const roleId = createResponse.data.role.id
284
285 const response = await api.get(
286 `/admin/rbac/roles/${roleId}`,
287 adminHeaders
288 )
289
290 expect(response.status).toEqual(200)
291 expect(response.data.role).toEqual(
292 expect.objectContaining({
293 id: roleId,
294 name: "Manager",
295 description: "Can manage resources",
296 })
297 )
298 })
299 })
300
301 describe("POST /admin/rbac/roles/:id", () => {
302 it("should update a role", async () => {
303 const createResponse = await api.post(
304 "/admin/rbac/roles",
305 {
306 name: "Support",
307 description: "Support team",
308 },
309 adminHeaders
310 )
311
312 const roleId = createResponse.data.role.id
313
314 const response = await api.post(
315 `/admin/rbac/roles/${roleId}`,
316 {
317 name: "Customer Support",
318 description: "Customer support team with limited access",
319 },
320 adminHeaders
321 )
322
323 expect(response.status).toEqual(200)
324 expect(response.data.role).toEqual(
325 expect.objectContaining({
326 id: roleId,
327 name: "Customer Support",
328 description: "Customer support team with limited access",
329 })
330 )
331 })
332 })
333
334 describe("DELETE /admin/rbac/roles/:id", () => {
335 it("should delete a role", async () => {
336 const createResponse = await api.post(
337 "/admin/rbac/roles",
338 {
339 name: "Temporary",
340 description: "Temporary role",
341 },
342 adminHeaders
343 )
344
345 const roleId = createResponse.data.role.id
346
347 const deleteResponse = await api.delete(
348 `/admin/rbac/roles/${roleId}`,
349 adminHeaders
350 )
351
352 expect(deleteResponse.status).toEqual(200)
353 expect(deleteResponse.data).toEqual({
354 id: roleId,
355 object: "rbac_role",
356 deleted: true,
357 })
358
359 const listResponse = await api.get("/admin/rbac/roles", adminHeaders)
360 expect(
361 listResponse.data.roles.find((r) => r.id === roleId)
362 ).toBeUndefined()
363 })
364 })
365
366 describe("Role Policies", () => {
367 let policies
368 let viewerRole
369 let editorRole
370 let adminUser
371
372 beforeEach(async () => {
373 const userModule = container.resolve(Modules.USER)
374 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
375
376 // Create policies
377 const policy1 = await api.post(
378 "/admin/rbac/policies",
379 {
380 key: "read:products",
381 resource: "product",
382 operation: "read",
383 name: "Read Products",
384 },
385 adminHeaders
386 )
387
388 const policy2 = await api.post(
389 "/admin/rbac/policies",
390 {
391 key: "write:products",
392 resource: "product",
393 operation: "write",
394 name: "Write Products",
395 },
396 adminHeaders
397 )
398
399 const policy3 = await api.post(
400 "/admin/rbac/policies",
401 {
402 key: "delete:products",
403 resource: "product",
404 operation: "delete",
405 name: "Delete Products",
406 },
407 adminHeaders
408 )
409
410 policies = [
411 policy1.data.policy,
412 policy2.data.policy,
413 policy3.data.policy,
414 ]
415
416 // Create an admin role with all policies
417 const adminRoleResponse = await api.post(
418 "/admin/rbac/roles",
419 {
420 name: "Admin Role",
421 description: "Has all permissions",
422 },
423 adminHeaders
424 )
425 const adminRole = adminRoleResponse.data.role
426
427 // Associate all policies with the admin role using the module directly
428 const rbacModule = container.resolve(Modules.RBAC)
429 await rbacModule.createRbacRolePolicies([
430 { role_id: adminRole.id, policy_id: policies[0].id },
431 { role_id: adminRole.id, policy_id: policies[1].id },
432 { role_id: adminRole.id, policy_id: policies[2].id },
433 ])
434
435 // Get the admin user
436 const users = await userModule.listUsers({ email: "admin@medusa.js" })
437 adminUser = users[0]
438
439 // Link the admin user to the admin role
440 await remoteLink.create({
441 [Modules.USER]: {
442 user_id: adminUser.id,
443 },
444 [Modules.RBAC]: {
445 rbac_role_id: adminRole.id,
446 },
447 })
448
449 // Create viewer and editor roles for the tests
450 const viewer = await api.post(
451 "/admin/rbac/roles",
452 {
453 name: "Product Viewer",
454 description: "Can view products",
455 },
456 adminHeaders
457 )
458 viewerRole = viewer.data.role
459
460 const editor = await api.post(
461 "/admin/rbac/roles",
462 {
463 name: "Product Editor",
464 description: "Can edit products",
465 },
466 adminHeaders
467 )
468 editorRole = editor.data.role
469 })
470
471 it("should create a user with roles using workflow", async () => {
472 // Create a user with roles using the workflow
473 const { result } = await createUsersWorkflow(container).run({
474 input: {
475 users: [
476 {
477 email: "test-user@example.com",
478 first_name: "Test",
479 last_name: "User",
480 roles: [viewerRole.id, editorRole.id],
481 },
482 ],
483 },
484 })
485
486 expect(result).toHaveLength(1)
487 const createdUser = result[0]
488 expect(createdUser.email).toEqual("test-user@example.com")
489 expect(createdUser.first_name).toEqual("Test")
490 expect(createdUser.last_name).toEqual("User")
491
492 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
493 const linkService = remoteLink.getLinkModule(
494 Modules.USER,
495 "user_id",
496 Modules.RBAC,
497 "rbac_role_id"
498 )
499
500 const userRoles = await linkService.list({
501 user_id: createdUser.id,
502 })
503
504 expect(userRoles).toHaveLength(2)
505 expect(userRoles.map((link) => link.rbac_role_id)).toEqual(
506 expect.arrayContaining([viewerRole.id, editorRole.id])
507 )
508
509 const userModule = container.resolve(Modules.USER)
510 const retrievedUser = await userModule.retrieveUser(createdUser.id)
511 expect(retrievedUser.email).toEqual("test-user@example.com")
512 })
513
514 it("should add policies to a role", async () => {
515 const response = await api.post(
516 `/admin/rbac/roles/${viewerRole.id}/policies`,
517 {
518 policies: [policies[0].id],
519 },
520 adminHeaders
521 )
522
523 expect(response.status).toEqual(200)
524
525 expect(response.data.policies).toHaveLength(1)
526 expect(response.data.policies[0]).toMatchObject({
527 role_id: viewerRole.id,
528 policy_id: policies[0].id,
529 })
530 })
531
532 it("should list role-policies for a specific role", async () => {
533 // Add multiple policies to the role
534 await api.post(
535 `/admin/rbac/roles/${viewerRole.id}/policies`,
536 {
537 policies: [policies[0].id, policies[1].id],
538 },
539 adminHeaders
540 )
541
542 // List the role to get its policies
543 const response = await api.get(
544 `/admin/rbac/roles/${viewerRole.id}/?fields=policies`,
545 adminHeaders
546 )
547
548 expect(response.status).toEqual(200)
549 expect(Array.isArray(response.data.role.policies)).toBe(true)
550 expect(response.data.role.policies).toHaveLength(2)
551 expect(response.data.role.policies).toEqual(
552 expect.arrayContaining([
553 expect.objectContaining({
554 id: policies[0].id,
555 }),
556 expect.objectContaining({
557 id: policies[1].id,
558 }),
559 ])
560 )
561 })
562
563 it("should remove a policy from a role", async () => {
564 // First add a policy to the role
565 await api.post(
566 `/admin/rbac/roles/${editorRole.id}/policies`,
567 {
568 policies: [policies[2].id],
569 },
570 adminHeaders
571 )
572
573 // Verify the policy was added
574 const initialResponse = await api.get(
575 `/admin/rbac/roles/${editorRole.id}?fields=policies`,
576 adminHeaders
577 )
578 expect(initialResponse.data.role.policies).toHaveLength(1)
579
580 // Remove the policy from the role
581 const deleteResponse = await api.delete(
582 `/admin/rbac/roles/${editorRole.id}/policies/${policies[2].id}`,
583 adminHeaders
584 )
585
586 expect(deleteResponse.status).toEqual(200)
587 expect(deleteResponse.data).toEqual({
588 id: expect.stringContaining("rlpl_"),
589 object: "rbac_role_policy",
590 deleted: true,
591 })
592
593 // Verify the policy was removed
594 const finalResponse = await api.get(
595 `/admin/rbac/roles/${editorRole.id}?fields=policies`,
596 adminHeaders
597 )
598 expect(finalResponse.data.role.policies).toHaveLength(0)
599 })
600 })
601
602 describe("Role Policies - Wildcard Permissions", () => {
603 const productManagerHeaders = { headers: { ...adminHeaders.headers } }
604 const universalReaderHeaders = { headers: { ...adminHeaders.headers } }
605 const productReaderHeaders = { headers: { ...adminHeaders.headers } }
606 const noPolicyHeaders = { headers: { ...adminHeaders.headers } }
607
608 let productReadPolicyId: string
609 let productCreatePolicyId: string
610 let productUpdatePolicyId: string
611 let customerReadPolicyId: string
612 let customerCreatePolicyId: string
613
614 let emptyTargetRoleId: string
615
616 beforeEach(async () => {
617 const rbacModule = container.resolve(Modules.RBAC)
618
619 const productRead = await ensureRbacPolicy(rbacModule, {
620 key: "product:read",
621 resource: "product",
622 operation: "read",
623 name: "Read Products",
624 })
625 const productCreate = await ensureRbacPolicy(rbacModule, {
626 key: "product:create",
627 resource: "product",
628 operation: "create",
629 name: "Create Products",
630 })
631 const productUpdate = await ensureRbacPolicy(rbacModule, {
632 key: "product:update",
633 resource: "product",
634 operation: "update",
635 name: "Update Products",
636 })
637 const customerRead = await ensureRbacPolicy(rbacModule, {
638 key: "customer:read",
639 resource: "customer",
640 operation: "read",
641 name: "Read Customers",
642 })
643 const customerCreate = await ensureRbacPolicy(rbacModule, {
644 key: "customer:create",
645 resource: "customer",
646 operation: "create",
647 name: "Create Customers",
648 })
649 const productWildcard = await ensureRbacPolicy(rbacModule, {
650 key: "product:*",
651 resource: "product",
652 operation: "*",
653 name: "Manage Products",
654 })
655 const universalRead = await ensureRbacPolicy(rbacModule, {
656 key: "*:read",
657 resource: "*",
658 operation: "read",
659 name: "Read Anything",
660 })
661 const rbacRoleUpdate = await ensureRbacPolicy(rbacModule, {
662 key: "rbac_role:update",
663 resource: "rbac_role",
664 operation: "update",
665 name: "Update Roles",
666 })
667
668 productReadPolicyId = productRead.id
669 productCreatePolicyId = productCreate.id
670 productUpdatePolicyId = productUpdate.id
671 customerReadPolicyId = customerRead.id
672 customerCreatePolicyId = customerCreate.id
673
674 const productManagerRole = await rbacModule.createRbacRoles({
675 name: "Product Manager",
676 description: "Holds product:* wildcard",
677 })
678 const universalReaderRole = await rbacModule.createRbacRoles({
679 name: "Universal Reader",
680 description: "Holds *:read wildcard",
681 })
682 const productReaderRole = await rbacModule.createRbacRoles({
683 name: "Product Reader",
684 description: "Holds only product:read",
685 })
686 const noPolicyRole = await rbacModule.createRbacRoles({
687 name: "No Grants Role",
688 description: "Only rbac_role:update; no other grants",
689 })
690
691 await rbacModule.createRbacRolePolicies([
692 { role_id: productManagerRole.id, policy_id: productWildcard.id },
693 { role_id: productManagerRole.id, policy_id: rbacRoleUpdate.id },
694 { role_id: universalReaderRole.id, policy_id: universalRead.id },
695 { role_id: universalReaderRole.id, policy_id: rbacRoleUpdate.id },
696 {
697 role_id: productReaderRole.id,
698 policy_id: productReadPolicyId,
699 },
700 { role_id: productReaderRole.id, policy_id: rbacRoleUpdate.id },
701 { role_id: noPolicyRole.id, policy_id: rbacRoleUpdate.id },
702 ])
703
704 await createAdminUser(
705 dbConnection,
706 productManagerHeaders,
707 container,
708 {
709 email: "product-manager@medusa.js",
710 roles: [productManagerRole.id],
711 }
712 )
713 await createAdminUser(
714 dbConnection,
715 universalReaderHeaders,
716 container,
717 {
718 email: "universal-reader@medusa.js",
719 roles: [universalReaderRole.id],
720 }
721 )
722 await createAdminUser(dbConnection, productReaderHeaders, container, {
723 email: "product-reader@medusa.js",
724 roles: [productReaderRole.id],
725 })
726 await createAdminUser(dbConnection, noPolicyHeaders, container, {
727 email: "no-policy@medusa.js",
728 roles: [noPolicyRole.id],
729 })
730
731 // Empty role used as the grant target in each scenario.
732 const emptyTargetRole = await rbacModule.createRbacRoles({
733 name: "Grant Target",
734 description: "Role used as the target for grant attempts",
735 })
736 emptyTargetRoleId = emptyTargetRole.id
737 })
738
739 describe("POST /admin/rbac/roles/:id/policies", () => {
740 it("allows super-admin (`*:*`) to grant any policy", async () => {
741 const response = await api.post(
742 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
743 {
744 policies: [
745 productReadPolicyId,
746 productCreatePolicyId,
747 customerReadPolicyId,
748 ],
749 },
750 adminHeaders
751 )
752
753 expect(response.status).toEqual(200)
754 expect(response.data.policies).toHaveLength(3)
755 })
756
757 it("allows `resource:*` holder to grant any operation on that resource", async () => {
758 const response = await api.post(
759 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
760 {
761 policies: [
762 productReadPolicyId,
763 productCreatePolicyId,
764 productUpdatePolicyId,
765 ],
766 },
767 productManagerHeaders
768 )
769
770 expect(response.status).toEqual(200)
771 expect(response.data.policies).toHaveLength(3)
772 })
773
774 it("denies `resource:*` holder when granting a different resource", async () => {
775 const error = await api
776 .post(
777 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
778 { policies: [customerReadPolicyId] },
779 productManagerHeaders
780 )
781 .catch((e) => e)
782
783 expect(error.response.status).toEqual(403)
784 expect(error.response.data).toMatchObject({
785 type: "forbidden",
786 message:
787 "You do not have access to some of the policies you are trying to assign.",
788 })
789 })
790
791 it("allows `*:op` holder to grant that operation on any resource", async () => {
792 const response = await api.post(
793 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
794 {
795 policies: [productReadPolicyId, customerReadPolicyId],
796 },
797 universalReaderHeaders
798 )
799
800 expect(response.status).toEqual(200)
801 expect(response.data.policies).toHaveLength(2)
802 })
803
804 it("denies `*:op` holder when granting a different operation", async () => {
805 const error = await api
806 .post(
807 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
808 { policies: [customerCreatePolicyId] },
809 universalReaderHeaders
810 )
811 .catch((e) => e)
812
813 expect(error.response.status).toEqual(403)
814 })
815
816 it("allows exact `resource:op` holder to grant that policy", async () => {
817 const response = await api.post(
818 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
819 { policies: [productReadPolicyId] },
820 productReaderHeaders
821 )
822
823 expect(response.status).toEqual(200)
824 expect(response.data.policies).toHaveLength(1)
825 })
826
827 it("denies exact-match holder when granting any other policy", async () => {
828 const error = await api
829 .post(
830 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
831 {
832 policies: [productReadPolicyId, productCreatePolicyId],
833 },
834 productReaderHeaders
835 )
836 .catch((e) => e)
837
838 expect(error.response.status).toEqual(403)
839 })
840
841 it("denies a user whose only policy does not cover the grant target", async () => {
842 const error = await api
843 .post(
844 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
845 { policies: [productReadPolicyId] },
846 noPolicyHeaders
847 )
848 .catch((e) => e)
849
850 expect(error.response.status).toEqual(403)
851 })
852
853 it("returns 404 when granting a non-existent policy id", async () => {
854 const error = await api
855 .post(
856 `/admin/rbac/roles/${emptyTargetRoleId}/policies`,
857 { policies: ["rpol_does_not_exist"] },
858 adminHeaders
859 )
860 .catch((e) => e)
861
862 expect(error.response.status).toEqual(404)
863 expect(error.response.data.message).toContain(
864 "do not exist: rpol_does_not_exist"
865 )
866 })
867 })
868
869 describe("workflows", () => {
870 it("createRbacRolesWorkflow: super-admin can create a role with any policy_ids", async () => {
871 const userModule = container.resolve(Modules.USER)
872 const [superAdminUser] = await userModule.listUsers({
873 email: "admin@medusa.js",
874 })
875
876 const { result } = await createRbacRolesWorkflow(container).run({
877 input: {
878 actor_id: superAdminUser.id,
879 actor: "user",
880 roles: [
881 {
882 name: "Mixed Bag",
883 policy_ids: [productReadPolicyId, customerCreatePolicyId],
884 },
885 ],
886 },
887 })
888
889 expect(result).toHaveLength(1)
890
891 const rolePolicies = await container
892 .resolve(Modules.RBAC)
893 .listRbacRolePolicies({ role_id: result[0].id })
894 expect(rolePolicies).toHaveLength(2)
895 })
896
897 it("createRbacRolesWorkflow: rejects when actor lacks a policy in the set", async () => {
898 const userModule = container.resolve(Modules.USER)
899 const [productReader] = await userModule.listUsers({
900 email: "product-reader@medusa.js",
901 })
902
903 const error = await createRbacRolesWorkflow(container)
904 .run({
905 input: {
906 actor_id: productReader.id,
907 actor: "user",
908 roles: [
909 {
910 name: "Would Be Forbidden",
911 policy_ids: [productReadPolicyId, customerReadPolicyId],
912 },
913 ],
914 },
915 })
916 .catch((e) => e)
917
918 expect(error.message).toContain(
919 "You do not have access to some of the policies you are trying to assign."
920 )
921 })
922
923 it("updateRbacRolesWorkflow: super-admin can update a role's policies", async () => {
924 const userModule = container.resolve(Modules.USER)
925 const [superAdminUser] = await userModule.listUsers({
926 email: "admin@medusa.js",
927 })
928
929 const { result } = await updateRbacRolesWorkflow(container).run({
930 input: {
931 actor_id: superAdminUser.id,
932 actor: "user",
933 selector: { id: emptyTargetRoleId },
934 update: {
935 policy_ids: [productCreatePolicyId, customerReadPolicyId],
936 },
937 },
938 })
939
940 expect(result).toHaveLength(1)
941 expect(result[0].id).toEqual(emptyTargetRoleId)
942
943 const rolePolicies = await container
944 .resolve(Modules.RBAC)
945 .listRbacRolePolicies({ role_id: emptyTargetRoleId })
946 expect(rolePolicies.map((rp) => rp.policy_id)).toEqual(
947 expect.arrayContaining([
948 productCreatePolicyId,
949 customerReadPolicyId,
950 ])
951 )
952 })
953
954 it("authorizes a scoped holder when policy_ids fall under their wildcard", async () => {
955 const userModule = container.resolve(Modules.USER)
956 const [productManager] = await userModule.listUsers({
957 email: "product-manager@medusa.js",
958 })
959
960 const { result } = await createRbacRolesWorkflow(container)
961 .run({
962 input: {
963 actor_id: productManager.id,
964 actor: "user",
965 roles: [
966 {
967 name: "Product Editor",
968 policy_ids: [productUpdatePolicyId],
969 },
970 ],
971 },
972 })
973 .catch((e) => e)
974
975 expect(result).toHaveLength(1)
976 })
977 })
978
979 describe("assignUserRolesWorkflow / removeUserRolesWorkflow", () => {
980 // A role-with-policies fixture used as the target of assign/remove
981 // operations. Built once per test from the shared policy IDs.
982 let productReadRoleId: string
983 let mixedRoleId: string
984 let assigneeUserId: string
985
986 beforeEach(async () => {
987 const rbacModule = container.resolve(Modules.RBAC)
988 const userModule = container.resolve(Modules.USER)
989
990 const productReadRole = await rbacModule.createRbacRoles({
991 name: "Assignable - Product Read",
992 })
993 const mixedRole = await rbacModule.createRbacRoles({
994 name: "Assignable - Mixed",
995 })
996
997 await rbacModule.createRbacRolePolicies([
998 {
999 role_id: productReadRole.id,
1000 policy_id: productReadPolicyId,
1001 },
1002 { role_id: mixedRole.id, policy_id: productReadPolicyId },
1003 { role_id: mixedRole.id, policy_id: customerCreatePolicyId },
1004 ])
1005
1006 productReadRoleId = productReadRole.id
1007 mixedRoleId = mixedRole.id
1008
1009 const assignee = await userModule.createUsers({
1010 email: "assignee@medusa.js",
1011 first_name: "Assignee",
1012 last_name: "User",
1013 })
1014 assigneeUserId = assignee.id
1015 })
1016
1017 it("super-admin (`*:*`) can assign a role with policies to a user", async () => {
1018 const userModule = container.resolve(Modules.USER)
1019 const [superAdminUser] = await userModule.listUsers({
1020 email: "admin@medusa.js",
1021 })
1022
1023 const { result } = await assignUserRolesWorkflow(container).run({
1024 input: {
1025 actor_id: superAdminUser.id,
1026 actor: "user",
1027 user_id: assigneeUserId,
1028 role_ids: [mixedRoleId],
1029 },
1030 })
1031
1032 expect(result).toBeUndefined()
1033 })
1034
1035 it("`resource:*` holder can assign a role whose policies fall under that resource", async () => {
1036 // product-manager holds product:* and can assign a role whose only
1037 // policy is product:read.
1038 const userModule = container.resolve(Modules.USER)
1039 const [productManager] = await userModule.listUsers({
1040 email: "product-manager@medusa.js",
1041 })
1042
1043 const { result } = await assignUserRolesWorkflow(container).run({
1044 input: {
1045 actor_id: productManager.id,
1046 actor: "user",
1047 user_id: assigneeUserId,
1048 role_ids: [productReadRoleId],
1049 },
1050 })
1051
1052 expect(result).toBeUndefined()
1053 })
1054
1055 it("denies a scoped holder when the role contains policies outside their grant", async () => {
1056 // product-manager holds product:* but the mixed role also has
1057 // customer:create, so the assignment must be rejected.
1058 const userModule = container.resolve(Modules.USER)
1059 const [productManager] = await userModule.listUsers({
1060 email: "product-manager@medusa.js",
1061 })
1062
1063 const error = await assignUserRolesWorkflow(container)
1064 .run({
1065 input: {
1066 actor_id: productManager.id,
1067 actor: "user",
1068 user_id: assigneeUserId,
1069 role_ids: [mixedRoleId],
1070 },
1071 })
1072 .catch((e) => e)
1073
1074 expect(error.message).toContain(
1075 "You do not have permission to assign these roles"
1076 )
1077 })
1078
1079 it("denies an actor with no roles", async () => {
1080 const userModule = container.resolve(Modules.USER)
1081 const stray = await userModule.createUsers({
1082 email: "stray@medusa.js",
1083 first_name: "Stray",
1084 last_name: "User",
1085 })
1086
1087 const error = await assignUserRolesWorkflow(container)
1088 .run({
1089 input: {
1090 actor_id: stray.id,
1091 actor: "user",
1092 user_id: assigneeUserId,
1093 role_ids: [productReadRoleId],
1094 },
1095 })
1096 .catch((e) => e)
1097
1098 expect(error.message).toContain(
1099 "You do not have permission to assign these roles"
1100 )
1101 })
1102
1103 it("removeUserRolesWorkflow: super-admin can remove a role with policies", async () => {
1104 const userModule = container.resolve(Modules.USER)
1105 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
1106 const [superAdminUser] = await userModule.listUsers({
1107 email: "admin@medusa.js",
1108 })
1109
1110 await remoteLink.create({
1111 [Modules.USER]: { user_id: assigneeUserId },
1112 [Modules.RBAC]: { rbac_role_id: mixedRoleId },
1113 })
1114
1115 const { result } = await removeUserRolesWorkflow(container).run({
1116 input: {
1117 actor_id: superAdminUser.id,
1118 actor: "user",
1119 user_id: assigneeUserId,
1120 role_ids: [mixedRoleId],
1121 },
1122 })
1123
1124 expect(result).toBeUndefined()
1125 })
1126 })
1127 })
1128
1129 describe("GET /admin/rbac/roles/assignable", () => {
1130 // Headers for actors with varying levels of permission coverage.
1131 // `adminHeaders` is the super-admin baseline (holds `*:*`).
1132 const productManagerHeaders = { headers: { ...adminHeaders.headers } }
1133 const universalReaderHeaders = { headers: { ...adminHeaders.headers } }
1134 const productReaderHeaders = { headers: { ...adminHeaders.headers } }
1135 const noRolesUserHeaders = { headers: { ...adminHeaders.headers } }
1136
1137 // Role IDs created in setup, used to assert which subset each actor
1138 // can assign. Names describe the policy composition of each target.
1139 let productOnlyRoleId: string
1140 let crossResourceRoleId: string
1141 let universalReadRoleId: string
1142 let emptyRoleId: string
1143 let superAdminLikeRoleId: string
1144
1145 beforeEach(async () => {
1146 const rbacModule = container.resolve(Modules.RBAC)
1147
1148 // Look up an existing policy by key, or create it if absent
1149 const ensurePolicy = async (params: {
1150 key: string
1151 resource: string
1152 operation: string
1153 name: string
1154 }) => {
1155 const [existing] = await rbacModule.listRbacPolicies({
1156 key: params.key,
1157 })
1158 if (existing) {
1159 return existing
1160 }
1161 const [created] = await rbacModule.createRbacPolicies([params])
1162 return created
1163 }
1164
1165 // Concrete policies — the universe of `resource:operation` tuples
1166 // that wildcard grants expand against in `hasPermission`.
1167 const productRead = await ensurePolicy({
1168 key: "product:read",
1169 resource: "product",
1170 operation: "read",
1171 name: "Read Products",
1172 })
1173 const productCreate = await ensurePolicy({
1174 key: "product:create",
1175 resource: "product",
1176 operation: "create",
1177 name: "Create Products",
1178 })
1179 const customerRead = await ensurePolicy({
1180 key: "customer:read",
1181 resource: "customer",
1182 operation: "read",
1183 name: "Read Customers",
1184 })
1185 const customerCreate = await ensurePolicy({
1186 key: "customer:create",
1187 resource: "customer",
1188 operation: "create",
1189 name: "Create Customers",
1190 })
1191
1192 // Wildcard grants attached to actor roles (drive the wildcard
1193 // expansion code path in `hasPermission`).
1194 const productWildcard = await ensurePolicy({
1195 key: "product:*",
1196 resource: "product",
1197 operation: "*",
1198 name: "Manage Products",
1199 })
1200 const universalRead = await ensurePolicy({
1201 key: "*:read",
1202 resource: "*",
1203 operation: "read",
1204 name: "Read Anything",
1205 })
1206 const fullWildcard = await ensurePolicy({
1207 key: "*:*",
1208 resource: "*",
1209 operation: "*",
1210 name: "Everything",
1211 })
1212
1213 // The route is gated by `rbac_role:read` — every non-super-admin
1214 // actor below also holds it so they reach the workflow.
1215 const rbacRoleRead = await ensurePolicy({
1216 key: "rbac_role:read",
1217 resource: "rbac_role",
1218 operation: "read",
1219 name: "Read Roles",
1220 })
1221
1222 // --- Actor roles (held by users we drive requests with) ---
1223 const productManagerRole = await rbacModule.createRbacRoles({
1224 name: "Assignable Suite — Product Manager (actor)",
1225 })
1226 const universalReaderRole = await rbacModule.createRbacRoles({
1227 name: "Assignable Suite — Universal Reader (actor)",
1228 })
1229 const productReaderRole = await rbacModule.createRbacRoles({
1230 name: "Assignable Suite — Product Reader (actor)",
1231 })
1232
1233 await rbacModule.createRbacRolePolicies([
1234 { role_id: productManagerRole.id, policy_id: productWildcard.id },
1235 { role_id: productManagerRole.id, policy_id: rbacRoleRead.id },
1236 { role_id: universalReaderRole.id, policy_id: universalRead.id },
1237 { role_id: universalReaderRole.id, policy_id: rbacRoleRead.id },
1238 { role_id: productReaderRole.id, policy_id: productRead.id },
1239 { role_id: productReaderRole.id, policy_id: rbacRoleRead.id },
1240 ])
1241
1242 // --- Target roles (the candidates the endpoint is asked about) ---
1243 // (1) Needs only product:read + product:create → covered by product:*
1244 const productOnly = await rbacModule.createRbacRoles({
1245 name: "Assignable Suite — Target Product Only",
1246 })
1247 productOnlyRoleId = productOnly.id
1248 await rbacModule.createRbacRolePolicies([
1249 { role_id: productOnly.id, policy_id: productRead.id },
1250 { role_id: productOnly.id, policy_id: productCreate.id },
1251 ])
1252
1253 // (2) Needs customer:create — NOT covered by product:* nor by *:read
1254 const crossResource = await rbacModule.createRbacRoles({
1255 name: "Assignable Suite — Target Cross Resource",
1256 })
1257 crossResourceRoleId = crossResource.id
1258 await rbacModule.createRbacRolePolicies([
1259 { role_id: crossResource.id, policy_id: productRead.id },
1260 { role_id: crossResource.id, policy_id: customerCreate.id },
1261 ])
1262
1263 // (3) Needs read on multiple resources — covered by *:read
1264 universalReadRoleId = (
1265 await rbacModule.createRbacRoles({
1266 name: "Assignable Suite — Target Universal Read",
1267 })
1268 ).id
1269 await rbacModule.createRbacRolePolicies([
1270 { role_id: universalReadRoleId, policy_id: productRead.id },
1271 { role_id: universalReadRoleId, policy_id: customerRead.id },
1272 ])
1273
1274 // (4) Empty policy set — assignable by any actor with at least one role.
1275 const empty = await rbacModule.createRbacRoles({
1276 name: "Assignable Suite — Target Empty",
1277 })
1278 emptyRoleId = empty.id
1279
1280 // (5) Holds `*:*` — only an actor that also holds `*:*` can cover it.
1281 const superAdminLike = await rbacModule.createRbacRoles({
1282 name: "Assignable Suite — Target Super-Admin Like",
1283 })
1284 superAdminLikeRoleId = superAdminLike.id
1285 await rbacModule.createRbacRolePolicies([
1286 { role_id: superAdminLike.id, policy_id: fullWildcard.id },
1287 ])
1288
1289 // --- Users holding the actor roles ---
1290 await createAdminUser(
1291 dbConnection,
1292 productManagerHeaders,
1293 container,
1294 {
1295 email: "assignable-product-manager@medusa.js",
1296 roles: [productManagerRole.id],
1297 }
1298 )
1299 await createAdminUser(
1300 dbConnection,
1301 universalReaderHeaders,
1302 container,
1303 {
1304 email: "assignable-universal-reader@medusa.js",
1305 roles: [universalReaderRole.id],
1306 }
1307 )
1308 await createAdminUser(dbConnection, productReaderHeaders, container, {
1309 email: "assignable-product-reader@medusa.js",
1310 roles: [productReaderRole.id],
1311 })
1312 // Actor with no roles linked at all. This actor would still
1313 // fail the route's `rbac_role:read` gate, but for the endpoint's
1314 // semantic test we use the super-admin headers to invoke it on
1315 // their behalf when needed (see test below).
1316 await createAdminUser(dbConnection, noRolesUserHeaders, container, {
1317 email: "assignable-no-roles@medusa.js",
1318 roles: [],
1319 })
1320 })
1321
1322 it("returns response shape `{ roles, count }` with count matching roles.length", async () => {
1323 const response = await api.get(
1324 "/admin/rbac/roles/assignable",
1325 adminHeaders
1326 )
1327
1328 expect(response.status).toEqual(200)
1329 expect(response.data).toMatchObject({
1330 roles: expect.any(Array),
1331 count: expect.any(Number),
1332 })
1333 expect(response.data.count).toEqual(response.data.roles.length)
1334 })
1335
1336 it("returns every target role for a super-admin (`*:*`)", async () => {
1337 const response = await api.get(
1338 "/admin/rbac/roles/assignable",
1339 adminHeaders
1340 )
1341
1342 const ids = response.data.roles.map((r: { id: string }) => r.id)
1343 // Super-admin covers every action, so every target role is assignable.
1344 expect(ids).toEqual(
1345 expect.arrayContaining([
1346 productOnlyRoleId,
1347 crossResourceRoleId,
1348 universalReadRoleId,
1349 emptyRoleId,
1350 superAdminLikeRoleId,
1351 ])
1352 )
1353 })
1354
1355 it("returns role projection of `{ id, name, description }` without policies leakage", async () => {
1356 const response = await api.get(
1357 "/admin/rbac/roles/assignable",
1358 adminHeaders
1359 )
1360
1361 for (const role of response.data.roles) {
1362 expect(typeof role.id).toEqual("string")
1363 expect(typeof role.name).toEqual("string")
1364 expect(
1365 role.description === null || typeof role.description === "string"
1366 ).toEqual(true)
1367 expect(role).not.toHaveProperty("policies")
1368 }
1369 })
1370
1371 it("expands `resource:*` — product:* actor sees product-only roles, not cross-resource", async () => {
1372 const response = await api.get(
1373 "/admin/rbac/roles/assignable",
1374 productManagerHeaders
1375 )
1376
1377 const ids = response.data.roles.map((r: { id: string }) => r.id)
1378 expect(ids).toContain(productOnlyRoleId)
1379 expect(ids).toContain(emptyRoleId)
1380 expect(ids).not.toContain(crossResourceRoleId)
1381 expect(ids).not.toContain(universalReadRoleId)
1382 expect(ids).not.toContain(superAdminLikeRoleId)
1383 })
1384
1385 it("expands `*:op` — *:read actor sees read-only roles across resources", async () => {
1386 const response = await api.get(
1387 "/admin/rbac/roles/assignable",
1388 universalReaderHeaders
1389 )
1390
1391 const ids = response.data.roles.map((r: { id: string }) => r.id)
1392 expect(ids).toContain(universalReadRoleId)
1393 expect(ids).toContain(emptyRoleId)
1394 // product:create + customer:create fall outside `*:read`.
1395 expect(ids).not.toContain(productOnlyRoleId)
1396 expect(ids).not.toContain(crossResourceRoleId)
1397 expect(ids).not.toContain(superAdminLikeRoleId)
1398 })
1399
1400 it("requires literal coverage — actor with product:read alone only covers empty targets", async () => {
1401 const response = await api.get(
1402 "/admin/rbac/roles/assignable",
1403 productReaderHeaders
1404 )
1405
1406 const ids = response.data.roles.map((r: { id: string }) => r.id)
1407 expect(ids).toContain(emptyRoleId)
1408 // Even productOnlyRoleId is out — it bundles product:read AND
1409 // product:create; product:read alone doesn't cover create.
1410 expect(ids).not.toContain(productOnlyRoleId)
1411 expect(ids).not.toContain(crossResourceRoleId)
1412 expect(ids).not.toContain(universalReadRoleId)
1413 expect(ids).not.toContain(superAdminLikeRoleId)
1414 })
1415
1416 it("returns empty roles via the workflow when the actor holds no roles", async () => {
1417 // The no-roles user can't pass the route's `rbac_role:read` gate,
1418 // so we exercise the empty-actor branch by running the workflow
1419 // directly with their id.
1420 const userModule = container.resolve(Modules.USER)
1421 const [noRolesUser] = await userModule.listUsers({
1422 email: "assignable-no-roles@medusa.js",
1423 })
1424
1425 const { result } = await getAssignableRolesWorkflow(container).run({
1426 input: {
1427 actor_id: noRolesUser.id,
1428 actor: "user",
1429 },
1430 })
1431
1432 expect(result.roles).toEqual([])
1433 expect(result.count).toEqual(0)
1434 })
1435
1436 it("treats roles with no policies as assignable by anyone with roles", async () => {
1437 // hasPermission on an empty actions list returns true, so an empty
1438 // target role passes for every actor that holds at least one role.
1439 const responses = await Promise.all([
1440 api.get("/admin/rbac/roles/assignable", productManagerHeaders),
1441 api.get("/admin/rbac/roles/assignable", universalReaderHeaders),
1442 api.get("/admin/rbac/roles/assignable", productReaderHeaders),
1443 ])
1444
1445 for (const response of responses) {
1446 const ids = response.data.roles.map((r: { id: string }) => r.id)
1447 expect(ids).toContain(emptyRoleId)
1448 }
1449 })
1450
1451 it("only a `*:*` holder can assign a role whose policies include `*:*`", async () => {
1452 // Super-admin holds *:* → can assign superAdminLikeRoleId.
1453 const superAdminResponse = await api.get(
1454 "/admin/rbac/roles/assignable",
1455 adminHeaders
1456 )
1457 const superAdminIds = superAdminResponse.data.roles.map(
1458 (r: { id: string }) => r.id
1459 )
1460 expect(superAdminIds).toContain(superAdminLikeRoleId)
1461
1462 // Every other actor (product:*, *:read, product:read) cannot.
1463 const otherResponses = await Promise.all([
1464 api.get("/admin/rbac/roles/assignable", productManagerHeaders),
1465 api.get("/admin/rbac/roles/assignable", universalReaderHeaders),
1466 api.get("/admin/rbac/roles/assignable", productReaderHeaders),
1467 ])
1468 for (const response of otherResponses) {
1469 const ids = response.data.roles.map((r: { id: string }) => r.id)
1470 expect(ids).not.toContain(superAdminLikeRoleId)
1471 }
1472 })
1473
1474 it("aggregates grants across multiple actor roles before checking coverage", async () => {
1475 // Actor holds product:read via one role and customer:create via
1476 // another. Neither covers crossResourceRoleId alone — together they
1477 // do. Pins the actor-roles union behavior to the response.
1478 const rbacModule = container.resolve(Modules.RBAC)
1479
1480 const [productReadPolicy] = await rbacModule.listRbacPolicies({
1481 key: "product:read",
1482 })
1483 const [customerCreatePolicy] = await rbacModule.listRbacPolicies({
1484 key: "customer:create",
1485 })
1486 const [rbacRoleReadPolicy] = await rbacModule.listRbacPolicies({
1487 key: "rbac_role:read",
1488 })
1489
1490 const roleA = await rbacModule.createRbacRoles({
1491 name: "Assignable Suite — Multi-role A",
1492 })
1493 const roleB = await rbacModule.createRbacRoles({
1494 name: "Assignable Suite — Multi-role B",
1495 })
1496 await rbacModule.createRbacRolePolicies([
1497 { role_id: roleA.id, policy_id: productReadPolicy.id },
1498 { role_id: roleA.id, policy_id: rbacRoleReadPolicy.id },
1499 { role_id: roleB.id, policy_id: customerCreatePolicy.id },
1500 ])
1501
1502 const multiRoleHeaders = { headers: { ...adminHeaders.headers } }
1503 await createAdminUser(dbConnection, multiRoleHeaders, container, {
1504 email: "assignable-multi-role@medusa.js",
1505 roles: [roleA.id, roleB.id],
1506 })
1507
1508 const response = await api.get(
1509 "/admin/rbac/roles/assignable",
1510 multiRoleHeaders
1511 )
1512
1513 const ids = response.data.roles.map((r: { id: string }) => r.id)
1514 expect(ids).toContain(crossResourceRoleId)
1515 })
1516
1517 it("applies the `id` filter when forwarded", async () => {
1518 // Verifies the route forwards `req.filterableFields` into the
1519 // workflow so candidate narrowing happens before per-role coverage.
1520 const response = await api.get(
1521 `/admin/rbac/roles/assignable?id=${emptyRoleId}`,
1522 adminHeaders
1523 )
1524
1525 const ids = response.data.roles.map((r: { id: string }) => r.id)
1526 expect(ids).toEqual([emptyRoleId])
1527 expect(response.data.count).toEqual(1)
1528 })
1529 })
1530
1531 describe("GET /admin/rbac/roles/:id/users", () => {
1532 let testRole
1533 let testUser1
1534 let testUser2
1535
1536 beforeEach(async () => {
1537 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
1538
1539 // Create a role for testing
1540 const roleResponse = await api.post(
1541 "/admin/rbac/roles",
1542 {
1543 name: "Test Role",
1544 description: "Role for testing users endpoint",
1545 },
1546 adminHeaders
1547 )
1548 testRole = roleResponse.data.role
1549
1550 // Create test users using the workflow
1551 const { result: users } = await createUsersWorkflow(container).run({
1552 input: {
1553 users: [
1554 {
1555 email: "user1@example.com",
1556 first_name: "User",
1557 last_name: "One",
1558 },
1559 {
1560 email: "user2@example.com",
1561 first_name: "User",
1562 last_name: "Two",
1563 },
1564 ],
1565 },
1566 })
1567
1568 testUser1 = users[0]
1569 testUser2 = users[1]
1570
1571 // Link users to the role
1572 await remoteLink.create([
1573 {
1574 [Modules.USER]: { user_id: testUser1.id },
1575 [Modules.RBAC]: { rbac_role_id: testRole.id },
1576 },
1577 {
1578 [Modules.USER]: { user_id: testUser2.id },
1579 [Modules.RBAC]: { rbac_role_id: testRole.id },
1580 },
1581 ])
1582 })
1583
1584 it("should list users for a role", async () => {
1585 const response = await api.get(
1586 `/admin/rbac/roles/${testRole.id}/users`,
1587 adminHeaders
1588 )
1589
1590 expect(response.status).toEqual(200)
1591 expect(response.data.count).toEqual(2)
1592 expect(response.data.users).toHaveLength(2)
1593 expect(response.data.users).toEqual(
1594 expect.arrayContaining([
1595 expect.objectContaining({
1596 id: testUser1.id,
1597 email: "user1@example.com",
1598 }),
1599 expect.objectContaining({
1600 id: testUser2.id,
1601 email: "user2@example.com",
1602 }),
1603 ])
1604 )
1605 })
1606
1607 it("should filter users by user_id", async () => {
1608 const response = await api.get(
1609 `/admin/rbac/roles/${testRole.id}/users?user_id=${testUser1.id}`,
1610 adminHeaders
1611 )
1612
1613 expect(response.status).toEqual(200)
1614 expect(response.data.count).toEqual(1)
1615 expect(response.data.users).toHaveLength(1)
1616 expect(response.data.users[0]).toEqual(
1617 expect.objectContaining({
1618 id: testUser1.id,
1619 email: "user1@example.com",
1620 })
1621 )
1622 })
1623
1624 it("should filter users by multiple user_ids", async () => {
1625 const response = await api.get(
1626 `/admin/rbac/roles/${testRole.id}/users?user_id[]=${testUser1.id}&user_id[]=${testUser2.id}`,
1627 adminHeaders
1628 )
1629
1630 expect(response.status).toEqual(200)
1631 expect(response.data.count).toEqual(2)
1632 expect(response.data.users).toHaveLength(2)
1633 })
1634
1635 it("should paginate users", async () => {
1636 const response = await api.get(
1637 `/admin/rbac/roles/${testRole.id}/users?limit=1&offset=0`,
1638 adminHeaders
1639 )
1640
1641 expect(response.status).toEqual(200)
1642 expect(response.data.count).toEqual(2)
1643 expect(response.data.users).toHaveLength(1)
1644 expect(response.data.limit).toEqual(1)
1645 expect(response.data.offset).toEqual(0)
1646 })
1647
1648 it("should return empty array for role with no users", async () => {
1649 const emptyRoleResponse = await api.post(
1650 "/admin/rbac/roles",
1651 {
1652 name: "Empty Role",
1653 description: "Role with no users",
1654 },
1655 adminHeaders
1656 )
1657 const emptyRole = emptyRoleResponse.data.role
1658
1659 const response = await api.get(
1660 `/admin/rbac/roles/${emptyRole.id}/users`,
1661 adminHeaders
1662 )
1663
1664 expect(response.status).toEqual(200)
1665 expect(response.data.count).toEqual(0)
1666 expect(response.data.users).toHaveLength(0)
1667 })
1668 })
1669
1670 describe("POST /admin/rbac/roles/:id/users", () => {
1671 it("should assign multiple users to a role", async () => {
1672 const userModule = container.resolve(Modules.USER)
1673
1674 // Create test users
1675 const testUser1 = await userModule.createUsers({
1676 email: "testuser1@example.com",
1677 first_name: "Test",
1678 last_name: "User1",
1679 })
1680 const testUser2 = await userModule.createUsers({
1681 email: "testuser2@example.com",
1682 first_name: "Test",
1683 last_name: "User2",
1684 })
1685
1686 // Create a role
1687 const roleResponse = await api.post(
1688 "/admin/rbac/roles",
1689 {
1690 name: "Batch Test Role",
1691 description: "Role for batch user assignment",
1692 },
1693 adminHeaders
1694 )
1695 const testRole = roleResponse.data.role
1696
1697 // Assign multiple users to the role
1698 const response = await api.post(
1699 `/admin/rbac/roles/${testRole.id}/users`,
1700 { users: [testUser1.id, testUser2.id] },
1701 adminHeaders
1702 )
1703
1704 expect(response.status).toEqual(200)
1705 expect(response.data.users).toHaveLength(2)
1706 expect(response.data.users).toEqual(
1707 expect.arrayContaining([
1708 expect.objectContaining({ id: testUser1.id }),
1709 expect.objectContaining({ id: testUser2.id }),
1710 ])
1711 )
1712
1713 // Verify users were assigned
1714 const verifyResponse = await api.get(
1715 `/admin/rbac/roles/${testRole.id}/users`,
1716 adminHeaders
1717 )
1718 expect(verifyResponse.data.count).toEqual(2)
1719 })
1720
1721 it("should return 404 for non-existent role", async () => {
1722 const error = await api
1723 .post(
1724 `/admin/rbac/roles/non_existent_id/users`,
1725 { users: ["user_123"] },
1726 adminHeaders
1727 )
1728 .catch((e) => e)
1729
1730 expect(error.response.status).toEqual(404)
1731 })
1732 })
1733
1734 describe("DELETE /admin/rbac/roles/:id/users", () => {
1735 it("should remove multiple users from a role", async () => {
1736 const userModule = container.resolve(Modules.USER)
1737 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
1738
1739 // Create test users
1740 const testUser1 = await userModule.createUsers({
1741 email: "removeuser1@example.com",
1742 first_name: "Remove",
1743 last_name: "User1",
1744 })
1745 const testUser2 = await userModule.createUsers({
1746 email: "removeuser2@example.com",
1747 first_name: "Remove",
1748 last_name: "User2",
1749 })
1750
1751 // Create a role
1752 const roleResponse = await api.post(
1753 "/admin/rbac/roles",
1754 {
1755 name: "Batch Remove Test Role",
1756 description: "Role for batch user removal",
1757 },
1758 adminHeaders
1759 )
1760 const testRole = roleResponse.data.role
1761
1762 // Assign users to the role
1763 await remoteLink.create([
1764 {
1765 [Modules.USER]: { user_id: testUser1.id },
1766 [Modules.RBAC]: { rbac_role_id: testRole.id },
1767 },
1768 {
1769 [Modules.USER]: { user_id: testUser2.id },
1770 [Modules.RBAC]: { rbac_role_id: testRole.id },
1771 },
1772 ])
1773
1774 // Verify users were assigned
1775 const beforeResponse = await api.get(
1776 `/admin/rbac/roles/${testRole.id}/users`,
1777 adminHeaders
1778 )
1779 expect(beforeResponse.data.count).toEqual(2)
1780
1781 // Remove multiple users from the role
1782 const deleteResponse = await api.delete(
1783 `/admin/rbac/roles/${testRole.id}/users`,
1784 {
1785 ...adminHeaders,
1786 data: { users: [testUser1.id, testUser2.id] },
1787 }
1788 )
1789
1790 expect(deleteResponse.status).toEqual(200)
1791 expect(deleteResponse.data).toEqual({
1792 ids: [testUser1.id, testUser2.id],
1793 object: "role_user",
1794 deleted: true,
1795 })
1796
1797 // Verify users were removed
1798 const afterResponse = await api.get(
1799 `/admin/rbac/roles/${testRole.id}/users`,
1800 adminHeaders
1801 )
1802 expect(afterResponse.data.count).toEqual(0)
1803 })
1804
1805 it("should return 404 for non-existent role", async () => {
1806 const error = await api
1807 .delete(`/admin/rbac/roles/non_existent_id/users`, {
1808 ...adminHeaders,
1809 data: { users: ["user_123"] },
1810 })
1811 .catch((e) => e)
1812
1813 expect(error.response.status).toEqual(404)
1814 })
1815 })
1816 })
1817 },
1818 })