1 import { createUsersWorkflow } from "@medusajs/core-flows"
2 import { IWorkflowEngineService } from "@medusajs/framework/types"
3 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
4 import { IAuthModuleService } from "@medusajs/types"
5 import {
6 ContainerRegistrationKeys,
7 generateJwtToken,
8 Modules,
9 } from "@medusajs/utils"
10 import {
11 adminHeaders,
12 createAdminUser,
13 } from "../../../../helpers/create-admin-user"
14
15 jest.setTimeout(30000)
16
17 process.env.MEDUSA_FF_RBAC = "true"
18
19 medusaIntegrationTestRunner({
20 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
21 let user, container, authIdentity
22
23 beforeAll(async () => {
24 container = getContainer()
25 const { user: adminUser, authIdentity: authId } = await createAdminUser(
26 dbConnection,
27 adminHeaders,
28 container
29 )
30
31 user = adminUser
32 authIdentity = authId
33
34 await dbUtils.snapshot()
35 })
36
37 describe("GET /admin/users/:id", () => {
38 it("should return user by id", async () => {
39 const response = await api.get(`/admin/users/${user.id}`, adminHeaders)
40
41 const v2Response = {
42 id: user.id,
43 email: "admin@medusa.js",
44 created_at: expect.any(String),
45 updated_at: expect.any(String),
46 }
47
48 // BREAKING: V2 users do not have role + api_token
49 expect(response.status).toEqual(200)
50 expect(response.data.user).toEqual(expect.objectContaining(v2Response))
51 })
52 })
53
54 describe("GET /admin/users", () => {
55 it("should list users", async () => {
56 const response = await api.get("/admin/users", adminHeaders)
57
58 expect(response.status).toEqual(200)
59
60 const v2Response = [
61 expect.objectContaining({
62 id: user.id,
63 email: "admin@medusa.js",
64 created_at: expect.any(String),
65 updated_at: expect.any(String),
66 }),
67 ]
68
69 expect(response.data.users).toEqual(v2Response)
70 })
71
72 it("should list users that match the free text search", async () => {
73 const emptyResponse = await api.get(
74 "/admin/users?q=member",
75 adminHeaders
76 )
77
78 expect(emptyResponse.status).toEqual(200)
79 expect(emptyResponse.data.users.length).toEqual(0)
80
81 const response = await api.get("/admin/users?q=user", adminHeaders)
82
83 expect(response.data.users.length).toEqual(1)
84 expect(response.data.users).toEqual([
85 expect.objectContaining({
86 id: user.id,
87 email: "admin@medusa.js",
88 created_at: expect.any(String),
89 updated_at: expect.any(String),
90 }),
91 ])
92 })
93 })
94
95 describe("POST /admin/users/:id", () => {
96 it("should update a user", async () => {
97 const updateResponse = (
98 await api.post(
99 `/admin/users/${user.id}`,
100 { first_name: "John", last_name: "Doe" },
101 adminHeaders
102 )
103 ).data.user
104
105 expect(updateResponse).toEqual(
106 expect.objectContaining({
107 id: user.id,
108 created_at: expect.any(String),
109 updated_at: expect.any(String),
110 first_name: "John",
111 last_name: "Doe",
112 })
113 )
114 })
115 })
116
117 describe("DELETE /admin/users", () => {
118 it("Deletes a user and its auth identity when the user is the only associated actor", async () => {
119 const userTwoAdminHeaders = {
120 headers: { "x-medusa-access-token": "test_token" },
121 }
122
123 const { user: userTwo, authIdentity: userTwoAuthIdentity } =
124 await createAdminUser(dbConnection, userTwoAdminHeaders, container, {
125 email: "test@test.com",
126 })
127
128 const authModule: IAuthModuleService = container.resolve(Modules.AUTH)
129
130 const response = await api.delete(
131 `/admin/users/${userTwo.id}`,
132 adminHeaders
133 )
134
135 expect(response.status).toEqual(200)
136 expect(response.data).toEqual({
137 id: userTwo.id,
138 object: "user",
139 deleted: true,
140 })
141
142 // The user was the only actor associated with the auth identity, so the
143 // whole auth identity should be deleted.
144 await expect(
145 authModule.retrieveAuthIdentity(userTwoAuthIdentity.id)
146 ).rejects.toThrow()
147
148 // And its provider identity should be cascade-deleted along with it, so
149 // authentication with the old credentials should no longer succeed.
150 const authError = await api
151 .post(`/auth/user/emailpass`, {
152 email: userTwo.email,
153 password: "somepassword",
154 })
155 .catch((e) => e)
156
157 expect(authError.response.status).toEqual(401)
158
159 // And the provider identity should no longer exist.
160 const providerIdentities = await authModule.listProviderIdentities({
161 entity_id: userTwo.email,
162 })
163 expect(providerIdentities).toHaveLength(0)
164 })
165
166 it("Keeps the auth identity when another non-null actor type is still associated", async () => {
167 const userThreeAdminHeaders = {
168 headers: { "x-medusa-access-token": "test_token" },
169 }
170
171 const { user: userThree, authIdentity: userThreeAuthIdentity } =
172 await createAdminUser(
173 dbConnection,
174 userThreeAdminHeaders,
175 container,
176 {
177 email: "test-multi@test.com",
178 }
179 )
180
181 const authModule: IAuthModuleService = container.resolve(Modules.AUTH)
182
183 // Associate another (non-null) actor type with the same auth identity.
184 await authModule.updateAuthIdentities({
185 id: userThreeAuthIdentity.id,
186 app_metadata: {
187 user_id: userThree.id,
188 customer_id: "cus_123",
189 },
190 })
191
192 const response = await api.delete(
193 `/admin/users/${userThree.id}`,
194 adminHeaders
195 )
196
197 expect(response.status).toEqual(200)
198 expect(response.data).toEqual({
199 id: userThree.id,
200 object: "user",
201 deleted: true,
202 })
203
204 // The auth identity must be kept since another actor is still associated.
205 const authIdentity = await authModule.retrieveAuthIdentity(
206 userThreeAuthIdentity.id
207 )
208
209 expect(authIdentity).toEqual(
210 expect.objectContaining({
211 id: userThreeAuthIdentity.id,
212 app_metadata: expect.objectContaining({
213 // The other actor type keeps its value...
214 customer_id: "cus_123",
215 // ...while the deleted actor's entry is set to null.
216 user_id: null,
217 }),
218 })
219 )
220
221 // The provider identity should still exist since the auth identity was kept.
222 const providerIdentities = await authModule.listProviderIdentities({
223 entity_id: userThree.email,
224 })
225 expect(providerIdentities).toHaveLength(1)
226 })
227
228 it("throws if you attempt to delete your own user", async () => {
229 const error = await api
230 .delete(`/admin/users/${user.id}`, adminHeaders)
231 .catch((e) => e)
232
233 expect(error.response.status).toEqual(400)
234 expect(error.response.data.message).toEqual(
235 "A user cannot delete itself"
236 )
237 })
238
239 // TODO: Migrate when analytics config is implemented in 2.0
240 it.skip("Deletes a user and their analytics config", async () => {
241 const userId = "member-user"
242
243 // await simpleAnalyticsConfigFactory(dbConnection, {
244 // user_id: userId,
245 // })
246
247 const response = await api.delete(
248 `/admin/users/${userId}`,
249 adminHeaders
250 )
251
252 expect(response.status).toEqual(200)
253 expect(response.data).toEqual({
254 id: userId,
255 object: "user",
256 deleted: true,
257 })
258
259 const configs = await dbConnection.manager.query(
260 `SELECT * FROM public.analytics_config WHERE user_id = '${userId}'`
261 )
262
263 expect(configs).toEqual(
264 expect.arrayContaining([
265 expect.objectContaining({
266 created_at: expect.any(Date),
267 updated_at: expect.any(Date),
268 deleted_at: expect.any(Date),
269 id: expect.any(String),
270 user_id: userId,
271 opt_out: false,
272 anonymize: false,
273 }),
274 ])
275 )
276 })
277 })
278
279 describe("GET /admin/users/:id/auth-providers", () => {
280 it("lists the auth providers the user can authenticate with", async () => {
281 const response = await api.get(
282 `/admin/users/${user.id}/auth-providers`,
283 adminHeaders
284 )
285
286 expect(response.status).toEqual(200)
287 expect(response.data.providers).toEqual(["emailpass"])
288 })
289
290 it("returns an empty list for a user without an auth identity", async () => {
291 const userModule = container.resolve(Modules.USER)
292 const providerlessUser = await userModule.createUsers({
293 email: "no-auth-identity@test.com",
294 })
295
296 const response = await api.get(
297 `/admin/users/${providerlessUser.id}/auth-providers`,
298 adminHeaders
299 )
300
301 expect(response.status).toEqual(200)
302 expect(response.data.providers).toEqual([])
303 })
304 })
305
306 describe("POST /admin/users/:id/reset-password", () => {
307 it("returns a token that the user can use to reset their password", async () => {
308 const email = "reset-link@test.com"
309
310 const resetUserHeaders = {
311 headers: { "x-medusa-access-token": "test_token" },
312 }
313
314 const { user: resetUser } = await createAdminUser(
315 dbConnection,
316 resetUserHeaders,
317 container,
318 { email }
319 )
320
321 const response = await api.post(
322 `/admin/users/${resetUser.id}/reset-password`,
323 {},
324 adminHeaders
325 )
326
327 expect(response.status).toEqual(200)
328 expect(response.data).toEqual({ token: expect.any(String) })
329
330 const updateResponse = await api.post(
331 `/auth/user/emailpass/update`,
332 { password: "new_password" },
333 { headers: { authorization: `Bearer ${response.data.token}` } }
334 )
335
336 expect(updateResponse.status).toEqual(200)
337
338 const loginResponse = await api.post("/auth/user/emailpass", {
339 email,
340 password: "new_password",
341 })
342
343 expect(loginResponse.status).toEqual(200)
344 })
345
346 it("throws when the user does not exist", async () => {
347 const error = await api
348 .post(
349 `/admin/users/usr_does-not-exist/reset-password`,
350 {},
351 adminHeaders
352 )
353 .catch((e) => e)
354
355 expect(error.response.status).toEqual(404)
356 expect(error.response.data.message).toEqual(
357 "User with id: usr_does-not-exist was not found"
358 )
359 })
360 })
361
362 // TODO: Migrate when implemented in 2.0
363 describe.skip("POST /admin/users/reset-password + POST /admin/users/password-token", () => {
364 let user
365 beforeEach(async () => {
366 const response = await api
367 .post(
368 "/admin/users",
369 {
370 email: "test@forgottenPassword.com",
371 role: "member",
372 password: "test123453",
373 },
374 adminHeaders
375 )
376 .catch((err) => console.log(err))
377
378 user = response.data.user
379 })
380
381 it("Doesn't fail to fetch user when resetting password for an unknown email (unauthorized endpoint)", async () => {
382 const resp = await api.post("/admin/users/password-token", {
383 email: "test-doesnt-exist@test.com",
384 })
385
386 expect(resp.status).toEqual(204)
387 })
388
389 it("Doesn't fail when generating password reset token (unauthorized endpoint)", async () => {
390 const resp = await api
391 .post("/admin/users/password-token", {
392 email: user.email,
393 })
394 .catch((err) => {
395 console.log(err)
396 })
397
398 expect(resp.data).toEqual("")
399 expect(resp.status).toEqual(204)
400 })
401
402 it("Resets the password given a valid token (unauthorized endpoint)", async () => {
403 const expiry = Math.floor(Date.now() / 1000) + 60 * 15
404 const dbUser = await dbConnection.manager.query(
405 `SELECT * FROM public.user WHERE email = '${user.email}'`
406 )
407
408 const token_payload = {
409 user_id: user.id,
410 email: user.email,
411 exp: expiry,
412 }
413 const token = jwt.sign(token_payload, dbUser[0].password_hash)
414
415 const result = await api
416 .post("/admin/users/reset-password", {
417 token,
418 email: "test@forgottenpassword.com",
419 password: "new password",
420 })
421 .catch((err) => console.log(err))
422
423 const loginResult = await api.post("admin/auth", {
424 email: "test@forgottenpassword.com",
425 password: "new password",
426 })
427
428 expect(result.status).toEqual(200)
429 expect(result.data.user).toEqual(
430 expect.objectContaining({
431 email: user.email,
432 role: user.role,
433 })
434 )
435 expect(result.data.user.password_hash).toEqual(undefined)
436
437 expect(loginResult.status).toEqual(200)
438 expect(loginResult.data.user).toEqual(
439 expect.objectContaining({
440 email: user.email,
441 role: user.role,
442 })
443 )
444 })
445
446 it("Resets the password given a valid token without including email(unauthorized endpoint)", async () => {
447 const expiry = Math.floor(Date.now() / 1000) + 60 * 15
448 const dbUser = await dbConnection.manager.query(
449 `SELECT * FROM public.user WHERE email = '${user.email}'`
450 )
451
452 const token_payload = {
453 user_id: user.id,
454 email: user.email,
455 exp: expiry,
456 }
457 const token = jwt.sign(token_payload, dbUser[0].password_hash)
458
459 const result = await api
460 .post("/admin/users/reset-password", {
461 token,
462 password: "new password",
463 })
464 .catch((err) => console.log(err.response.data.message))
465
466 const loginResult = await api.post("admin/auth", {
467 email: user.email,
468 password: "new password",
469 })
470
471 expect(result.status).toEqual(200)
472 expect(result.data.user).toEqual(
473 expect.objectContaining({
474 email: user.email,
475 role: user.role,
476 })
477 )
478 expect(result.data.user.password_hash).toEqual(undefined)
479
480 expect(loginResult.status).toEqual(200)
481 expect(loginResult.data.user).toEqual(
482 expect.objectContaining({
483 email: user.email,
484 role: user.role,
485 })
486 )
487 })
488
489 it("Fails to Reset the password given an invalid token (unauthorized endpoint)", async () => {
490 expect.assertions(2)
491
492 const token = "test.test.test"
493
494 await api
495 .post("/admin/users/reset-password", {
496 token,
497 email: "test@forgottenpassword.com",
498 password: "new password",
499 })
500 .catch((err) => {
501 expect(err.response.status).toEqual(400)
502 expect(err.response.data.message).toEqual("invalid token")
503 })
504 })
505 })
506
507 describe("User creation with roles", () => {
508 it("should fail to create user with non-existent role", async () => {
509 const workflowService: IWorkflowEngineService = container.resolve(
510 Modules.WORKFLOW_ENGINE
511 )
512
513 const error = await workflowService
514 .run("create-users-workflow", {
515 input: {
516 users: [
517 {
518 email: "test-role@medusa.js",
519 roles: ["non_existent_role_id"],
520 },
521 ],
522 },
523 })
524 .catch((e) => e)
525
526 expect(error.message).toContain("non_existent_role_id")
527 })
528
529 it("should create user with valid role", async () => {
530 const workflowService: IWorkflowEngineService = container.resolve(
531 Modules.WORKFLOW_ENGINE
532 )
533
534 // Get the super admin role created by the RBAC module loader
535 const rbacService = container.resolve(Modules.RBAC)
536 const superAdminRoles = await rbacService.listRbacRoles({
537 id: "role_super_admin",
538 })
539
540 expect(superAdminRoles.length).toBeGreaterThan(0)
541
542 const { result: users } = await workflowService.run(
543 "create-users-workflow",
544 {
545 input: {
546 users: [
547 {
548 email: "test-with-role@medusa.js",
549 roles: [superAdminRoles[0].id],
550 },
551 ],
552 },
553 }
554 )
555
556 expect(users).toHaveLength(1)
557 expect(users[0].email).toEqual("test-with-role@medusa.js")
558 })
559 })
560
561 describe("User Roles Management", () => {
562 let testUser
563 let viewerRole
564 let editorRole
565 let adminRole
566 let policies
567
568 beforeEach(async () => {
569 const rbacModule = container.resolve(Modules.RBAC)
570 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
571
572 // Create policies
573 const policy1 = await api.post(
574 "/admin/rbac/policies",
575 {
576 key: "read:products",
577 resource: "product",
578 operation: "read",
579 name: "Read Products",
580 },
581 adminHeaders
582 )
583
584 const policy2 = await api.post(
585 "/admin/rbac/policies",
586 {
587 key: "write:products",
588 resource: "product",
589 operation: "write",
590 name: "Write Products",
591 },
592 adminHeaders
593 )
594
595 const policy3 = await api.post(
596 "/admin/rbac/policies",
597 {
598 key: "delete:products",
599 resource: "product",
600 operation: "delete",
601 name: "Delete Products",
602 },
603 adminHeaders
604 )
605
606 policies = [
607 policy1.data.policy,
608 policy2.data.policy,
609 policy3.data.policy,
610 ]
611
612 // Create roles with different policies
613 const viewerRoleResponse = await api.post(
614 "/admin/rbac/roles",
615 {
616 name: "Product Viewer",
617 description: "Can view products",
618 },
619 adminHeaders
620 )
621 viewerRole = viewerRoleResponse.data.role
622
623 const editorRoleResponse = await api.post(
624 "/admin/rbac/roles",
625 {
626 name: "Product Editor",
627 description: "Can edit products",
628 },
629 adminHeaders
630 )
631 editorRole = editorRoleResponse.data.role
632
633 const adminRoleResponse = await api.post(
634 "/admin/rbac/roles",
635 {
636 name: "Product Admin",
637 description: "Full product access",
638 },
639 adminHeaders
640 )
641 adminRole = adminRoleResponse.data.role
642
643 // Assign policies to roles
644 await rbacModule.createRbacRolePolicies([
645 { role_id: viewerRole.id, policy_id: policies[0].id },
646 ])
647 await rbacModule.createRbacRolePolicies([
648 { role_id: editorRole.id, policy_id: policies[0].id },
649 { role_id: editorRole.id, policy_id: policies[1].id },
650 ])
651 await rbacModule.createRbacRolePolicies([
652 { role_id: adminRole.id, policy_id: policies[0].id },
653 { role_id: adminRole.id, policy_id: policies[1].id },
654 { role_id: adminRole.id, policy_id: policies[2].id },
655 ])
656
657 // Link the admin user to the admin role (so they have all policies)
658 await remoteLink.create({
659 [Modules.USER]: { user_id: user.id },
660 [Modules.RBAC]: { rbac_role_id: adminRole.id },
661 })
662
663 // Create a test user
664 const { result: users } = await createUsersWorkflow(container).run({
665 input: {
666 users: [
667 {
668 email: "testuser@example.com",
669 first_name: "Test",
670 last_name: "User",
671 },
672 ],
673 },
674 })
675 testUser = users[0]
676 })
677
678 describe("GET /admin/users/:id/roles", () => {
679 it("should list roles for a user", async () => {
680 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
681
682 // Assign roles to test user
683 await remoteLink.create([
684 {
685 [Modules.USER]: { user_id: testUser.id },
686 [Modules.RBAC]: { rbac_role_id: viewerRole.id },
687 },
688 {
689 [Modules.USER]: { user_id: testUser.id },
690 [Modules.RBAC]: { rbac_role_id: editorRole.id },
691 },
692 ])
693
694 const response = await api.get(
695 `/admin/users/${testUser.id}/roles`,
696 adminHeaders
697 )
698
699 expect(response.status).toEqual(200)
700 expect(response.data.count).toEqual(2)
701 expect(response.data.roles).toHaveLength(2)
702 expect(response.data.roles).toEqual(
703 expect.arrayContaining([
704 expect.objectContaining({ id: viewerRole.id }),
705 expect.objectContaining({ id: editorRole.id }),
706 ])
707 )
708 })
709
710 it("should return empty array for user with no roles", async () => {
711 const response = await api.get(
712 `/admin/users/${testUser.id}/roles`,
713 adminHeaders
714 )
715
716 expect(response.status).toEqual(200)
717 expect(response.data.count).toEqual(0)
718 expect(response.data.roles).toHaveLength(0)
719 })
720 })
721
722 describe("POST /admin/users/:id/roles", () => {
723 it("should assign roles to a user when actor has all required policies", async () => {
724 const response = await api.post(
725 `/admin/users/${testUser.id}/roles`,
726 { roles: [viewerRole.id, editorRole.id] },
727 adminHeaders
728 )
729
730 expect(response.status).toEqual(200)
731 expect(response.data.roles).toHaveLength(2)
732 expect(response.data.roles).toEqual(
733 expect.arrayContaining([
734 expect.objectContaining({ id: viewerRole.id }),
735 expect.objectContaining({ id: editorRole.id }),
736 ])
737 )
738 })
739
740 it("should fail to assign roles when actor lacks required policies", async () => {
741 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
742
743 // Create a limited user with only viewer role
744 const { result: limitedUsers } = await createUsersWorkflow(
745 container
746 ).run({
747 input: {
748 users: [
749 {
750 email: "limited@example.com",
751 first_name: "Limited",
752 last_name: "User",
753 },
754 ],
755 },
756 })
757 const limitedUser = limitedUsers[0]
758
759 // Assign only viewer role to limited user
760 await remoteLink.create({
761 [Modules.USER]: { user_id: limitedUser.id },
762 [Modules.RBAC]: { rbac_role_id: viewerRole.id },
763 })
764
765 // Create auth identity and generate JWT for limited user
766 const authModule: IAuthModuleService = container.resolve(Modules.AUTH)
767 const limitedAuthIdentity = await authModule.createAuthIdentities({
768 provider_identities: [
769 {
770 provider: "emailpass",
771 entity_id: limitedUser.email,
772 },
773 ],
774 app_metadata: { user_id: limitedUser.id },
775 })
776
777 const config = container.resolve(
778 ContainerRegistrationKeys.CONFIG_MODULE
779 )
780 const { projectConfig } = config
781 const { jwtSecret, jwtOptions } = projectConfig.http
782 const limitedToken = generateJwtToken(
783 {
784 actor_id: limitedUser.id,
785 actor_type: "user",
786 auth_identity_id: limitedAuthIdentity.id,
787 app_metadata: {
788 user_id: limitedUser.id,
789 roles: [viewerRole.id],
790 },
791 },
792 {
793 secret: jwtSecret,
794 expiresIn: "1d",
795 jwtOptions,
796 }
797 )
798
799 const limitedHeaders = {
800 headers: { authorization: `Bearer ${limitedToken}` },
801 }
802
803 // Try to assign admin role (which has policies the limited user doesn't have)
804 const error = await api
805 .post(
806 `/admin/users/${testUser.id}/roles`,
807 { roles: [adminRole.id] },
808 limitedHeaders
809 )
810 .catch((e) => e)
811
812 expect(error.response.status).toEqual(403)
813 })
814
815 it("should return 404 for non-existent user", async () => {
816 const error = await api
817 .post(
818 `/admin/users/non_existent_id/roles`,
819 { roles: [viewerRole.id] },
820 adminHeaders
821 )
822 .catch((e) => e)
823
824 expect(error.response.status).toEqual(404)
825 })
826 })
827
828 describe("DELETE /admin/users/:id/roles/:role_id", () => {
829 it("should remove a role from a user", async () => {
830 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
831
832 // First assign a role
833 await remoteLink.create({
834 [Modules.USER]: { user_id: testUser.id },
835 [Modules.RBAC]: { rbac_role_id: viewerRole.id },
836 })
837
838 // Verify role was assigned
839 const beforeResponse = await api.get(
840 `/admin/users/${testUser.id}/roles`,
841 adminHeaders
842 )
843 expect(beforeResponse.data.count).toEqual(1)
844
845 // Remove the role
846 const deleteResponse = await api.delete(
847 `/admin/users/${testUser.id}/roles/${viewerRole.id}`,
848 adminHeaders
849 )
850
851 expect(deleteResponse.status).toEqual(200)
852 expect(deleteResponse.data).toEqual({
853 id: viewerRole.id,
854 object: "user_role",
855 deleted: true,
856 })
857
858 // Verify role was removed
859 const afterResponse = await api.get(
860 `/admin/users/${testUser.id}/roles`,
861 adminHeaders
862 )
863 expect(afterResponse.data.count).toEqual(0)
864 })
865 })
866
867 describe("DELETE /admin/users/:id/roles (batch)", () => {
868 it("should remove multiple roles from a user", async () => {
869 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
870
871 // Assign multiple roles to test user
872 await remoteLink.create([
873 {
874 [Modules.USER]: { user_id: testUser.id },
875 [Modules.RBAC]: { rbac_role_id: viewerRole.id },
876 },
877 {
878 [Modules.USER]: { user_id: testUser.id },
879 [Modules.RBAC]: { rbac_role_id: editorRole.id },
880 },
881 ])
882
883 // Verify roles were assigned
884 const beforeResponse = await api.get(
885 `/admin/users/${testUser.id}/roles`,
886 adminHeaders
887 )
888 expect(beforeResponse.data.count).toEqual(2)
889
890 // Remove multiple roles
891 const deleteResponse = await api.delete(
892 `/admin/users/${testUser.id}/roles`,
893 {
894 ...adminHeaders,
895 data: { roles: [viewerRole.id, editorRole.id] },
896 }
897 )
898
899 expect(deleteResponse.status).toEqual(200)
900 expect(deleteResponse.data).toEqual({
901 ids: [viewerRole.id, editorRole.id],
902 object: "user_role",
903 deleted: true,
904 })
905
906 // Verify roles were removed
907 const afterResponse = await api.get(
908 `/admin/users/${testUser.id}/roles`,
909 adminHeaders
910 )
911 expect(afterResponse.data.count).toEqual(0)
912 })
913
914 it("should fail to remove a role when actor lacks required policies", async () => {
915 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
916
917 // Assign admin role to test user (has policies A, B, C)
918 await remoteLink.create({
919 [Modules.USER]: { user_id: testUser.id },
920 [Modules.RBAC]: { rbac_role_id: adminRole.id },
921 })
922
923 // Create a limited user with only viewer role (has policy A only)
924 const { result: limitedUsers } = await createUsersWorkflow(
925 container
926 ).run({
927 input: {
928 users: [
929 {
930 email: "limited-delete@example.com",
931 first_name: "Limited",
932 last_name: "Deleter",
933 },
934 ],
935 },
936 })
937 const limitedUser = limitedUsers[0]
938
939 // Assign only viewer role to limited user
940 await remoteLink.create({
941 [Modules.USER]: { user_id: limitedUser.id },
942 [Modules.RBAC]: { rbac_role_id: viewerRole.id },
943 })
944
945 // Create auth identity and generate JWT for limited user
946 const authModule: IAuthModuleService = container.resolve(Modules.AUTH)
947 const limitedAuthIdentity = await authModule.createAuthIdentities({
948 provider_identities: [
949 {
950 provider: "emailpass",
951 entity_id: limitedUser.email,
952 },
953 ],
954 app_metadata: { user_id: limitedUser.id },
955 })
956
957 const config = container.resolve(
958 ContainerRegistrationKeys.CONFIG_MODULE
959 )
960 const { projectConfig } = config
961 const { jwtSecret, jwtOptions } = projectConfig.http
962 const limitedToken = generateJwtToken(
963 {
964 actor_id: limitedUser.id,
965 actor_type: "user",
966 auth_identity_id: limitedAuthIdentity.id,
967 app_metadata: {
968 user_id: limitedUser.id,
969 roles: [viewerRole.id],
970 },
971 },
972 {
973 secret: jwtSecret,
974 expiresIn: "1d",
975 jwtOptions,
976 }
977 )
978
979 const limitedHeaders = {
980 headers: { authorization: `Bearer ${limitedToken}` },
981 }
982
983 // Try to remove admin role (which has policies the limited user doesn't have)
984 const error = await api
985 .delete(
986 `/admin/users/${testUser.id}/roles/${adminRole.id}`,
987 limitedHeaders
988 )
989 .catch((e) => e)
990
991 expect(error.response.status).toEqual(403)
992 })
993 })
994 })
995 },
996 })