1 import { Modules } from "@medusajs/framework/utils"
2 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
3 import { IAuthModuleService } from "@medusajs/types"
4 import crypto from "crypto"
5 import jwt from "jsonwebtoken"
6 import { http, HttpResponse } from "msw"
7 import { setupServer } from "msw/node"
8
9 jest.setTimeout(30000)
10
11 const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
12 modulusLength: 2048,
13 })
14
15 const KID = "test-kid"
16
17 const jwkPublic = {
18 ...(publicKey.export({ format: "jwk" }) as Record<string, string>),
19 kid: KID,
20 use: "sig",
21 alg: "RS256",
22 }
23
24 const TOKEN_ENDPOINT = "https://medusa.cloud/oauth/token"
25 const JWKS_URI = "https://medusa.cloud/oauth/jwks"
26
27 const createMockIdToken = (payload: Record<string, any> = {}) => {
28 return jwt.sign(
29 {
30 sub: "user-123",
31 email: "john@doe.com",
32 email_verified: true,
33 name: "John Doe",
34 given_name: "John",
35 family_name: "Doe",
36 aud: "test-environment",
37 ...payload,
38 },
39 privateKey.export({ format: "pem", type: "pkcs8" }),
40 {
41 algorithm: "RS256",
42 keyid: KID,
43 expiresIn: "1d",
44 }
45 )
46 }
47
48 type TokenResponse = {
49 status?: number
50 body: Record<string, unknown>
51 }
52
53 let nextTokenResponse: TokenResponse | null = null
54 let lastTokenRequest: {
55 url: string
56 method: string
57 headers: Record<string, string>
58 body: URLSearchParams
59 } | null = null
60
61 const server = setupServer(
62 http.get(JWKS_URI, () => HttpResponse.json({ keys: [jwkPublic] })),
63
64 http.post(TOKEN_ENDPOINT, async ({ request }) => {
65 const rawBody = await request.text()
66 lastTokenRequest = {
67 url: request.url,
68 method: request.method,
69 headers: Object.fromEntries(request.headers.entries()),
70 body: new URLSearchParams(rawBody),
71 }
72
73 if (!nextTokenResponse) {
74 return HttpResponse.json({}, { status: 500 })
75 }
76 const { status = 200, body } = nextTokenResponse
77 return HttpResponse.json(body, { status })
78 })
79 )
80
81 beforeAll(() => server.listen({ onUnhandledRequest: "warn" }))
82 afterAll(() => server.close())
83
84 const mockCache = new Map()
85 const inMemoryCache = {
86 get: async (key: string) => mockCache.get(key) ?? null,
87 set: async (key: string, data: any, ttl?: number) => {
88 mockCache.set(key, data)
89 },
90 invalidate: async (key: string) => {
91 mockCache.delete(key)
92 },
93 clear: async () => {
94 mockCache.clear()
95 },
96 }
97
98 moduleIntegrationTestRunner<IAuthModuleService>({
99 moduleName: Modules.AUTH,
100 moduleOptions: {
101 cloud: {
102 oauth_authorize_endpoint: "https://medusa.cloud/oauth/authorize",
103 oauth_token_endpoint: TOKEN_ENDPOINT,
104 oauth_jwks_uri: JWKS_URI,
105 oauth_audience: "test-environment",
106 api_key: "test-api-key",
107 callback_url: "https://store.app/oauth/callback",
108 environment_handle: "test-environment",
109 },
110 },
111 moduleDependencies: [Modules.CACHE],
112 injectedDependencies: {
113 [Modules.CACHE]: inMemoryCache,
114 },
115 testSuite: ({ service }) =>
116 describe("Medusa Cloud Auth provider", () => {
117 afterEach(() => {
118 mockCache.clear()
119 nextTokenResponse = null
120 lastTokenRequest = null
121 server.resetHandlers(
122 http.get(JWKS_URI, () => HttpResponse.json({ keys: [jwkPublic] })),
123 http.post(TOKEN_ENDPOINT, async ({ request }) => {
124 const rawBody = await request.text()
125 lastTokenRequest = {
126 url: request.url,
127 method: request.method,
128 headers: Object.fromEntries(request.headers.entries()),
129 body: new URLSearchParams(rawBody),
130 }
131 if (!nextTokenResponse) {
132 return HttpResponse.json({}, { status: 500 })
133 }
134 const { status = 200, body } = nextTokenResponse
135 return HttpResponse.json(body, { status })
136 })
137 )
138 })
139
140 describe("authenticate", () => {
141 it("should redirect to authorization URL with default callback URL", async () => {
142 const response = await service.authenticate("cloud", {
143 query: {},
144 body: {},
145 })
146
147 expect(response.success).toBe(true)
148 expect(response.location).toBeDefined()
149 const query = new URL(response.location!).searchParams
150 expect(query.size).toBe(5)
151 expect(query.get("redirect_uri")).toBe(
152 "https://store.app/oauth/callback"
153 )
154 expect(query.get("client_id")).toBe("test-environment")
155 expect(query.get("response_type")).toBe("code")
156 expect(query.get("scope")).toBe("email profile openid")
157 expect(query.get("state")?.length).toBeGreaterThan(0)
158 })
159
160 it("should redirect to authorization URL with overriden callback URL", async () => {
161 const response = await service.authenticate("cloud", {
162 query: {},
163 body: {
164 callback_url: "https://overriden-callback.app/oauth/callback",
165 },
166 })
167
168 expect(response.success).toBe(true)
169 expect(response.location).toBeDefined()
170 const query = new URL(response.location!).searchParams
171 expect(query.size).toBe(5)
172 expect(query.get("redirect_uri")).toBe(
173 "https://overriden-callback.app/oauth/callback"
174 )
175 expect(query.get("client_id")).toBe("test-environment")
176 expect(query.get("response_type")).toBe("code")
177 expect(query.get("scope")).toBe("email profile openid")
178 expect(query.get("state")?.length).toBeGreaterThan(0)
179 })
180 })
181
182 describe("validateCallback", () => {
183 let state: string
184
185 beforeEach(async () => {
186 const response = await service.authenticate("cloud", {
187 query: {},
188 body: {},
189 })
190
191 expect(response.success).toBe(true)
192 expect(response.location).toBeDefined()
193 const query = new URL(response.location!).searchParams
194 state = query.get("state")!
195
196 nextTokenResponse = {
197 body: { id_token: createMockIdToken() },
198 }
199 })
200
201 it("should validate a valid callback", async () => {
202 const response = await service.validateCallback("cloud", {
203 query: {
204 code: "code1",
205 state: state,
206 },
207 })
208 expect(response).toMatchObject({
209 success: true,
210 authIdentity: {
211 provider_identities: [
212 {
213 entity_id: "user-123",
214 provider: "cloud",
215 user_metadata: {
216 email: "john@doe.com",
217 given_name: "John",
218 family_name: "Doe",
219 name: "John Doe",
220 },
221 },
222 ],
223 },
224 })
225
226 expect(lastTokenRequest).not.toBeNull()
227 expect(lastTokenRequest!.url).toBe(TOKEN_ENDPOINT)
228 expect(lastTokenRequest!.method).toBe("POST")
229 expect(lastTokenRequest!.headers["content-type"]).toContain(
230 "application/x-www-form-urlencoded"
231 )
232 expect(lastTokenRequest!.body.get("client_id")).toBe("test-environment")
233 expect(lastTokenRequest!.body.get("client_secret")).toBe("test-api-key")
234 expect(lastTokenRequest!.body.get("code")).toBe("code1")
235 expect(lastTokenRequest!.body.get("redirect_uri")).toBe(
236 "https://store.app/oauth/callback"
237 )
238 expect(lastTokenRequest!.body.get("grant_type")).toBe(
239 "authorization_code"
240 )
241 })
242
243 it("should consume the state so it can only be used once", async () => {
244 const first = await service.validateCallback("cloud", {
245 query: {
246 code: "code1",
247 state: state,
248 },
249 })
250 expect(first.success).toBe(true)
251
252 // The state is single-use: replaying it must fail because it was
253 // consumed (deleted) on the first read.
254 const second = await service.validateCallback("cloud", {
255 query: {
256 code: "code1",
257 state: state,
258 },
259 })
260 expect(second.success).toBe(false)
261 expect(second.error).toBe("No state provided, or session expired")
262 })
263
264 it("should return an error if the code is not provided", async () => {
265 const response = await service.validateCallback("cloud", {
266 query: {
267 state: state,
268 },
269 })
270
271 expect(response.success).toBe(false)
272 expect(response.error).toBe("No code provided")
273 })
274
275 it("should return an error if the state is not provided", async () => {
276 const response = await service.validateCallback("cloud", {
277 query: {
278 code: "code1",
279 },
280 })
281
282 expect(response.success).toBe(false)
283 expect(response.error).toBe("No state provided, or session expired")
284 })
285
286 it("should return an error if the state doesn't match the stored state", async () => {
287 const response = await service.validateCallback("cloud", {
288 query: {
289 code: "code1",
290 state: "other-state",
291 },
292 })
293
294 expect(response.success).toBe(false)
295 expect(response.error).toBe("No state provided, or session expired")
296 })
297
298 it("should return an error if the token exchange does not return an id_token", async () => {
299 nextTokenResponse = { body: {} }
300 const response = await service.validateCallback("cloud", {
301 query: {
302 code: "code1",
303 state: state,
304 },
305 })
306
307 expect(response.success).toBe(false)
308 expect(response.error).toBe("No id_token")
309 })
310
311 it("should reject a forged id_token whose signature does not match the JWKS", async () => {
312 nextTokenResponse = {
313 body: {
314 id_token: jwt.sign(
315 {
316 sub: "attacker-sub",
317 email: "attacker@example.com",
318 email_verified: true,
319 aud: "test-environment",
320 },
321 "attacker-secret",
322 { algorithm: "HS256", keyid: KID, expiresIn: "1d" }
323 ),
324 },
325 }
326
327 const response = await service.validateCallback("cloud", {
328 query: {
329 code: "code1",
330 state: state,
331 },
332 })
333
334 expect(response.success).toBe(false)
335 expect(response.error).toMatch(/Could not verify id_token/i)
336 })
337
338 it("should return an error if the email is not verified", async () => {
339 nextTokenResponse = {
340 body: {
341 id_token: createMockIdToken({ email_verified: false }),
342 },
343 }
344 const response = await service.validateCallback("cloud", {
345 query: {
346 code: "code1",
347 state: state,
348 },
349 })
350
351 expect(response.success).toBe(false)
352 expect(response.error).toBe(
353 "Email not verified, cannot proceed with authentication"
354 )
355 })
356 })
357 }),
358 })
359
360 moduleIntegrationTestRunner<IAuthModuleService>({
361 moduleName: Modules.AUTH,
362 moduleOptions: {},
363 moduleDependencies: [Modules.CACHE],
364 injectedDependencies: {
365 [Modules.CACHE]: inMemoryCache,
366 },
367 testSuite: ({ service }) =>
368 describe("Medusa Cloud Auth provider - when cloud options are not provided", () => {
369 it("should not enable Medusa Cloud Email provider", async () => {
370 const error = await service
371 .authenticate("cloud", {
372 query: {},
373 body: {},
374 })
375 .catch((e) => e)
376
377 expect(error).toEqual({
378 success: false,
379 error: expect.stringContaining(
380 "Unable to retrieve the auth provider with id: cloud"
381 ),
382 })
383 })
384 }),
385 })
386
387 moduleIntegrationTestRunner<IAuthModuleService>({
388 moduleName: Modules.AUTH,
389 moduleOptions: {
390 cloud: {
391 oauth_authorize_endpoint: "https://medusa.cloud/oauth/authorize",
392 oauth_token_endpoint: TOKEN_ENDPOINT,
393 oauth_jwks_uri: JWKS_URI,
394 oauth_audience: "test-environment",
395 api_key: "test-api-key",
396 callback_url: "https://store.app/oauth/callback",
397 environment_handle: "test-environment",
398 disabled: true,
399 },
400 },
401 moduleDependencies: [Modules.CACHE],
402 injectedDependencies: {
403 [Modules.CACHE]: inMemoryCache,
404 },
405 testSuite: ({ service }) =>
406 describe("Medusa Cloud Auth provider - when cloud auth is disabled", () => {
407 it("should not enable Medusa Cloud Email provider", async () => {
408 const error = await service
409 .authenticate("cloud", {
410 query: {},
411 body: {},
412 })
413 .catch((e) => e)
414
415 expect(error).toEqual({
416 success: false,
417 error: expect.stringContaining(
418 "Unable to retrieve the auth provider with id: cloud"
419 ),
420 })
421 })
422 }),
423 })