1 import { MedusaError } from "@medusajs/framework/utils"
2 import { Issuer } from "openid-client"
3 import { OidcEngine } from "../../src/engine/engine"
4 import { OidcEngineOptions } from "../../src/engine/types"
5
6 const ISSUER = "https://idp.example.com"
7 const AUTHORIZATION_ENDPOINT = "https://idp.example.com/authorize"
8 const TOKEN_ENDPOINT = "https://idp.example.com/token"
9 const JWKS_URI = "https://idp.example.com/jwks"
10 const CALLBACK_URL = "https://app.example.com/callback"
11
12 const baseOptions = (
13 overrides: Partial<OidcEngineOptions> = {}
14 ): OidcEngineOptions => ({
15 issuer: ISSUER,
16 client_id: "client-123",
17 client_secret: "super-secret",
18 callback_url: CALLBACK_URL,
19 authorization_endpoint: AUTHORIZATION_ENDPOINT,
20 token_endpoint: TOKEN_ENDPOINT,
21 jwks_uri: JWKS_URI,
22 ...overrides,
23 })
24
25 describe("OidcEngine", () => {
26 beforeEach(() => {
27 jest.restoreAllMocks()
28 })
29
30 describe("constructor validation", () => {
31 it("throws when the issuer is missing", () => {
32 expect(() => new OidcEngine({ ...baseOptions(), issuer: "" })).toThrow(
33 /requires an 'issuer'/
34 )
35 })
36
37 it("throws when client_id is missing", () => {
38 expect(() => new OidcEngine({ ...baseOptions(), client_id: "" })).toThrow(
39 /requires a 'client_id'/
40 )
41 })
42
43 it("throws when callback_url is missing", () => {
44 expect(
45 () => new OidcEngine({ ...baseOptions(), callback_url: "" })
46 ).toThrow(/requires a 'callback_url'/)
47 })
48
49 it("rejects a non-https issuer that isn't localhost", () => {
50 expect(
51 () => new OidcEngine(baseOptions({ issuer: "http://idp.example.com" }))
52 ).toThrow(/must use https/)
53 })
54
55 it("allows an http issuer on localhost", () => {
56 expect(
57 () =>
58 new OidcEngine(
59 baseOptions({
60 issuer: "http://localhost:4000",
61 authorization_endpoint: "http://localhost:4000/authorize",
62 token_endpoint: "http://localhost:4000/token",
63 jwks_uri: "http://localhost:4000/jwks",
64 })
65 )
66 ).not.toThrow()
67 })
68
69 it("rejects an http issuer on localhost in production", () => {
70 const nodeEnv = process.env.NODE_ENV
71 process.env.NODE_ENV = "production"
72
73 try {
74 expect(
75 () =>
76 new OidcEngine(
77 baseOptions({
78 issuer: "http://localhost:4000",
79 authorization_endpoint: "http://localhost:4000/authorize",
80 token_endpoint: "http://localhost:4000/token",
81 jwks_uri: "http://localhost:4000/jwks",
82 })
83 )
84 ).toThrow(/must use https/)
85 } finally {
86 process.env.NODE_ENV = nodeEnv
87 }
88 })
89
90 it("rejects a non-https endpoint override", () => {
91 expect(
92 () =>
93 new OidcEngine(
94 baseOptions({ token_endpoint: "http://idp.example.com/token" })
95 )
96 ).toThrow(/must use https/)
97 })
98 })
99
100 describe("buildAuthorizationUrl", () => {
101 it("builds an authorization URL with PKCE, nonce, and state (no discovery when endpoints are set)", async () => {
102 const discoverSpy = jest.spyOn(Issuer, "discover")
103 const engine = new OidcEngine(baseOptions())
104
105 const result = await engine.buildAuthorizationUrl({ state: "state-key" })
106
107 expect(discoverSpy).not.toHaveBeenCalled()
108
109 const url = new URL(result.url)
110 expect(`${url.origin}${url.pathname}`).toBe(AUTHORIZATION_ENDPOINT)
111 expect(url.searchParams.get("response_type")).toBe("code")
112 expect(url.searchParams.get("client_id")).toBe("client-123")
113 expect(url.searchParams.get("redirect_uri")).toBe(CALLBACK_URL)
114 expect(url.searchParams.get("scope")).toBe("openid email profile")
115 expect(url.searchParams.get("state")).toBe("state-key")
116 expect(url.searchParams.get("nonce")).toBe(result.nonce)
117 expect(url.searchParams.get("code_challenge")).toBeTruthy()
118 expect(url.searchParams.get("code_challenge_method")).toBe("S256")
119
120 // PKCE verifier is a high-entropy string (43-128 chars per RFC 7636).
121 expect(result.codeVerifier.length).toBeGreaterThanOrEqual(43)
122 expect(result.nonce.length).toBeGreaterThan(0)
123 })
124
125 it("uses the configured scopes and overridden callback URL", async () => {
126 const engine = new OidcEngine(
127 baseOptions({ scopes: ["openid", "email"] })
128 )
129
130 const result = await engine.buildAuthorizationUrl({
131 state: "state-key",
132 callbackUrl: "https://other.example.com/callback",
133 })
134
135 const url = new URL(result.url)
136 expect(url.searchParams.get("scope")).toBe("openid email")
137 expect(url.searchParams.get("redirect_uri")).toBe(
138 "https://other.example.com/callback"
139 )
140 })
141
142 it("generates a fresh nonce and code verifier on each call", async () => {
143 const engine = new OidcEngine(baseOptions())
144
145 const first = await engine.buildAuthorizationUrl({ state: "a" })
146 const second = await engine.buildAuthorizationUrl({ state: "b" })
147
148 expect(first.nonce).not.toBe(second.nonce)
149 expect(first.codeVerifier).not.toBe(second.codeVerifier)
150 })
151
152 it("throws when no state is provided", async () => {
153 const engine = new OidcEngine(baseOptions())
154 await expect(engine.buildAuthorizationUrl({ state: "" })).rejects.toThrow(
155 /'state' value is required/
156 )
157 })
158 })
159
160 describe("exchangeCode", () => {
161 it("throws when no code is provided", async () => {
162 const engine = new OidcEngine(baseOptions())
163
164 await expect(
165 engine.exchangeCode({
166 params: {},
167 nonce: "nonce",
168 codeVerifier: "verifier",
169 })
170 ).rejects.toThrow(/authorization 'code' is required/)
171 })
172
173 it("throws UNAUTHORIZED when the token response contains no ID token", async () => {
174 const engine = new OidcEngine(baseOptions())
175
176 // Simulate a token endpoint response without an id_token, which happens
177 // when the 'openid' scope isn't requested.
178 jest.spyOn(engine as any, "getClient_").mockResolvedValue({
179 callback: jest.fn().mockResolvedValue({
180 access_token: "access-token",
181 token_type: "Bearer",
182 }),
183 })
184
185 const error = await engine
186 .exchangeCode({
187 params: { code: "code-123" },
188 nonce: "nonce",
189 codeVerifier: "verifier",
190 })
191 .catch((e) => e)
192
193 expect(error).toBeInstanceOf(MedusaError)
194 expect(error.type).toBe(MedusaError.Types.UNAUTHORIZED)
195 expect(error.message).toMatch(
196 /did not return an ID token.*'openid' scope/
197 )
198 })
199 })
200
201 describe("client caching", () => {
202 it("builds the client once and reuses it across calls", async () => {
203 const engine = new OidcEngine(baseOptions())
204 const buildSpy = jest.spyOn(engine as any, "buildClient_")
205
206 await engine.buildAuthorizationUrl({ state: "one" })
207 await engine.buildAuthorizationUrl({ state: "two" })
208
209 const firstClient = await (engine as any).getClient_()
210 const secondClient = await (engine as any).getClient_()
211
212 expect(buildSpy).toHaveBeenCalledTimes(1)
213 expect(firstClient).toBe(secondClient)
214 })
215
216 it("shares a single client build between concurrent first calls", async () => {
217 const engine = new OidcEngine(baseOptions())
218 const buildSpy = jest.spyOn(engine as any, "buildClient_")
219
220 const [first, second] = await Promise.all([
221 (engine as any).getClient_(),
222 (engine as any).getClient_(),
223 ])
224
225 expect(buildSpy).toHaveBeenCalledTimes(1)
226 expect(first).toBe(second)
227 })
228
229 it("rebuilds the client after the discovery TTL lapses", async () => {
230 const discoveredIssuer = new Issuer({
231 issuer: ISSUER,
232 authorization_endpoint: AUTHORIZATION_ENDPOINT,
233 token_endpoint: TOKEN_ENDPOINT,
234 jwks_uri: JWKS_URI,
235 })
236 const discoverSpy = jest
237 .spyOn(Issuer, "discover")
238 .mockResolvedValue(discoveredIssuer)
239
240 const ttlMs = 1000
241
242 // No endpoint overrides -> discovery is used and the client's lifetime is
243 // aligned with the discovery cache TTL.
244 const engine = new OidcEngine({
245 issuer: ISSUER,
246 client_id: "client-123",
247 client_secret: "super-secret",
248 callback_url: CALLBACK_URL,
249 discovery_cache_ttl_ms: ttlMs,
250 })
251 const buildSpy = jest.spyOn(engine as any, "buildClient_")
252
253 const start = Date.now()
254 const nowSpy = jest.spyOn(Date, "now").mockReturnValue(start)
255
256 const firstClient = await (engine as any).getClient_()
257 const cachedClient = await (engine as any).getClient_()
258 expect(cachedClient).toBe(firstClient)
259 expect(buildSpy).toHaveBeenCalledTimes(1)
260 expect(discoverSpy).toHaveBeenCalledTimes(1)
261
262 // Advance past the TTL: both the client and discovery caches expire.
263 nowSpy.mockReturnValue(start + ttlMs + 1)
264
265 const rebuiltClient = await (engine as any).getClient_()
266 expect(rebuiltClient).not.toBe(firstClient)
267 expect(buildSpy).toHaveBeenCalledTimes(2)
268 expect(discoverSpy).toHaveBeenCalledTimes(2)
269 })
270
271 it("does not cache a failed client build", async () => {
272 jest
273 .spyOn(Issuer, "discover")
274 .mockRejectedValueOnce(new Error("network down"))
275 .mockResolvedValueOnce(
276 new Issuer({
277 issuer: ISSUER,
278 authorization_endpoint: AUTHORIZATION_ENDPOINT,
279 token_endpoint: TOKEN_ENDPOINT,
280 jwks_uri: JWKS_URI,
281 })
282 )
283
284 const engine = new OidcEngine({
285 issuer: ISSUER,
286 client_id: "client-123",
287 callback_url: CALLBACK_URL,
288 })
289
290 await expect((engine as any).getClient_()).rejects.toThrow(/network down/)
291
292 // The failure isn't memoized: the next call retries and succeeds.
293 const client = await (engine as any).getClient_()
294 expect(client).toBeDefined()
295 })
296 })
297
298 describe("discovery caching via the cache module", () => {
299 const discoveredIssuer = () =>
300 new Issuer({
301 issuer: ISSUER,
302 authorization_endpoint: AUTHORIZATION_ENDPOINT,
303 token_endpoint: TOKEN_ENDPOINT,
304 jwks_uri: JWKS_URI,
305 })
306
307 const options: OidcEngineOptions = {
308 issuer: ISSUER,
309 client_id: "client-123",
310 callback_url: CALLBACK_URL,
311 discovery_cache_ttl_ms: 3600_000,
312 }
313
314 it("stores the discovery document in the cache module on a miss", async () => {
315 const discoverSpy = jest
316 .spyOn(Issuer, "discover")
317 .mockResolvedValue(discoveredIssuer())
318
319 const cache = {
320 get: jest.fn().mockResolvedValue(null),
321 set: jest.fn().mockResolvedValue(undefined),
322 invalidate: jest.fn().mockResolvedValue(undefined),
323 }
324
325 const engine = new OidcEngine(options, cache as any)
326 await engine.buildAuthorizationUrl({ state: "one" })
327
328 expect(cache.get).toHaveBeenCalledWith(`oidc:discovery:${ISSUER}`)
329 expect(discoverSpy).toHaveBeenCalledTimes(1)
330 // TTL is passed to the cache module in seconds.
331 expect(cache.set).toHaveBeenCalledWith(
332 `oidc:discovery:${ISSUER}`,
333 expect.objectContaining({ issuer: ISSUER }),
334 3600
335 )
336 })
337
338 it("uses the cached discovery document and skips network discovery on a hit", async () => {
339 const discoverSpy = jest.spyOn(Issuer, "discover")
340
341 const cache = {
342 get: jest.fn().mockResolvedValue(discoveredIssuer().metadata),
343 set: jest.fn().mockResolvedValue(undefined),
344 invalidate: jest.fn().mockResolvedValue(undefined),
345 }
346
347 const engine = new OidcEngine(options, cache as any)
348 await engine.buildAuthorizationUrl({ state: "one" })
349
350 expect(cache.get).toHaveBeenCalledWith(`oidc:discovery:${ISSUER}`)
351 expect(discoverSpy).not.toHaveBeenCalled()
352 expect(cache.set).not.toHaveBeenCalled()
353 })
354 })
355
356 describe("mapClaims", () => {
357 it("maps sub to entityId and profile claims to user_metadata by default", () => {
358 const engine = new OidcEngine(baseOptions())
359
360 const mapped = engine.mapClaims({
361 sub: "user-1",
362 email: "alice@acme.com",
363 email_verified: true,
364 name: "Alice",
365 picture: "https://cdn.example.com/alice.png",
366 })
367
368 expect(mapped.entityId).toBe("user-1")
369 expect(mapped.userMetadata).toEqual({
370 email: "alice@acme.com",
371 name: "Alice",
372 })
373 })
374
375 it("supports custom claim mappings", () => {
376 const engine = new OidcEngine(
377 baseOptions({
378 claim_mappings: {
379 entity_id: "oid",
380 email: "upn",
381 name: "display_name",
382 department: "dept",
383 },
384 })
385 )
386
387 const mapped = engine.mapClaims({
388 oid: "azure-oid-123",
389 upn: "bob@acme.com",
390 email_verified: true,
391 display_name: "Bob",
392 dept: "Engineering",
393 })
394
395 expect(mapped.entityId).toBe("azure-oid-123")
396 expect(mapped.userMetadata).toEqual({
397 email: "bob@acme.com",
398 name: "Bob",
399 department: "Engineering",
400 })
401 })
402
403 it("throws when the entity_id claim is missing", () => {
404 const engine = new OidcEngine(baseOptions())
405
406 const error = getError(() =>
407 engine.mapClaims({ email: "a@acme.com", email_verified: true })
408 )
409 expect(error.type).toBe(MedusaError.Types.INVALID_DATA)
410 expect(error.message).toMatch(/missing the 'sub' claim/)
411 })
412
413 it("throws when email is not verified and verification is required", () => {
414 const engine = new OidcEngine(baseOptions())
415
416 const error = getError(() =>
417 engine.mapClaims({
418 sub: "user-1",
419 email: "a@acme.com",
420 email_verified: false,
421 })
422 )
423 expect(error.type).toBe(MedusaError.Types.INVALID_DATA)
424 expect(error.message).toMatch(/verified email/)
425 })
426
427 it("allows unverified email when require_verified_email is false", () => {
428 const engine = new OidcEngine(
429 baseOptions({ require_verified_email: false })
430 )
431
432 const mapped = engine.mapClaims({
433 sub: "user-1",
434 email: "a@acme.com",
435 email_verified: false,
436 })
437
438 expect(mapped.entityId).toBe("user-1")
439 })
440
441 it("enforces the allowed_email_domains policy", () => {
442 const engine = new OidcEngine(
443 baseOptions({ allowed_email_domains: ["acme.com"] })
444 )
445
446 // Allowed domain passes.
447 expect(
448 engine.mapClaims({
449 sub: "user-1",
450 email: "alice@ACME.com",
451 email_verified: true,
452 }).entityId
453 ).toBe("user-1")
454
455 // Disallowed domain is rejected with UNAUTHORIZED.
456 const error = getError(() =>
457 engine.mapClaims({
458 sub: "user-2",
459 email: "eve@evil.com",
460 email_verified: true,
461 })
462 )
463 expect(error.type).toBe(MedusaError.Types.UNAUTHORIZED)
464 })
465 })
466 })
467
468 function getError(fn: () => unknown): MedusaError {
469 try {
470 fn()
471 } catch (e) {
472 return e as MedusaError
473 }
474 throw new Error("Expected function to throw, but it did not")
475 }