1 import { getAssignablePoliciesWorkflow } from "@medusajs/core-flows"
2 import { Modules } from "@medusajs/framework/utils"
3 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
4 import {
5 adminHeaders,
6 createAdminUser,
7 } from "../../../../helpers/create-admin-user"
8
9 jest.setTimeout(60000)
10
11 process.env.MEDUSA_FF_RBAC = "true"
12
13 medusaIntegrationTestRunner({
14 testSuite: ({ dbConnection, api, getContainer, dbUtils }) => {
15 let container
16
17 beforeAll(async () => {
18 container = getContainer()
19 await createAdminUser(dbConnection, adminHeaders, container)
20
21 await dbUtils.snapshot()
22 })
23
24 afterAll(async () => {
25 delete process.env.MEDUSA_FF_RBAC
26 })
27
28 describe("RBAC Policies - Admin API", () => {
29 describe("POST /admin/rbac/policies", () => {
30 it("should create a policy", async () => {
31 const response = await api.post(
32 "/admin/rbac/policies",
33 {
34 key: "read:products",
35 resource: "product",
36 operation: "read",
37 name: "Read Products",
38 description: "Permission to read products",
39 },
40 adminHeaders
41 )
42
43 expect(response.status).toEqual(200)
44 expect(response.data.policy).toEqual(
45 expect.objectContaining({
46 id: expect.any(String),
47 key: "read:products",
48 resource: "product",
49 operation: "read",
50 name: "Read Products",
51 description: "Permission to read products",
52 })
53 )
54 })
55
56 it("should create a policy with metadata", async () => {
57 const response = await api.post(
58 "/admin/rbac/policies",
59 {
60 key: "write:orders",
61 resource: "order",
62 operation: "write",
63 name: "Write Orders",
64 metadata: { category: "order_management" },
65 },
66 adminHeaders
67 )
68
69 expect(response.status).toEqual(200)
70 expect(response.data.policy).toEqual(
71 expect.objectContaining({
72 key: "write:orders",
73 resource: "order",
74 operation: "write",
75 metadata: { category: "order_management" },
76 })
77 )
78 })
79 })
80
81 describe("GET /admin/rbac/policies", () => {
82 beforeEach(async () => {
83 await api.post(
84 "/admin/rbac/policies",
85 {
86 key: "read:products",
87 resource: "product",
88 operation: "read",
89 name: "Read Products",
90 },
91 adminHeaders
92 )
93
94 await api.post(
95 "/admin/rbac/policies",
96 {
97 key: "write:products",
98 resource: "product",
99 operation: "write",
100 name: "Write Products",
101 },
102 adminHeaders
103 )
104
105 await api.post(
106 "/admin/rbac/policies",
107 {
108 key: "read:orders",
109 resource: "order",
110 operation: "read",
111 name: "Read Orders",
112 },
113 adminHeaders
114 )
115 })
116
117 it("should list all policies", async () => {
118 const response = await api.get(
119 "/admin/rbac/policies?limit=1000",
120 adminHeaders
121 )
122
123 expect(response.status).toEqual(200)
124 expect(response.data.count).toBeGreaterThanOrEqual(3)
125 expect(response.data.policies).toEqual(
126 expect.arrayContaining([
127 expect.objectContaining({
128 key: "read:products",
129 resource: "product",
130 operation: "read",
131 }),
132 expect.objectContaining({
133 key: "write:products",
134 resource: "product",
135 operation: "write",
136 }),
137 expect.objectContaining({
138 key: "read:orders",
139 resource: "order",
140 operation: "read",
141 }),
142 ])
143 )
144 })
145
146 it("should filter policies by resource", async () => {
147 const response = await api.get(
148 "/admin/rbac/policies?resource=product",
149 adminHeaders
150 )
151
152 expect(response.status).toEqual(200)
153 expect(response.data.count).toEqual(6)
154 expect(response.data.policies).toEqual(
155 expect.arrayContaining([
156 expect.objectContaining({
157 key: "read:products",
158 resource: "product",
159 }),
160 expect.objectContaining({
161 key: "write:products",
162 resource: "product",
163 }),
164 ])
165 )
166 })
167
168 it("should filter policies by operation", async () => {
169 const response = await api.get(
170 "/admin/rbac/policies?operation=read&limit=1000",
171 adminHeaders
172 )
173
174 expect(response.status).toEqual(200)
175 expect(response.data.count).toBeGreaterThanOrEqual(2)
176 expect(response.data.policies).toEqual(
177 expect.arrayContaining([
178 expect.objectContaining({
179 key: "read:products",
180 operation: "read",
181 }),
182 expect.objectContaining({
183 key: "read:orders",
184 operation: "read",
185 }),
186 ])
187 )
188 })
189 })
190
191 describe("GET /admin/rbac/policies/:id", () => {
192 it("should retrieve a policy by id", async () => {
193 const createResponse = await api.post(
194 "/admin/rbac/policies",
195 {
196 key: "delete:users",
197 resource: "user",
198 operation: "delete",
199 name: "Delete Users",
200 },
201 adminHeaders
202 )
203
204 const policyId = createResponse.data.policy.id
205
206 const response = await api.get(
207 `/admin/rbac/policies/${policyId}`,
208 adminHeaders
209 )
210
211 expect(response.status).toEqual(200)
212 expect(response.data.policy).toEqual(
213 expect.objectContaining({
214 id: policyId,
215 key: "delete:users",
216 resource: "user",
217 operation: "delete",
218 name: "Delete Users",
219 })
220 )
221 })
222 })
223
224 describe("POST /admin/rbac/policies/:id", () => {
225 it("should update a policy", async () => {
226 const createResponse = await api.post(
227 "/admin/rbac/policies",
228 {
229 key: "admin:system",
230 resource: "system",
231 operation: "admin",
232 name: "System Admin",
233 },
234 adminHeaders
235 )
236
237 const policyId = createResponse.data.policy.id
238
239 const response = await api.post(
240 `/admin/rbac/policies/${policyId}`,
241 {
242 name: "System Administrator",
243 description: "Full system access",
244 },
245 adminHeaders
246 )
247
248 expect(response.status).toEqual(200)
249 expect(response.data.policy).toEqual(
250 expect.objectContaining({
251 id: policyId,
252 key: "admin:system",
253 name: "System Administrator",
254 description: "Full system access",
255 })
256 )
257 })
258 })
259
260 describe("DELETE /admin/rbac/policies/:id", () => {
261 it("should delete a policy", async () => {
262 const createResponse = await api.post(
263 "/admin/rbac/policies",
264 {
265 key: "test:delete",
266 resource: "test",
267 operation: "delete",
268 name: "Test Delete",
269 },
270 adminHeaders
271 )
272
273 const policyId = createResponse.data.policy.id
274
275 const deleteResponse = await api.delete(
276 `/admin/rbac/policies/${policyId}`,
277 adminHeaders
278 )
279
280 expect(deleteResponse.status).toEqual(200)
281 expect(deleteResponse.data).toEqual({
282 id: policyId,
283 object: "rbac_policy",
284 deleted: true,
285 })
286
287 const listResponse = await api.get(
288 "/admin/rbac/policies",
289 adminHeaders
290 )
291 expect(
292 listResponse.data.policies.find((p) => p.id === policyId)
293 ).toBeUndefined()
294 })
295 })
296
297 describe("GET /admin/rbac/policies/assignable", () => {
298 // Headers for actors with varying levels of permission coverage.
299 // `adminHeaders` is the super-admin baseline (holds `*:*`).
300 const productManagerHeaders = { headers: { ...adminHeaders.headers } }
301 const universalReaderHeaders = { headers: { ...adminHeaders.headers } }
302 const productReaderHeaders = { headers: { ...adminHeaders.headers } }
303 const noRolesUserHeaders = { headers: { ...adminHeaders.headers } }
304
305 // Candidate policy IDs we ask the endpoint about. Their `(resource,
306 // operation)` shape drives whether each scoped actor can cover them.
307 let productReadId: string
308 let productCreateId: string
309 let productUpdateId: string
310 let productDeleteId: string
311 let customerReadId: string
312 let customerCreateId: string
313 let wildcardPolicyId: string
314 let productWildcardId: string
315 let universalReadId: string
316 let rbacPolicyReadId: string
317
318 beforeEach(async () => {
319 const rbacModule = container.resolve(Modules.RBAC)
320
321 // Concrete candidate policies — covered by various wildcard grants.
322 const ensurePolicy = async (params: {
323 key: string
324 resource: string
325 operation: string
326 name: string
327 }) => {
328 const [existing] = await rbacModule.listRbacPolicies({
329 key: params.key,
330 })
331 if (existing) {
332 return existing
333 }
334 const [created] = await rbacModule.createRbacPolicies([params])
335 return created
336 }
337
338 const productRead = await ensurePolicy({
339 key: "product:read",
340 resource: "product",
341 operation: "read",
342 name: "Read Products",
343 })
344 const productCreate = await ensurePolicy({
345 key: "product:create",
346 resource: "product",
347 operation: "create",
348 name: "Create Products",
349 })
350 const productUpdate = await ensurePolicy({
351 key: "product:update",
352 resource: "product",
353 operation: "update",
354 name: "Update Products",
355 })
356 const productDelete = await ensurePolicy({
357 key: "product:delete",
358 resource: "product",
359 operation: "delete",
360 name: "Delete Products",
361 })
362 const customerRead = await ensurePolicy({
363 key: "customer:read",
364 resource: "customer",
365 operation: "read",
366 name: "Read Customers",
367 })
368 const customerCreate = await ensurePolicy({
369 key: "customer:create",
370 resource: "customer",
371 operation: "create",
372 name: "Create Customers",
373 })
374
375 // Wildcard grants attached to actor roles.
376 const productWildcard = await ensurePolicy({
377 key: "product:*",
378 resource: "product",
379 operation: "*",
380 name: "Manage Products",
381 })
382 const universalRead = await ensurePolicy({
383 key: "*:read",
384 resource: "*",
385 operation: "read",
386 name: "Read Anything",
387 })
388
389 // A literal `*:*` candidate row — only a `*:*` holder can assign it.
390 const fullWildcard = await ensurePolicy({
391 key: "*:*",
392 resource: "*",
393 operation: "*",
394 name: "Everything",
395 })
396
397 // The route is guarded by `rbac_policy:read` — every non-super-admin
398 // actor below also holds it so they reach the workflow.
399 const rbacPolicyRead = await ensurePolicy({
400 key: "rbac_policy:read",
401 resource: "rbac_policy",
402 operation: "read",
403 name: "Read Policies",
404 })
405
406 productReadId = productRead.id
407 productCreateId = productCreate.id
408 productUpdateId = productUpdate.id
409 productDeleteId = productDelete.id
410 customerReadId = customerRead.id
411 customerCreateId = customerCreate.id
412 wildcardPolicyId = fullWildcard.id
413 productWildcardId = productWildcard.id
414 universalReadId = universalRead.id
415 rbacPolicyReadId = rbacPolicyRead.id
416
417 // --- Actor roles ---
418 const productManagerRole = await rbacModule.createRbacRoles({
419 name: "Assignable Policies — Product Manager",
420 })
421 const universalReaderRole = await rbacModule.createRbacRoles({
422 name: "Assignable Policies — Universal Reader",
423 })
424 const productReaderRole = await rbacModule.createRbacRoles({
425 name: "Assignable Policies — Product Reader",
426 })
427
428 await rbacModule.createRbacRolePolicies([
429 {
430 role_id: productManagerRole.id,
431 policy_id: productWildcard.id,
432 },
433 {
434 role_id: productManagerRole.id,
435 policy_id: rbacPolicyRead.id,
436 },
437 { role_id: universalReaderRole.id, policy_id: universalRead.id },
438 {
439 role_id: universalReaderRole.id,
440 policy_id: rbacPolicyRead.id,
441 },
442 { role_id: productReaderRole.id, policy_id: productRead.id },
443 {
444 role_id: productReaderRole.id,
445 policy_id: rbacPolicyRead.id,
446 },
447 ])
448
449 await createAdminUser(
450 dbConnection,
451 productManagerHeaders,
452 container,
453 {
454 email: "assignable-policies-product-manager@medusa.js",
455 roles: [productManagerRole.id],
456 }
457 )
458 await createAdminUser(
459 dbConnection,
460 universalReaderHeaders,
461 container,
462 {
463 email: "assignable-policies-universal-reader@medusa.js",
464 roles: [universalReaderRole.id],
465 }
466 )
467 await createAdminUser(dbConnection, productReaderHeaders, container, {
468 email: "assignable-policies-product-reader@medusa.js",
469 roles: [productReaderRole.id],
470 })
471 await createAdminUser(dbConnection, noRolesUserHeaders, container, {
472 email: "assignable-policies-no-roles@medusa.js",
473 roles: [],
474 })
475 })
476
477 it("returns every candidate policy for a super-admin (`*:*`)", async () => {
478 const response = await api.get(
479 "/admin/rbac/policies/assignable?limit=1000",
480 adminHeaders
481 )
482
483 const ids = response.data.policies.map((p: { id: string }) => p.id)
484 expect(ids).toEqual(
485 expect.arrayContaining([
486 productReadId,
487 productCreateId,
488 productUpdateId,
489 productDeleteId,
490 customerReadId,
491 customerCreateId,
492 wildcardPolicyId,
493 ])
494 )
495 })
496
497 it("expands `resource:*` — product:* actor sees all product policies including the wildcard itself", async () => {
498 const response = await api.get(
499 "/admin/rbac/policies/assignable",
500 productManagerHeaders
501 )
502
503 const ids = response.data.policies.map((p: { id: string }) => p.id)
504 expect(ids).toEqual(
505 expect.arrayContaining([
506 productReadId,
507 productCreateId,
508 productUpdateId,
509 productDeleteId,
510 productWildcardId,
511 rbacPolicyReadId,
512 ])
513 )
514 expect(ids.length).toEqual(6)
515 })
516
517 it("expands `*:op` — *:read actor sees all read policies including the wildcard itself", async () => {
518 const response = await api.get(
519 "/admin/rbac/policies/assignable?limit=1000",
520 universalReaderHeaders
521 )
522
523 const ids = response.data.policies.map((p: { id: string }) => p.id)
524 expect(ids).toEqual(
525 expect.arrayContaining([
526 productReadId,
527 customerReadId,
528 universalReadId,
529 rbacPolicyReadId,
530 ])
531 )
532 })
533
534 it("literal grant — product:read actor sees product:read and any policy covered by that grant", async () => {
535 const response = await api.get(
536 "/admin/rbac/policies/assignable",
537 productReaderHeaders
538 )
539
540 const ids = response.data.policies.map((p: { id: string }) => p.id)
541 expect(ids).toEqual(
542 expect.arrayContaining([productReadId, rbacPolicyReadId])
543 )
544 expect(ids.length).toEqual(2)
545 })
546
547 it("only a `*:*` holder can assign a literal `*:*` policy", async () => {
548 // Super-admin holds *:* → can assign the wildcard policy row.
549 const superAdminIds = (
550 await api.get(
551 `/admin/rbac/policies/assignable?id=${wildcardPolicyId}`,
552 adminHeaders
553 )
554 ).data.policies.map((p: { id: string }) => p.id)
555 expect(superAdminIds).toContain(wildcardPolicyId)
556
557 // Every scoped actor cannot.
558 const others = await Promise.all([
559 api.get(
560 `/admin/rbac/policies/assignable?id=${wildcardPolicyId}`,
561 productManagerHeaders
562 ),
563 api.get(
564 `/admin/rbac/policies/assignable?id=${wildcardPolicyId}`,
565 universalReaderHeaders
566 ),
567 api.get(
568 `/admin/rbac/policies/assignable?id=${wildcardPolicyId}`,
569 productReaderHeaders
570 ),
571 ])
572 for (const response of others) {
573 const ids = response.data.policies.map((p: { id: string }) => p.id)
574 expect(ids).not.toContain(wildcardPolicyId)
575 }
576 })
577
578 it("returns empty policies via the workflow when the actor holds no roles", async () => {
579 // No-roles actor can't pass the route's `rbac_policy:read` gate,
580 // so we exercise the empty-actor branch by running the workflow
581 // directly with their id.
582 const userModule = container.resolve(Modules.USER)
583 const [noRolesUser] = await userModule.listUsers({
584 email: "assignable-policies-no-roles@medusa.js",
585 })
586
587 const { result } = await getAssignablePoliciesWorkflow(container).run(
588 {
589 input: {
590 actor_id: noRolesUser.id,
591 actor: "user",
592 },
593 }
594 )
595
596 expect(result.policies).toEqual([])
597 expect(result.count).toEqual(0)
598 })
599
600 it("applies the `id` filter when forwarded", async () => {
601 const response = await api.get(
602 `/admin/rbac/policies/assignable?id=${productReadId}`,
603 adminHeaders
604 )
605
606 const ids = response.data.policies.map((p: { id: string }) => p.id)
607 expect(ids).toEqual([productReadId])
608 expect(response.data.count).toEqual(1)
609 })
610
611 it("paginates the assignable subset, not the raw rbac_policy set", async () => {
612 // product:* actor is assignable exactly 6 policies:
613 // product:read/create/update/delete, product:* (self),
614 // rbac_policy:read.
615 // Asking for limit=2 must return 2 rows (a full page), and the next
616 // page (offset=2, limit=2) must return the remaining 2 — proving
617 // filtering happens before pagination. count must reflect the total
618 // assignable, not the page size.
619 const firstPage = await api.get(
620 "/admin/rbac/policies/assignable?limit=2&offset=0&order=id",
621 productManagerHeaders
622 )
623
624 expect(firstPage.data.policies).toHaveLength(2)
625 expect(firstPage.data.count).toEqual(6)
626
627 const secondPage = await api.get(
628 "/admin/rbac/policies/assignable?limit=2&offset=2&order=id",
629 productManagerHeaders
630 )
631
632 expect(secondPage.data.policies).toHaveLength(2)
633 expect(secondPage.data.count).toEqual(6)
634
635 const thirdPage = await api.get(
636 "/admin/rbac/policies/assignable?limit=2&offset=4&order=id",
637 productManagerHeaders
638 )
639
640 expect(thirdPage.data.policies).toHaveLength(2)
641 expect(thirdPage.data.count).toEqual(6)
642
643 // No overlap between the pages
644 const firstIds = firstPage.data.policies.map(
645 (p: { id: string }) => p.id
646 )
647 const secondIds = secondPage.data.policies.map(
648 (p: { id: string }) => p.id
649 )
650 const thirdIds = thirdPage.data.policies.map(
651 (p: { id: string }) => p.id
652 )
653 expect(firstIds).not.toEqual(
654 expect.arrayContaining(secondIds as string[])
655 )
656 expect(firstIds).not.toEqual(
657 expect.arrayContaining(thirdIds as string[])
658 )
659 expect(secondIds).not.toEqual(
660 expect.arrayContaining(thirdIds as string[])
661 )
662
663 // Union covers exactly the assignable set.
664 expect(new Set([...firstIds, ...secondIds, ...thirdIds])).toEqual(
665 new Set([
666 productReadId,
667 productCreateId,
668 productUpdateId,
669 productDeleteId,
670 productWildcardId,
671 rbacPolicyReadId,
672 ])
673 )
674 })
675 })
676 })
677 },
678 })