-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathslas.test.ts
More file actions
619 lines (536 loc) · 20.7 KB
/
slas.test.ts
File metadata and controls
619 lines (536 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/*
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import nock from "nock";
import { expect } from "chai";
import { ShopperLogin, ShopperLoginTypes } from "../../../renderedTemplates";
import { ISlasClient } from "./slasClient";
import * as slasHelper from "./slas";
import sinon from "sinon";
import { URL } from "url";
import { CommonParameters } from "@commerce-apps/core";
import crypto from "crypto";
const codeVerifier = "code_verifier";
const mockURL =
"https://localhost:3000/callback?usid=048adcfb-aa93-4978-be9e-09cb569fdcb9&code=J2lHm0cgXmnXpwDhjhLoyLJBoUAlBfxDY-AhjqGMC-o";
const clientConfig = {
parameters: {
shortCode: "short_code",
organizationId: "organization_id",
clientId: "client_id",
siteId: "site_id",
},
};
const credentials = {
username: "shopper_user_id",
password: "shopper_password",
clientSecret: "client_secret",
};
const expectedTokenResponse: ShopperLoginTypes.TokenResponse = {
access_token: "access_token",
id_token: "id_token",
refresh_token: "refresh_token",
expires_in: 0,
refresh_token_expires_in: 0,
token_type: "Bearer",
usid: "usid",
customer_id: "customer_id",
enc_user_id: "enc_user_id",
idp_access_token: "idp_access_token",
};
const parameters = {
accessToken: "access_token",
hint: "hint",
redirectURI: "redirect_uri",
refreshToken: "refresh_token",
usid: "usid",
};
const createSlasClient = (): ISlasClient => {
return new ShopperLogin.ShopperLogin(clientConfig) as ISlasClient;
};
const sandbox = sinon.createSandbox();
beforeEach(() => {
nock.cleanAll();
sandbox.restore();
});
describe("Create code verifier", () => {
it("creates 128-character URL-safe string", () => {
const verifier = slasHelper.createCodeVerifier();
expect(verifier).to.match(/[A-Za-z0-9_-]{128}/);
});
});
describe("Generate code challenge", () => {
const verifier =
"XVv3DJSzPDdbcVsrcs-4KuUtMYhvd6fxS0Gtbu_gv-UaVKo80w8WKA1gitXhC-DMW0H_mOtUNJhecfTwb-n_dXQWz8Ay6iWZWoeSBPfwgzP_pblgQr4eqodqeYNxfdWv";
const expectedChallenge = "AH8WaHxbEtoZuFw-rw2YS9SazhKJilGoESoSlICXsQw";
it("generates correct code challenge for verifier", async () => {
const challenge = await slasHelper.generateCodeChallenge(verifier);
expect(challenge).to.be.deep.equal(expectedChallenge);
});
it("throws error when code challenge is not generated correctly", async () => {
sandbox.stub(crypto, "createHash").callsFake(() => {
return {
update: () => ({
digest: () => "",
}),
} as any;
});
let expectedError;
try {
await slasHelper.generateCodeChallenge(verifier);
} catch (error) {
expectedError = error;
}
expect(expectedError.message).to.be.equal(
"Problem generating code challenge"
);
});
});
describe("Get code and usid", () => {
const expectedRecord = {
code: "J2lHm0cgXmnXpwDhjhLoyLJBoUAlBfxDY-AhjqGMC-o",
usid: "048adcfb-aa93-4978-be9e-09cb569fdcb9",
};
const expectedNoQueryParamsRecord = {
code: "",
usid: "",
};
const noQueryParamsUrl = "https://localhost:3000/callback?";
it("extracts code and usid from url", () => {
const record = slasHelper.getCodeAndUsidFromUrl(mockURL);
expect(record).to.be.deep.equal(expectedRecord);
});
it("evaluates code and usid as empty strings when called with no query params", () => {
const record = slasHelper.getCodeAndUsidFromUrl(noQueryParamsUrl);
expect(record).to.be.deep.equal(expectedNoQueryParamsRecord);
});
});
describe("Authorize user", () => {
const expectedAuthResponse = {
code: "J2lHm0cgXmnXpwDhjhLoyLJBoUAlBfxDY-AhjqGMC-o",
url: mockURL,
usid: "048adcfb-aa93-4978-be9e-09cb569fdcb9",
};
const expectedAuthResponseNoLocation = {
code: "",
url: "https://short_code.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/organization_id/oauth2/authorize?client_id=client_id&code_challenge=73oehA2tBul5grZPhXUGQwNAjxh69zNES8bu2bVD0EM&hint=hint&redirect_uri=redirect_uri&response_type=code&usid=usid",
usid: "usid",
};
const params = {
redirectURI: parameters.redirectURI,
hint: parameters.hint,
usid: parameters.usid,
};
it("hits the authorize endpoint and receives authorization code", async () => {
const mockSlasClient = createSlasClient();
const authorizeSpy = sinon.spy(mockSlasClient, "authorizeCustomer");
const { shortCode, organizationId } = clientConfig.parameters;
// slasClient is copied and tries to make an actual API call
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.get(`/shopper/auth/v1/organizations/${organizationId}/oauth2/authorize`)
.query(true)
.reply(303, { response_body: "response_body" }, { location: mockURL });
const authResponse = await slasHelper.authorize({
slasClient: mockSlasClient,
codeVerifier,
parameters: params,
});
expect(authResponse).to.be.deep.equal(expectedAuthResponse);
});
it("uses response.url if location header is unavailable", async () => {
const mockSlasClient = createSlasClient();
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.get(`/shopper/auth/v1/organizations/${organizationId}/oauth2/authorize`)
.query(true)
.reply(303, { response_body: "response_body" }, { location: "" });
const authResponse = await slasHelper.authorize({
slasClient: mockSlasClient,
codeVerifier,
parameters: params,
});
const authURL = new URL(authResponse.url);
const expectedURL = new URL(expectedAuthResponseNoLocation.url);
expect(authURL.origin).to.equal(expectedURL.origin);
expect(authURL.pathname).to.equal(expectedURL.pathname);
authURL.searchParams.sort();
expectedURL.searchParams.sort();
expect(authURL.searchParams.toString()).to.equal(
expectedURL.searchParams.toString()
);
});
it("throws an error when authorization fails", async () => {
const mockSlasClient = createSlasClient();
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.get(`/shopper/auth/v1/organizations/${organizationId}/oauth2/authorize`)
.query(true)
.reply(400);
await slasHelper
.authorize({
slasClient: mockSlasClient,
codeVerifier,
parameters: params,
})
.catch((error) => expect(error.message).to.be.equal("400 Bad Request"));
});
});
describe("Guest user flow", () => {
const expectedOptionsPrivate = {
headers: {
Authorization: "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=",
},
body: {
grant_type: "client_credentials",
channel_id: "site_id",
},
};
const expectedOptionsPublic = {
body: {
client_id: "client_id",
code: "",
redirect_uri: "redirect_uri",
grant_type: "authorization_code_pkce",
usid: "",
},
};
it("using a private client takes in a client secret to generate token", async () => {
const mockSlasClient = createSlasClient();
const spy = sinon.spy(mockSlasClient, "getAccessToken");
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.query(true)
.reply(200, expectedTokenResponse);
const accessToken = await slasHelper.loginGuestUserPrivate({
slasClient: mockSlasClient,
credentials: {
clientSecret: credentials.clientSecret,
},
});
expect(spy.getCall(0).args[0]).to.be.deep.equals(expectedOptionsPrivate);
expect(accessToken).to.be.deep.equals(expectedTokenResponse);
});
it("throws an error when channel_id is not passed into private client", async () => {
const mockSlasClient = createSlasClient();
const mockSlasClientNoSiteID = {
...mockSlasClient,
clientConfig: {
parameters: {
...mockSlasClient.clientConfig.parameters,
siteId: undefined, // siteId in client config is used for channel_id
},
},
};
try {
await slasHelper.loginGuestUserPrivate({
slasClient: mockSlasClientNoSiteID,
credentials: {
clientSecret: credentials.clientSecret,
},
});
expect.fail("Expected error not thrown, this line should not be reached");
} catch (error) {
expect(error.message).to.equal(
"Required argument channel_id is not provided through clientConfig.parameters.siteId"
);
}
});
it("using a public client uses a code verifier and code challenge to generate token", async () => {
const mockSlasClient = createSlasClient();
const spy = sinon.spy(mockSlasClient, "getAccessToken");
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.get(`/shopper/auth/v1/organizations/${organizationId}/oauth2/authorize`)
.query(true)
.reply(303, { response_body: "response_body" });
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.query(true)
.reply(200, expectedTokenResponse);
const accessToken = await slasHelper.loginGuestUser({
slasClient: mockSlasClient,
parameters: {
redirectURI: parameters.redirectURI,
},
});
const options = spy.getCall(0).args[0];
// have to match object since code_verifier is randomly generated
sinon.assert.match(options, expectedOptionsPublic);
expect(options.body).to.include.keys("code_verifier");
expect(accessToken).to.be.deep.equals(expectedTokenResponse);
});
it("can pass custom params when using a public client flow", async () => {
const mockSlasClient = createSlasClient();
const getTokenSpy = sinon.spy(mockSlasClient, "getAccessToken");
const authorizeSpy = sinon.spy(mockSlasClient, "authorizeCustomer");
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.get(`/shopper/auth/v1/organizations/${organizationId}/oauth2/authorize`)
.query(true)
.reply(303, { response_body: "response_body" });
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.query(true)
.reply(200, expectedTokenResponse);
const accessToken = await slasHelper.loginGuestUser({
slasClient: mockSlasClient,
parameters: {
c_cloth: "jeans",
redirectURI: parameters.redirectURI,
},
});
const getTokenOpts = getTokenSpy.getCall(0).args[0];
const authorizeOpt = authorizeSpy.getCall(0).args[0];
// have to match object since code_verifier is randomly generated
sinon.assert.match(getTokenOpts, expectedOptionsPublic);
sinon.assert.match(authorizeOpt, {
parameters: {
c_cloth: "jeans",
client_id: clientConfig.parameters.clientId,
code_challenge: sinon.match(/./),
hint: "guest",
organizationId: clientConfig.parameters.organizationId,
redirect_uri: parameters.redirectURI,
response_type: "code",
},
fetchOptions: { redirect: "manual" },
});
expect(getTokenOpts.body).to.include.keys("code_verifier");
expect(accessToken).to.be.deep.equals(expectedTokenResponse);
});
});
describe("Registered B2C user flow", () => {
const params = {
redirectURI: parameters.redirectURI,
usid: parameters.usid,
};
it("using a private client uses hits login and token endpoints to generate JWT", async () => {
const mockSlasClient = createSlasClient();
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/login`)
.query(true)
.reply(303, { response_body: "response_body" });
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.query(true)
.reply(200, expectedTokenResponse);
const accessToken = await slasHelper.loginRegisteredUserB2Cprivate({
slasClient: mockSlasClient,
credentials,
parameters: params,
});
expect(accessToken).to.be.deep.equals(expectedTokenResponse);
});
it("using a public client uses hits login and token endpoints to generate JWT", async () => {
const mockSlasClient = createSlasClient();
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/login`)
.query(true)
.reply(303, { response_body: "response_body" }, { location: mockURL });
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.query(true)
.reply(200, expectedTokenResponse);
const accessToken = await slasHelper.loginRegisteredUserB2C({
slasClient: mockSlasClient,
credentials,
parameters: params,
});
expect(accessToken).to.be.deep.equals(expectedTokenResponse);
});
it("loginRegisteredUserB2C accepts custom body", async () => {
const mockSlasClient = createSlasClient();
const authenticateSpy = sinon.spy(mockSlasClient, "authenticateCustomer");
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/login`)
.reply(303, { response_body: "response_body" }, { location: mockURL });
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.reply(200, expectedTokenResponse);
const accessToken = await slasHelper.loginRegisteredUserB2C({
slasClient: mockSlasClient,
credentials,
parameters: params,
body: { c_body: "custom-body" },
});
const authenticateOpts = authenticateSpy.getCall(0).args[0];
sinon.assert.match(authenticateOpts, {
headers: {
Authorization: sinon.match(/./),
},
parameters: { organizationId: organizationId },
body: {
c_body: "custom-body",
redirect_uri: params.redirectURI,
client_id: clientConfig.parameters.clientId,
code_challenge: sinon.match(/./),
channel_id: clientConfig.parameters.siteId,
usid: params.usid,
},
fetchOptions: { redirect: "manual" },
});
expect(accessToken).to.be.deep.equals(expectedTokenResponse);
});
it("loginRegisteredUserB2Cprivate excepts custom body", async () => {
const mockSlasClient = createSlasClient();
const authenticateSpy = sinon.spy(mockSlasClient, "authenticateCustomer");
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/login`)
.reply(303, { response_body: "response_body" });
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.reply(200, expectedTokenResponse);
const accessToken = await slasHelper.loginRegisteredUserB2Cprivate({
slasClient: mockSlasClient,
credentials,
parameters: params,
body: { c_body: "custom-body" },
});
const authenticateOpts = authenticateSpy.getCall(0).args[0];
sinon.assert.match(authenticateOpts, {
headers: {
Authorization: sinon.match(/./),
},
body: {
c_body: "custom-body",
code_challenge: sinon.match(/./),
channel_id: clientConfig.parameters.siteId,
client_id: clientConfig.parameters.clientId,
redirect_uri: params.redirectURI,
usid: params.usid,
},
fetchOptions: { redirect: "manual" },
});
expect(accessToken).to.be.deep.equals(expectedTokenResponse);
});
it("throws an error when login is unsuccessful for public", async () => {
const mockSlasClient = createSlasClient();
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/login`)
.query(true)
.reply(400);
await slasHelper
.loginRegisteredUserB2C({
slasClient: mockSlasClient,
credentials,
parameters: params,
})
.catch((error) => expect(error.message).to.be.equal("400 Bad Request"));
});
it("throws an error when login is unsuccessful for private", async () => {
const mockSlasClient = createSlasClient();
const { shortCode, organizationId } = mockSlasClient.clientConfig
.parameters as CommonParameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/login`)
.query(true)
.reply(400);
await slasHelper
.loginRegisteredUserB2Cprivate({
slasClient: mockSlasClient,
credentials,
parameters: params,
})
.catch((error) => expect(error.message).to.be.equal("400 Bad Request"));
});
});
describe("Refresh Token", () => {
it("refreshes the token", async () => {
const expectedOpts = {
body: {
client_id: "client_id",
grant_type: "refresh_token",
refresh_token: "refresh_token",
},
};
const mockSlasClient = createSlasClient();
const spy = sinon.spy(mockSlasClient, "getAccessToken");
const { shortCode, organizationId } = clientConfig.parameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.query(true)
.reply(200, expectedTokenResponse);
const token = await slasHelper.refreshAccessToken({
slasClient: mockSlasClient,
parameters: {
refreshToken: parameters.refreshToken,
},
});
expect(spy.getCall(0).args[0]).to.be.deep.equals(expectedOpts);
expect(token).to.be.deep.equals(expectedTokenResponse);
});
it("refreshes the token using client secret", async () => {
const expectedOptions = {
headers: {
Authorization: "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=",
},
body: {
grant_type: "refresh_token",
refresh_token: parameters.refreshToken,
},
};
const mockSlasClient = createSlasClient();
const spy = sinon.spy(mockSlasClient, "getAccessToken");
const { shortCode, organizationId } = clientConfig.parameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.post(`/shopper/auth/v1/organizations/${organizationId}/oauth2/token`)
.query(true)
.reply(200, expectedTokenResponse);
const token = await slasHelper.refreshAccessTokenPrivate({
slasClient: mockSlasClient,
credentials,
parameters: { refreshToken: parameters.refreshToken },
});
expect(spy.getCall(0).args[0]).to.be.deep.equals(expectedOptions);
expect(token).to.be.deep.equals(expectedTokenResponse);
});
});
describe("Logout", () => {
const expectedOptions = {
headers: {
Authorization: "Bearer access_token",
},
parameters: {
client_id: "client_id",
channel_id: "site_id",
refresh_token: "refresh_token",
},
};
it("logs out the customer", async () => {
const mockSlasClient = createSlasClient();
const spy = sinon.spy(mockSlasClient, "logoutCustomer");
const { shortCode, organizationId } = clientConfig.parameters;
nock(`https://${shortCode}.api.commercecloud.salesforce.com`)
.get(`/shopper/auth/v1/organizations/${organizationId}/oauth2/logout`)
.query(true)
.reply(200, expectedTokenResponse);
const token = await slasHelper.logout({
slasClient: mockSlasClient,
parameters: {
refreshToken: parameters.refreshToken,
accessToken: parameters.accessToken,
},
});
expect(spy.getCall(0).args[0]).to.be.deep.equals(expectedOptions);
expect(token).to.be.deep.equals(expectedTokenResponse);
});
});