1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import jwt from "jsonwebtoken"
3 import {
4 adminHeaders,
5 createAdminUser,
6 } from "../../../../helpers/create-admin-user"
7 import { generateTotpCode } from "../../../../../packages/modules/auth/src/utils/totp"
8
9 jest.setTimeout(100000)
10
11 const EMAIL = "admin@medusa.js"
12 const PASSWORD = "somepassword"
13 const OTHER_EMAIL = "other-admin@medusa.js"
14
15 const otherAdminHeaders = { headers: {} } as {
16 headers: Record<string, string>
17 }
18
19 const enrollTotpFactor = async (api) => {
20 const setup = await api.post(
21 "/auth/mfa/factors",
22 { provider: "totp", label: "Authenticator app" },
23 adminHeaders
24 )
25
26 const verified = await api.post(
27 `/auth/mfa/factors/${setup.data.mfa_factor.id}/verify`,
28 { code: generateTotpCode({ secret: setup.data.secret }) },
29 adminHeaders
30 )
31
32 expect(verified.data.mfa_factor.status).toEqual("enabled")
33
34 return {
35 secret: setup.data.secret as string,
36 factorId: setup.data.mfa_factor.id as string,
37 }
38 }
39
40 // Logging in with an enabled factor returns an actorless token that is only good
41 // for completing the MFA challenge.
42 const loginWithoutCompletingMfa = async (api) => {
43 const login = await api.post("/auth/user/emailpass", {
44 email: EMAIL,
45 password: PASSWORD,
46 })
47
48 expect(login.data.mfa_required).toBe(true)
49
50 const decoded = jwt.decode(login.data.token) as Record<string, unknown>
51 expect(decoded.actor_id).toEqual("")
52
53 return {
54 challenge: login.data.mfa_challenge,
55 headers: { headers: { authorization: `Bearer ${login.data.token}` } },
56 }
57 }
58
59 const completeMfa = async (api, secret: string) => {
60 const pending = await loginWithoutCompletingMfa(api)
61
62 const completed = await api.post(
63 `/auth/mfa/challenges/${pending.challenge.id}/verify`,
64 { method: "totp", code: generateTotpCode({ secret }) },
65 pending.headers
66 )
67
68 return {
69 headers: { headers: { authorization: `Bearer ${completed.data.token}` } },
70 }
71 }
72
73 medusaIntegrationTestRunner({
74 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
75 beforeAll(async () => {
76 await createAdminUser(dbConnection, adminHeaders, getContainer())
77 await createAdminUser(dbConnection, otherAdminHeaders, getContainer(), {
78 email: OTHER_EMAIL,
79 })
80
81 await dbUtils.snapshot()
82 })
83
84 describe("An identity without MFA enabled", () => {
85 it("authenticates and manages factors without completing a challenge", async () => {
86 const login = await api.post("/auth/user/emailpass", {
87 email: EMAIL,
88 password: PASSWORD,
89 })
90
91 expect(login.data.mfa_required).toBeUndefined()
92
93 const decoded = jwt.decode(login.data.token) as Record<string, unknown>
94 expect(decoded.mfa_enabled).toBe(false)
95 expect(decoded.mfa_challenge_completed_at).toBeNull()
96
97 const headers = {
98 headers: { authorization: `Bearer ${login.data.token}` },
99 }
100
101 const me = await api.get("/admin/users/me", headers)
102 expect(me.status).toEqual(200)
103
104 const factors = await api.get("/auth/mfa/factors", headers)
105 expect(factors.status).toEqual(200)
106 expect(factors.data.mfa_factors).toEqual([])
107
108 // Enrolling the first factor has no challenge to complete first.
109 const setup = await api.post(
110 "/auth/mfa/factors",
111 { provider: "totp", label: "Authenticator app" },
112 headers
113 )
114 expect(setup.status).toEqual(200)
115
116 const verified = await api.post(
117 `/auth/mfa/factors/${setup.data.mfa_factor.id}/verify`,
118 { code: generateTotpCode({ secret: setup.data.secret }) },
119 headers
120 )
121 expect(verified.data.mfa_factor.status).toEqual("enabled")
122
123 // The session that enabled MFA can still read its recovery codes.
124 const codes = await api.post(
125 "/auth/mfa/recovery-codes",
126 { count: 10 },
127 headers
128 )
129 expect(codes.status).toEqual(200)
130 expect(codes.data.recovery_codes).toHaveLength(10)
131 })
132 })
133
134 describe("MFA routes with an incomplete MFA challenge", () => {
135 it("does not generate recovery codes", async () => {
136 await enrollTotpFactor(api)
137
138 const pending = await loginWithoutCompletingMfa(api)
139
140 const err = await api
141 .post("/auth/mfa/recovery-codes", { count: 10 }, pending.headers)
142 .catch((e) => e)
143
144 expect(err.response.status).toEqual(401)
145
146 // No codes exist, so `recovery_code` is not offered on a new challenge.
147 const nextLogin = await loginWithoutCompletingMfa(api)
148 expect(nextLogin.challenge.methods).toEqual(["totp"])
149 })
150
151 it("does not list factors", async () => {
152 await enrollTotpFactor(api)
153
154 const pending = await loginWithoutCompletingMfa(api)
155
156 const err = await api
157 .get("/auth/mfa/factors", pending.headers)
158 .catch((e) => e)
159
160 expect(err.response.status).toEqual(401)
161 })
162
163 it("does not enroll an additional factor", async () => {
164 await enrollTotpFactor(api)
165
166 const pending = await loginWithoutCompletingMfa(api)
167
168 const err = await api
169 .post(
170 "/auth/mfa/factors",
171 { provider: "totp", label: "Another authenticator" },
172 pending.headers
173 )
174 .catch((e) => e)
175
176 expect(err.response.status).toEqual(401)
177 })
178
179 it("does not disable an enabled factor", async () => {
180 const { factorId } = await enrollTotpFactor(api)
181
182 const pending = await loginWithoutCompletingMfa(api)
183
184 const err = await api
185 .delete(`/auth/mfa/factors/${factorId}`, {
186 ...pending.headers,
187 data: {},
188 })
189 .catch((e) => e)
190
191 expect(err.response.status).toEqual(401)
192
193 // The factor is untouched, so MFA is still required on the next login.
194 const login = await api.post("/auth/user/emailpass", {
195 email: EMAIL,
196 password: PASSWORD,
197 })
198
199 expect(login.data.mfa_required).toBe(true)
200 })
201 })
202
203 describe("The token issued before an MFA challenge is completed", () => {
204 it("still refreshes into a token that requires the challenge", async () => {
205 await enrollTotpFactor(api)
206
207 const pending = await loginWithoutCompletingMfa(api)
208
209 const refreshed = await api.post(
210 "/auth/token/refresh",
211 {},
212 pending.headers
213 )
214
215 expect(refreshed.status).toEqual(200)
216 expect(refreshed.data.mfa_required).toBe(true)
217 expect(
218 (jwt.decode(refreshed.data.token) as Record<string, unknown>)
219 .mfa_challenge_completed_at
220 ).toBeNull()
221
222 const err = await api
223 .post(
224 "/auth/mfa/recovery-codes",
225 { count: 10 },
226 { headers: { authorization: `Bearer ${refreshed.data.token}` } }
227 )
228 .catch((e) => e)
229
230 expect(err.response.status).toEqual(401)
231 })
232 })
233
234 describe("MFA challenge ownership", () => {
235 it("does not verify a challenge belonging to another auth identity", async () => {
236 const { secret } = await enrollTotpFactor(api)
237
238 const pending = await loginWithoutCompletingMfa(api)
239 const code = generateTotpCode({ secret })
240
241 const err = await api
242 .post(
243 `/auth/mfa/challenges/${pending.challenge.id}/verify`,
244 { method: "totp", code },
245 otherAdminHeaders
246 )
247 .catch((e) => e)
248
249 expect(err.response.status).toEqual(404)
250
251 // The rejected attempt did not consume or complete the challenge.
252 const verified = await api.post(
253 `/auth/mfa/challenges/${pending.challenge.id}/verify`,
254 { method: "totp", code },
255 pending.headers
256 )
257
258 expect(verified.status).toEqual(200)
259 })
260 })
261
262 describe("MFA routes with a completed MFA challenge", () => {
263 it("lists factors, generates recovery codes and disables a factor", async () => {
264 const { secret, factorId } = await enrollTotpFactor(api)
265
266 const session = await completeMfa(api, secret)
267
268 const factors = await api.get("/auth/mfa/factors", session.headers)
269 expect(factors.status).toEqual(200)
270 expect(factors.data.mfa_factors).toEqual([
271 expect.objectContaining({ id: factorId, status: "enabled" }),
272 ])
273
274 const codes = await api.post(
275 "/auth/mfa/recovery-codes",
276 { count: 10 },
277 session.headers
278 )
279 expect(codes.status).toEqual(200)
280 expect(codes.data.recovery_codes).toHaveLength(10)
281
282 const disabled = await api.delete(`/auth/mfa/factors/${factorId}`, {
283 ...session.headers,
284 data: {},
285 })
286 expect(disabled.data.mfa_factor.status).toEqual("disabled")
287 })
288
289 it("records when the challenge was completed and preserves it on refresh", async () => {
290 const { secret } = await enrollTotpFactor(api)
291
292 const session = await completeMfa(api, secret)
293
294 const completedAt = (
295 jwt.decode(
296 session.headers.headers.authorization.replace("Bearer ", "")
297 ) as Record<string, unknown>
298 ).mfa_challenge_completed_at
299
300 expect(completedAt).toEqual(expect.any(String))
301
302 const refreshed = await api.post(
303 "/auth/token/refresh",
304 {},
305 session.headers
306 )
307
308 expect(
309 (jwt.decode(refreshed.data.token) as Record<string, unknown>)
310 .mfa_challenge_completed_at
311 ).toEqual(completedAt)
312
313 const codes = await api.post(
314 "/auth/mfa/recovery-codes",
315 { count: 10 },
316 { headers: { authorization: `Bearer ${refreshed.data.token}` } }
317 )
318
319 expect(codes.status).toEqual(200)
320 })
321
322 it("generates recovery codes for an identity that has no actor yet", async () => {
323 const email = "no-actor@medusa.js"
324 const password = "somepassword"
325
326 // Registering yields a token for an auth identity with no actor behind
327 // it, which is enough to enroll the first factor.
328 const registered = await api.post("/auth/user/emailpass/register", {
329 email,
330 password,
331 })
332
333 const registrationHeaders = {
334 headers: { authorization: `Bearer ${registered.data.token}` },
335 }
336
337 expect(
338 (jwt.decode(registered.data.token) as Record<string, unknown>)
339 .actor_id
340 ).toEqual("")
341
342 const setup = await api.post(
343 "/auth/mfa/factors",
344 { provider: "totp", label: "Authenticator app" },
345 registrationHeaders
346 )
347
348 await api.post(
349 `/auth/mfa/factors/${setup.data.mfa_factor.id}/verify`,
350 { code: generateTotpCode({ secret: setup.data.secret }) },
351 registrationHeaders
352 )
353
354 const login = await api.post("/auth/user/emailpass", {
355 email,
356 password,
357 })
358
359 const completed = await api.post(
360 `/auth/mfa/challenges/${login.data.mfa_challenge.id}/verify`,
361 {
362 method: "totp",
363 code: generateTotpCode({ secret: setup.data.secret }),
364 },
365 { headers: { authorization: `Bearer ${login.data.token}` } }
366 )
367
368 // Still no actor, but the MFA challenge is completed.
369 expect(
370 (jwt.decode(completed.data.token) as Record<string, unknown>).actor_id
371 ).toEqual("")
372
373 const codes = await api.post(
374 "/auth/mfa/recovery-codes",
375 { count: 10 },
376 { headers: { authorization: `Bearer ${completed.data.token}` } }
377 )
378
379 expect(codes.status).toEqual(200)
380 expect(codes.data.recovery_codes).toHaveLength(10)
381 })
382 })
383 },
384 })