|
1
|
import { MedusaError } from "@medusajs/framework/utils" |
|
2
|
import crypto from "crypto" |
|
3
|
import jwt from "jsonwebtoken" |
|
4
|
import { GoogleAuthService } from "../../src/services/google" |
|
5
|
import { http, HttpResponse } from "msw" |
|
6
|
import { setupServer } from "msw/node" |
|
7
|
|
|
8
|
jest.setTimeout(100000) |
|
9
|
|
|
10
|
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", { |
|
11
|
modulusLength: 2048, |
|
12
|
}) |
|
13
|
|
|
14
|
const KID = "test-kid" |
|
15
|
|
|
16
|
const jwkPublic = { |
|
17
|
...(publicKey.export({ format: "jwk" }) as Record<string, string>), |
|
18
|
kid: KID, |
|
19
|
use: "sig", |
|
20
|
alg: "RS256", |
|
21
|
} |
|
22
|
|
|
23
|
const sampleIdPayload = { |
|
24
|
iss: "https://accounts.google.com", |
|
25
|
azp: "test", |
|
26
|
aud: "test", |
|
27
|
sub: "113664482950786663866", |
|
28
|
hd: "medusajs.com", |
|
29
|
email: "test@medusajs.com", |
|
30
|
email_verified: true, |
|
31
|
at_hash: "7DKi89ceSj-Bii1m_V1Pew", |
|
32
|
name: "Test Admin", |
|
33
|
picture: |
|
34
|
"https://lh3.googleusercontent.com/a/ACg8ocJu6nzIGJRzHnl6peAh3fKOzOkrrRCWyMOMuIfCwePDG-ykulA=s96-c", |
|
35
|
given_name: "Test", |
|
36
|
family_name: "Admin", |
|
37
|
} |
|
38
|
|
|
39
|
const signIdToken = (payload: object, opts: jwt.SignOptions = {}) => |
|
40
|
jwt.sign(payload, privateKey.export({ format: "pem", type: "pkcs8" }), { |
|
41
|
algorithm: "RS256", |
|
42
|
keyid: KID, |
|
43
|
expiresIn: "1d", |
|
44
|
...opts, |
|
45
|
}) |
|
46
|
|
|
47
|
const encodedIdToken = signIdToken(sampleIdPayload) |
|
48
|
|
|
49
|
const forgedIdToken = jwt.sign( |
|
50
|
{ ...sampleIdPayload, sub: "attacker-sub" }, |
|
51
|
"attacker-secret", |
|
52
|
{ algorithm: "HS256", keyid: KID, expiresIn: "1d" } |
|
53
|
) |
|
54
|
|
|
55
|
const baseUrl = "https://someurl.com" |
|
56
|
const callbackUrl = encodeURIComponent( |
|
57
|
"https://someurl.com/auth/google/callback" |
|
58
|
) |
|
59
|
|
|
60
|
let state = {} |
|
61
|
const defaultSpies = { |
|
62
|
retrieve: jest.fn(), |
|
63
|
create: jest.fn(), |
|
64
|
update: jest.fn(), |
|
65
|
setState: jest.fn().mockImplementation((key, value) => { |
|
66
|
state[key] = value |
|
67
|
}), |
|
68
|
getState: jest.fn().mockImplementation((key) => { |
|
69
|
return Promise.resolve(state[key]) |
|
70
|
}), |
|
71
|
} |
|
72
|
|
|
73
|
// This is just a network-layer mocking, it doesn't start an actual server |
|
74
|
const server = setupServer( |
|
75
|
http.get("https://www.googleapis.com/oauth2/v3/certs", () => { |
|
76
|
return HttpResponse.json({ keys: [jwkPublic] }) |
|
77
|
}), |
|
78
|
|
|
79
|
http.post( |
|
80
|
"https://oauth2.googleapis.com/token", |
|
81
|
async ({ request, params, cookies }) => { |
|
82
|
const url = request.url |
|
83
|
if ( |
|
84
|
url === |
|
85
|
`https://oauth2.googleapis.com/token?client_id=test&client_secret=test&code=invalid-code&redirect_uri=${callbackUrl}&grant_type=authorization_code` |
|
86
|
) { |
|
87
|
return new HttpResponse(null, { |
|
88
|
status: 401, |
|
89
|
statusText: "Unauthorized", |
|
90
|
}) |
|
91
|
} |
|
92
|
|
|
93
|
if ( |
|
94
|
url === |
|
95
|
`https://oauth2.googleapis.com/token?client_id=test&client_secret=test&code=valid-code&redirect_uri=${callbackUrl}&grant_type=authorization_code` |
|
96
|
) { |
|
97
|
return new HttpResponse( |
|
98
|
JSON.stringify({ |
|
99
|
access_token: "test", |
|
100
|
expires_in: 3600, |
|
101
|
token_type: "Bearer", |
|
102
|
refresh_token: "test", |
|
103
|
id_token: encodedIdToken, |
|
104
|
}) |
|
105
|
) |
|
106
|
} |
|
107
|
|
|
108
|
if ( |
|
109
|
url === |
|
110
|
`https://oauth2.googleapis.com/token?client_id=test&client_secret=test&code=forged-code&redirect_uri=${callbackUrl}&grant_type=authorization_code` |
|
111
|
) { |
|
112
|
return new HttpResponse( |
|
113
|
JSON.stringify({ |
|
114
|
access_token: "test", |
|
115
|
expires_in: 3600, |
|
116
|
token_type: "Bearer", |
|
117
|
refresh_token: "test", |
|
118
|
id_token: forgedIdToken, |
|
119
|
}) |
|
120
|
) |
|
121
|
} |
|
122
|
} |
|
123
|
), |
|
124
|
|
|
125
|
http.all("*", ({ request, params, cookies }) => { |
|
126
|
return new HttpResponse(null, { |
|
127
|
status: 404, |
|
128
|
statusText: "Not Found", |
|
129
|
}) |
|
130
|
}) |
|
131
|
) |
|
132
|
|
|
133
|
describe("Google auth provider", () => { |
|
134
|
let googleService: GoogleAuthService |
|
135
|
beforeAll(() => { |
|
136
|
googleService = new GoogleAuthService( |
|
137
|
{ |
|
138
|
logger: console as any, |
|
139
|
}, |
|
140
|
{ |
|
141
|
clientId: "test", |
|
142
|
clientSecret: "test", |
|
143
|
callbackUrl: `${baseUrl}/auth/google/callback`, |
|
144
|
} |
|
145
|
) |
|
146
|
|
|
147
|
server.listen() |
|
148
|
}) |
|
149
|
|
|
150
|
afterEach(() => { |
|
151
|
server.resetHandlers() |
|
152
|
jest.restoreAllMocks() |
|
153
|
state = {} |
|
154
|
}) |
|
155
|
|
|
156
|
afterAll(() => server.close()) |
|
157
|
|
|
158
|
it("throw an error if required options are not passed", async () => { |
|
159
|
let msg = "" |
|
160
|
try { |
|
161
|
GoogleAuthService.validateOptions({ |
|
162
|
clientId: "test", |
|
163
|
clientSecret: "test", |
|
164
|
} as any) |
|
165
|
} catch (e) { |
|
166
|
msg = e.message |
|
167
|
} |
|
168
|
|
|
169
|
expect(msg).toEqual("Google callbackUrl is required") |
|
170
|
}) |
|
171
|
|
|
172
|
it("returns a redirect URL on authenticate", async () => { |
|
173
|
const res = await googleService.authenticate({}, defaultSpies) |
|
174
|
expect(res).toEqual({ |
|
175
|
success: true, |
|
176
|
location: `https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${callbackUrl}&client_id=test&response_type=code&scope=email+profile+openid&state=${ |
|
177
|
Object.keys(state)[0] |
|
178
|
}`, |
|
179
|
}) |
|
180
|
}) |
|
181
|
|
|
182
|
it("returns a custom redirect_uri on authenticate", async () => { |
|
183
|
const res = await googleService.authenticate( |
|
184
|
{ |
|
185
|
body: { callback_url: "https://someotherurl.com" }, |
|
186
|
}, |
|
187
|
defaultSpies |
|
188
|
) |
|
189
|
expect(res).toEqual({ |
|
190
|
success: true, |
|
191
|
location: `https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fsomeotherurl.com&client_id=test&response_type=code&scope=email+profile+openid&state=${ |
|
192
|
Object.keys(state)[0] |
|
193
|
}`, |
|
194
|
}) |
|
195
|
}) |
|
196
|
|
|
197
|
it("validate callback should return an error on empty code", async () => { |
|
198
|
const res = await googleService.validateCallback( |
|
199
|
{ |
|
200
|
query: {}, |
|
201
|
}, |
|
202
|
defaultSpies |
|
203
|
) |
|
204
|
expect(res).toEqual({ |
|
205
|
success: false, |
|
206
|
error: "No code provided", |
|
207
|
}) |
|
208
|
}) |
|
209
|
|
|
210
|
it("validate callback should return an error on missing state", async () => { |
|
211
|
const res = await googleService.validateCallback( |
|
212
|
{ |
|
213
|
query: { |
|
214
|
code: "valid-code", |
|
215
|
}, |
|
216
|
}, |
|
217
|
defaultSpies |
|
218
|
) |
|
219
|
expect(res).toEqual({ |
|
220
|
success: false, |
|
221
|
error: "No state provided, or session expired", |
|
222
|
}) |
|
223
|
}) |
|
224
|
|
|
225
|
it("validate callback should return an error on expired/invalid state", async () => { |
|
226
|
const res = await googleService.validateCallback( |
|
227
|
{ |
|
228
|
query: { |
|
229
|
code: "valid-code", |
|
230
|
state: "somekey", |
|
231
|
}, |
|
232
|
}, |
|
233
|
defaultSpies |
|
234
|
) |
|
235
|
expect(res).toEqual({ |
|
236
|
success: false, |
|
237
|
error: "No state provided, or session expired", |
|
238
|
}) |
|
239
|
}) |
|
240
|
|
|
241
|
it("validate callback should return on a missing access token for code", async () => { |
|
242
|
state = { |
|
243
|
somekey: { |
|
244
|
callback_url: callbackUrl, |
|
245
|
}, |
|
246
|
} |
|
247
|
|
|
248
|
const res = await googleService.validateCallback( |
|
249
|
{ |
|
250
|
query: { |
|
251
|
code: "invalid-code", |
|
252
|
state: "somekey", |
|
253
|
}, |
|
254
|
}, |
|
255
|
defaultSpies |
|
256
|
) |
|
257
|
|
|
258
|
expect(res).toEqual({ |
|
259
|
success: false, |
|
260
|
error: "Could not exchange token, 401, Unauthorized", |
|
261
|
}) |
|
262
|
}) |
|
263
|
|
|
264
|
it("validate callback should return successfully on a correct code for a new user", async () => { |
|
265
|
const authServiceSpies = { |
|
266
|
...defaultSpies, |
|
267
|
retrieve: jest.fn().mockImplementation(() => { |
|
268
|
throw new MedusaError(MedusaError.Types.NOT_FOUND, "Not found") |
|
269
|
}), |
|
270
|
create: jest.fn().mockImplementation(() => { |
|
271
|
return { |
|
272
|
provider_identities: [ |
|
273
|
{ |
|
274
|
entity_id: "113664482950786663866", |
|
275
|
provider: "google", |
|
276
|
}, |
|
277
|
], |
|
278
|
} |
|
279
|
}), |
|
280
|
update: jest.fn().mockImplementation(() => { |
|
281
|
return {} |
|
282
|
}), |
|
283
|
} |
|
284
|
|
|
285
|
state = { |
|
286
|
somekey: { |
|
287
|
callback_url: callbackUrl, |
|
288
|
}, |
|
289
|
} |
|
290
|
|
|
291
|
const res = await googleService.validateCallback( |
|
292
|
{ |
|
293
|
query: { |
|
294
|
code: "valid-code", |
|
295
|
state: "somekey", |
|
296
|
}, |
|
297
|
}, |
|
298
|
authServiceSpies |
|
299
|
) |
|
300
|
|
|
301
|
expect(res).toEqual({ |
|
302
|
success: true, |
|
303
|
authIdentity: { |
|
304
|
provider_identities: [ |
|
305
|
{ |
|
306
|
entity_id: "113664482950786663866", |
|
307
|
provider: "google", |
|
308
|
}, |
|
309
|
], |
|
310
|
}, |
|
311
|
}) |
|
312
|
}) |
|
313
|
|
|
314
|
it("validate callback should reject a forged id_token whose signature does not match Google's JWKS", async () => { |
|
315
|
state = { |
|
316
|
somekey: { |
|
317
|
callback_url: callbackUrl, |
|
318
|
}, |
|
319
|
} |
|
320
|
|
|
321
|
const res = await googleService.validateCallback( |
|
322
|
{ |
|
323
|
query: { |
|
324
|
code: "forged-code", |
|
325
|
state: "somekey", |
|
326
|
}, |
|
327
|
}, |
|
328
|
defaultSpies |
|
329
|
) |
|
330
|
|
|
331
|
expect(res.success).toBe(false) |
|
332
|
expect(res.error).toMatch(/Could not verify Google id_token/i) |
|
333
|
}) |
|
334
|
|
|
335
|
it("validate callback should return successfully on a correct code for an existing user", async () => { |
|
336
|
const authServiceSpies = { |
|
337
|
...defaultSpies, |
|
338
|
retrieve: jest.fn().mockImplementation(() => { |
|
339
|
return { |
|
340
|
provider_identities: [ |
|
341
|
{ |
|
342
|
entity_id: "113664482950786663866", |
|
343
|
provider: "google", |
|
344
|
}, |
|
345
|
], |
|
346
|
} |
|
347
|
}), |
|
348
|
create: jest.fn().mockImplementation(() => { |
|
349
|
return {} |
|
350
|
}), |
|
351
|
update: jest.fn().mockImplementation(() => { |
|
352
|
return {} |
|
353
|
}), |
|
354
|
} |
|
355
|
|
|
356
|
state = { |
|
357
|
somekey: { |
|
358
|
callback_url: callbackUrl, |
|
359
|
}, |
|
360
|
} |
|
361
|
|
|
362
|
const res = await googleService.validateCallback( |
|
363
|
{ |
|
364
|
query: { |
|
365
|
code: "valid-code", |
|
366
|
state: "somekey", |
|
367
|
}, |
|
368
|
}, |
|
369
|
authServiceSpies |
|
370
|
) |
|
371
|
|
|
372
|
expect(res).toEqual({ |
|
373
|
success: true, |
|
374
|
authIdentity: { |
|
375
|
provider_identities: [ |
|
376
|
{ |
|
377
|
entity_id: "113664482950786663866", |
|
378
|
provider: "google", |
|
379
|
}, |
|
380
|
], |
|
381
|
}, |
|
382
|
}) |
|
383
|
}) |
|
384
|
}) |