1 import { MedusaContainer } from "@medusajs/types"
2 import {
3 ContainerRegistrationKeys,
4 useCache,
5 WILDCARD,
6 } from "@medusajs/utils"
7 import { FlagRouter } from "../feature-flags/flag-router"
8
9 export type PermissionAction = {
10 resource: string
11 operation: string | string[]
12 }
13
14 /*
15 /**
16 *
17 * @property roles the role(s) to check. Can be a single string or an array of strings.
18 * @property actions the action(s) to check. Can be a single `PermissionAction` or an array of `PermissionAction`s.
19 * @property container the Medusa container
20 */
21 export type HasPermissionInput = {
22 roles: string | string[]
23 actions: PermissionAction | PermissionAction[]
24 container: MedusaContainer
25 }
26
27 export type ResolvePermissionsInput = {
28 roles: string | string[]
29 /**
30 * The universe of `(resource, operation)` tuples to evaluate against the
31 * actor's policies. The result is the subset of this universe that the
32 * actor is granted, with wildcards (`*:*`, `*:op`, `resource:*`) expanded.
33 */
34 universe: { resource: string; operation: string }[]
35 container: MedusaContainer
36 }
37
38 type RolePoliciesCache = Map<string, Map<string, Set<string>>>
39
40 /**
41 * Applies wildcard-aware matching to decide whether any of the
42 * supplied roles grants `(resource, operation)`. This is the single source of
43 * truth for wildcard semantics used by both {@link hasPermission} and
44 * {@link resolvePermissions}.
45 */
46 function policyAllows(
47 rolePoliciesMap: RolePoliciesCache,
48 resource: string,
49 operation: string
50 ): boolean {
51 for (const resourceMap of rolePoliciesMap.values()) {
52 const allowedOps = new Set([
53 ...(resourceMap.get(resource) || []),
54 ...(resourceMap.get(WILDCARD) || []),
55 ])
56 if (allowedOps.has(operation) || allowedOps.has(WILDCARD)) {
57 return true
58 }
59 }
60 return false
61 }
62
63 /**
64 * Checks if the given role(s) have permission to perform the specified action(s).
65 *
66 * @param input - The input containing roles, actions, and container
67 * @returns true if all actions are permitted, false otherwise
68 *
69 * @example
70 * ```ts
71 * const canWrite = await hasPermission({
72 * roles: ['role_123'],
73 * actions: { resource: 'product', operation: 'write' },
74 * container
75 * })
76 *
77 * const canDeleteAndWrite = await hasPermission({
78 * roles: ['role_123'],
79 * actions: { resource: 'product', operation: ['delete', 'write'] },
80 * container
81 * })
82 * ```
83 */
84 export async function hasPermission(
85 input: HasPermissionInput
86 ): Promise<boolean> {
87 const { roles, actions, container } = input
88
89 const roleIds = Array.isArray(roles) ? roles : [roles]
90 const actionList = Array.isArray(actions) ? actions : [actions]
91 const ffRouter = container.resolve(
92 ContainerRegistrationKeys.FEATURE_FLAG_ROUTER
93 ) as FlagRouter
94
95 const isDisabled = !ffRouter.isFeatureEnabled("rbac")
96 if (isDisabled || !roleIds?.length || !actionList?.length) {
97 return true
98 }
99
100 const rolePoliciesMap = await fetchRolePolicies(roleIds, container)
101
102 for (const action of actionList) {
103 const operations = Array.isArray(action.operation)
104 ? action.operation
105 : [action.operation]
106
107 for (const op of operations) {
108 if (!policyAllows(rolePoliciesMap, action.resource, op)) {
109 return false
110 }
111 }
112 }
113
114 return true
115 }
116
117 /**
118 * Resolves the actor's effective permission set: the subset of `universe` that
119 * the actor is granted, with wildcards expanded against concrete entries.
120 *
121 * This is the "inverse" of {@link hasPermission}. It is intended for use by
122 * endpoints that need to hand the client a flat permission list (so the client
123 * can do literal lookups instead of duplicating wildcard semantics).
124 *
125 * @example
126 * ```ts
127 * const granted = await resolvePermissions({
128 * roles: ["role_super_admin"],
129 * universe: [
130 * { resource: "product", operation: "read" },
131 * { resource: "customer", operation: "create" },
132 * ],
133 * container,
134 * })
135 * // granted = Set { "product:read", "customer:create" }
136 * ```
137 */
138 export async function resolvePermissions(
139 input: ResolvePermissionsInput
140 ): Promise<Set<string>> {
141 const { roles, universe, container } = input
142
143 const roleIds = Array.isArray(roles) ? roles : [roles]
144 const ffRouter = container.resolve(
145 ContainerRegistrationKeys.FEATURE_FLAG_ROUTER
146 ) as FlagRouter
147
148 if (!ffRouter.isFeatureEnabled("rbac")) {
149 return new Set(
150 universe.map(({ resource, operation }) => `${resource}:${operation}`)
151 )
152 }
153
154 if (!roleIds.length) {
155 return new Set()
156 }
157
158 const rolePoliciesMap = await fetchRolePolicies(roleIds, container)
159 const granted = new Set<string>()
160
161 for (const { resource, operation } of universe) {
162 if (policyAllows(rolePoliciesMap, resource, operation)) {
163 granted.add(`${resource}:${operation}`)
164 }
165 }
166
167 return granted
168 }
169
170 /**
171 * Fetches a single role's policies from cache or database.
172 */
173 async function fetchSingleRolePolicies(
174 roleId: string,
175 container: MedusaContainer
176 ): Promise<Map<string, Set<string>>> {
177 const query = container.resolve(ContainerRegistrationKeys.QUERY)
178
179 const tags: string[] = []
180 return await useCache<Map<string, Set<string>>>(
181 async () => {
182 const { data: roles } = await query.graph({
183 entity: "rbac_role",
184 fields: ["id", "policies.*"],
185 filters: { id: roleId },
186 })
187
188 const role = roles[0]
189 const resourceMap = new Map<string, Set<string>>()
190
191 tags.push(`rbac_role:${roleId}`)
192 if (role?.policies && Array.isArray(role.policies)) {
193 const policyIds: string[] = []
194
195 for (const policy of role.policies) {
196 policyIds.push(policy.id)
197
198 if (!resourceMap.has(policy.resource)) {
199 resourceMap.set(policy.resource, new Set())
200 }
201 resourceMap.get(policy.resource)!.add(policy.operation)
202
203 tags.push(`rbac_policy:${policy.id}`)
204 }
205 }
206
207 return resourceMap
208 },
209 {
210 container,
211 key: roleId,
212 tags,
213 ttl: 60 * 60 * 24 * 7,
214 providers: ["cache-memory"],
215 }
216 )
217 }
218
219 /**
220 * Fetches policies for multiple roles by composing individually cached role queries.
221 */
222 async function fetchRolePolicies(
223 roleIds: string[],
224 container: MedusaContainer
225 ): Promise<RolePoliciesCache> {
226 const rolePoliciesMap: RolePoliciesCache = new Map()
227
228 await Promise.all(
229 roleIds.map(async (roleId) => {
230 const resourceMap = await fetchSingleRolePolicies(roleId, container)
231 rolePoliciesMap.set(roleId, resourceMap)
232 })
233 )
234
235 return rolePoliciesMap
236 }