1 import {
2 AuthenticationInput,
3 Logger,
4 OidcAuthProviderOptions,
5 } from "@medusajs/framework/types"
6 import { MedusaError } from "@medusajs/framework/utils"
7 import { OidcAuthService } from "../../src/services/oidc"
8
9 const ISSUER = "https://idp.example.com"
10 const CALLBACK_URL = "https://app.example.com/callback"
11
12 const baseOptions = (
13 overrides: Partial<OidcAuthProviderOptions> = {}
14 ): OidcAuthProviderOptions => ({
15 issuer: ISSUER,
16 client_id: "client-123",
17 client_secret: "super-secret",
18 callback_url: CALLBACK_URL,
19 ...overrides,
20 })
21
22 type MockEngine = {
23 buildAuthorizationUrl: jest.Mock
24 exchangeCode: jest.Mock
25 mapClaims: jest.Mock
26 }
27
28 type MockAuthIdentityService = {
29 setState: jest.Mock
30 getState: jest.Mock
31 retrieve: jest.Mock
32 create: jest.Mock
33 update: jest.Mock
34 }
35
36 const createLogger = (): Logger =>
37 ({
38 error: jest.fn(),
39 warn: jest.fn(),
40 info: jest.fn(),
41 debug: jest.fn(),
42 } as unknown as Logger)
43
44 const createAuthIdentityService = (): MockAuthIdentityService => ({
45 setState: jest.fn().mockResolvedValue(undefined),
46 getState: jest.fn(),
47 retrieve: jest.fn(),
48 create: jest.fn(),
49 update: jest.fn(),
50 })
51
52 const createService = (
53 options: OidcAuthProviderOptions = baseOptions()
54 ): { service: OidcAuthService; engine: MockEngine } => {
55 const service = new OidcAuthService({ logger: createLogger() }, options)
56
57 const engine: MockEngine = {
58 buildAuthorizationUrl: jest.fn(),
59 exchangeCode: jest.fn(),
60 mapClaims: jest.fn(),
61 }
62
63 // Replace the real engine with a mock so no network I/O happens.
64 ;(service as any).engine_ = engine
65
66 return { service, engine }
67 }
68
69 describe("OidcAuthService", () => {
70 describe("validateOptions", () => {
71 it("throws when issuer is missing", () => {
72 expect(() =>
73 OidcAuthService.validateOptions(baseOptions({ issuer: "" }))
74 ).toThrow(/requires an 'issuer'/)
75 })
76
77 it("throws when client_id is missing", () => {
78 expect(() =>
79 OidcAuthService.validateOptions(baseOptions({ client_id: "" }))
80 ).toThrow(/requires a 'client_id'/)
81 })
82
83 it("throws when callback_url is missing", () => {
84 expect(() =>
85 OidcAuthService.validateOptions(baseOptions({ callback_url: "" }))
86 ).toThrow(/requires a 'callback_url'/)
87 })
88
89 it("throws when the issuer is not https and not localhost", () => {
90 expect(() =>
91 OidcAuthService.validateOptions(
92 baseOptions({ issuer: "http://idp.example.com" })
93 )
94 ).toThrow(/must use https/)
95 })
96
97 it("allows an http issuer on localhost", () => {
98 expect(() =>
99 OidcAuthService.validateOptions(
100 baseOptions({ issuer: "http://localhost:8080" })
101 )
102 ).not.toThrow()
103 })
104
105 it("does not throw for valid options", () => {
106 expect(() => OidcAuthService.validateOptions(baseOptions())).not.toThrow()
107 })
108 })
109
110 describe("register", () => {
111 it("throws NOT_ALLOWED", async () => {
112 const { service } = createService()
113 await expect(
114 service.register({} as AuthenticationInput)
115 ).rejects.toMatchObject({
116 type: MedusaError.Types.NOT_ALLOWED,
117 })
118 })
119 })
120
121 describe("authenticate", () => {
122 it("stores single-use state with the configured TTL and returns the location", async () => {
123 const { service, engine } = createService(
124 baseOptions({ state_ttl_seconds: 900, scopes: ["openid", "email"] })
125 )
126 const authIdentityService = createAuthIdentityService()
127
128 engine.buildAuthorizationUrl.mockResolvedValue({
129 url: "https://idp.example.com/authorize?state=abc",
130 nonce: "nonce-value",
131 codeVerifier: "verifier-value",
132 })
133
134 const result = await service.authenticate(
135 { body: {} } as AuthenticationInput,
136 authIdentityService as any
137 )
138
139 expect(result.success).toBe(true)
140 expect(result.location).toBe(
141 "https://idp.example.com/authorize?state=abc"
142 )
143
144 expect(engine.buildAuthorizationUrl).toHaveBeenCalledWith(
145 expect.objectContaining({
146 callbackUrl: CALLBACK_URL,
147 scopes: ["openid", "email"],
148 state: expect.any(String),
149 })
150 )
151
152 expect(authIdentityService.setState).toHaveBeenCalledTimes(1)
153 const [stateKey, stateValue, ttl] =
154 authIdentityService.setState.mock.calls[0]
155 expect(typeof stateKey).toBe("string")
156 expect(stateValue).toEqual({
157 callback_url: CALLBACK_URL,
158 nonce: "nonce-value",
159 code_verifier: "verifier-value",
160 })
161 expect(ttl).toBe(900)
162 })
163
164 it("defaults the state TTL to 600 seconds", async () => {
165 const { service, engine } = createService()
166 const authIdentityService = createAuthIdentityService()
167
168 engine.buildAuthorizationUrl.mockResolvedValue({
169 url: "https://idp.example.com/authorize",
170 nonce: "n",
171 codeVerifier: "v",
172 })
173
174 await service.authenticate(
175 { body: {} } as AuthenticationInput,
176 authIdentityService as any
177 )
178
179 expect(authIdentityService.setState.mock.calls[0][2]).toBe(600)
180 })
181
182 it("allows a body callback_url that is in the allowlist", async () => {
183 const override = "https://app.example.com/other"
184 const { service, engine } = createService(
185 baseOptions({ allowed_callback_urls: [CALLBACK_URL, override] })
186 )
187 const authIdentityService = createAuthIdentityService()
188
189 engine.buildAuthorizationUrl.mockResolvedValue({
190 url: "https://idp.example.com/authorize",
191 nonce: "n",
192 codeVerifier: "v",
193 })
194
195 const result = await service.authenticate(
196 { body: { callback_url: override } } as unknown as AuthenticationInput,
197 authIdentityService as any
198 )
199
200 expect(result.success).toBe(true)
201 expect(engine.buildAuthorizationUrl).toHaveBeenCalledWith(
202 expect.objectContaining({ callbackUrl: override })
203 )
204 })
205
206 it("rejects a body callback_url that is not in the allowlist without echoing it", async () => {
207 const { service, engine } = createService(
208 baseOptions({ allowed_callback_urls: [CALLBACK_URL] })
209 )
210 const authIdentityService = createAuthIdentityService()
211
212 const result = await service.authenticate(
213 {
214 body: { callback_url: "https://evil.example.com/callback" },
215 } as unknown as AuthenticationInput,
216 authIdentityService as any
217 )
218
219 expect(result.success).toBe(false)
220 expect(result.error).not.toContain("evil.example.com")
221 expect(engine.buildAuthorizationUrl).not.toHaveBeenCalled()
222 expect(authIdentityService.setState).not.toHaveBeenCalled()
223 })
224
225 it("accepts any body callback_url when no allowlist is configured", async () => {
226 const override = "https://other.example.com/callback"
227 const { service, engine } = createService()
228 const authIdentityService = createAuthIdentityService()
229
230 engine.buildAuthorizationUrl.mockResolvedValue({
231 url: "https://idp.example.com/authorize",
232 nonce: "n",
233 codeVerifier: "v",
234 })
235
236 const result = await service.authenticate(
237 { body: { callback_url: override } } as unknown as AuthenticationInput,
238 authIdentityService as any
239 )
240
241 expect(result.success).toBe(true)
242 expect(engine.buildAuthorizationUrl).toHaveBeenCalledWith(
243 expect.objectContaining({ callbackUrl: override })
244 )
245 })
246 })
247
248 describe("validateCallback", () => {
249 const validState = {
250 callback_url: CALLBACK_URL,
251 nonce: "nonce-value",
252 code_verifier: "verifier-value",
253 }
254
255 it("creates a new auth identity on NOT_FOUND", async () => {
256 const { service, engine } = createService()
257 const authIdentityService = createAuthIdentityService()
258
259 authIdentityService.getState.mockResolvedValue(validState)
260 engine.exchangeCode.mockResolvedValue({
261 claims: { sub: "user-1", email: "a@acme.com" },
262 tokens: {},
263 })
264 engine.mapClaims.mockReturnValue({
265 entityId: "user-1",
266 userMetadata: { email: "a@acme.com" },
267 })
268 authIdentityService.retrieve.mockRejectedValue(
269 new MedusaError(MedusaError.Types.NOT_FOUND, "not found")
270 )
271 authIdentityService.create.mockResolvedValue({ id: "authid_1" })
272
273 const result = await service.validateCallback(
274 {
275 query: { code: "the-code", state: "state-key" },
276 } as unknown as AuthenticationInput,
277 authIdentityService as any
278 )
279
280 expect(result.success).toBe(true)
281 expect(result.authIdentity).toEqual({ id: "authid_1" })
282 expect(authIdentityService.getState).toHaveBeenCalledTimes(1)
283 expect(authIdentityService.getState).toHaveBeenCalledWith("state-key")
284 expect(engine.exchangeCode).toHaveBeenCalledWith(
285 expect.objectContaining({
286 params: { code: "the-code", state: "state-key" },
287 nonce: "nonce-value",
288 codeVerifier: "verifier-value",
289 callbackUrl: CALLBACK_URL,
290 state: "state-key",
291 })
292 )
293 expect(authIdentityService.create).toHaveBeenCalledWith({
294 entity_id: "user-1",
295 user_metadata: { email: "a@acme.com" },
296 })
297 expect(authIdentityService.update).not.toHaveBeenCalled()
298 })
299
300 it("updates the existing auth identity to refresh claims", async () => {
301 const { service, engine } = createService()
302 const authIdentityService = createAuthIdentityService()
303
304 authIdentityService.getState.mockResolvedValue(validState)
305 engine.exchangeCode.mockResolvedValue({
306 claims: { sub: "user-1" },
307 tokens: {},
308 })
309 engine.mapClaims.mockReturnValue({
310 entityId: "user-1",
311 userMetadata: { email: "new@acme.com" },
312 })
313 authIdentityService.retrieve.mockResolvedValue({ id: "authid_1" })
314 authIdentityService.update.mockResolvedValue({
315 id: "authid_1",
316 user_metadata: { email: "new@acme.com" },
317 })
318
319 const result = await service.validateCallback(
320 {
321 query: { code: "the-code", state: "state-key" },
322 } as unknown as AuthenticationInput,
323 authIdentityService as any
324 )
325
326 expect(result.success).toBe(true)
327 expect(authIdentityService.update).toHaveBeenCalledWith("user-1", {
328 user_metadata: { email: "new@acme.com" },
329 })
330 expect(authIdentityService.create).not.toHaveBeenCalled()
331 })
332
333 it("fails when the state is missing or expired", async () => {
334 const { service, engine } = createService()
335 const authIdentityService = createAuthIdentityService()
336
337 authIdentityService.getState.mockResolvedValue(null)
338
339 const result = await service.validateCallback(
340 {
341 query: { code: "the-code", state: "state-key" },
342 } as unknown as AuthenticationInput,
343 authIdentityService as any
344 )
345
346 expect(result).toEqual({
347 success: false,
348 error: "No state provided, or session expired",
349 })
350 expect(engine.exchangeCode).not.toHaveBeenCalled()
351 })
352
353 it("fails when no state key is provided", async () => {
354 const { service } = createService()
355 const authIdentityService = createAuthIdentityService()
356
357 const result = await service.validateCallback(
358 { query: { code: "the-code" } } as unknown as AuthenticationInput,
359 authIdentityService as any
360 )
361
362 expect(result).toEqual({
363 success: false,
364 error: "No state provided, or session expired",
365 })
366 expect(authIdentityService.getState).not.toHaveBeenCalled()
367 })
368
369 it("fails when no code is provided", async () => {
370 const { service } = createService()
371 const authIdentityService = createAuthIdentityService()
372
373 const result = await service.validateCallback(
374 { query: { state: "state-key" } } as unknown as AuthenticationInput,
375 authIdentityService as any
376 )
377
378 expect(result).toEqual({ success: false, error: "No code provided" })
379 })
380
381 it("handles an IdP error query param generically without reflecting it", async () => {
382 const { service } = createService()
383 const authIdentityService = createAuthIdentityService()
384
385 const result = await service.validateCallback(
386 {
387 query: {
388 error: "access_denied",
389 error_description: "<script>alert(1)</script>",
390 },
391 } as unknown as AuthenticationInput,
392 authIdentityService as any
393 )
394
395 expect(result.success).toBe(false)
396 expect(result.error).toBe("Authentication failed")
397 expect(result.error).not.toContain("script")
398 expect(authIdentityService.getState).not.toHaveBeenCalled()
399 })
400
401 it("returns a generic failure when the engine rejects the callback", async () => {
402 const { service, engine } = createService()
403 const authIdentityService = createAuthIdentityService()
404
405 authIdentityService.getState.mockResolvedValue(validState)
406 engine.exchangeCode.mockRejectedValue(
407 new MedusaError(
408 MedusaError.Types.UNAUTHORIZED,
409 "nonce mismatch detail that must not leak"
410 )
411 )
412
413 const result = await service.validateCallback(
414 {
415 query: { code: "the-code", state: "state-key" },
416 } as unknown as AuthenticationInput,
417 authIdentityService as any
418 )
419
420 expect(result.success).toBe(false)
421 expect(result.error).toBe("Authentication failed")
422 expect(result.error).not.toContain("nonce")
423 })
424 })
425 })