@webex/plugin-authorization-browser-first-party 3.12.0 → 3.13.0-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,7 +14,8 @@ import {base64, patterns} from '@webex/common';
14
14
  import {merge, times} from 'lodash';
15
15
  import CryptoJS from 'crypto-js';
16
16
  import Authorization from '@webex/plugin-authorization-browser-first-party';
17
- import {Events} from '../../../src';
17
+ import {Events, InitialAuthorizationCodeGrantOutcomes} from '../../../src';
18
+ import authorizationConfig from '../../../src/config';
18
19
 
19
20
  // Necessary to require lodash this way in order to stub the method
20
21
  const lodash = require('lodash');
@@ -25,9 +26,13 @@ describe('plugin-authorization-browser-first-party', () => {
25
26
  href = 'https://example.com',
26
27
  csrfToken = undefined,
27
28
  pkceVerifier = undefined,
28
- config = {}
29
+ config = {},
30
+ getRandomValues = sinon.stub().callsFake((randomValues) => randomValues.fill(0))
29
31
  ) {
30
32
  const mockWindow = {
33
+ crypto: {
34
+ getRandomValues,
35
+ },
31
36
  history: {
32
37
  replaceState(a, b, location) {
33
38
  mockWindow.location.href = location;
@@ -104,10 +109,45 @@ describe('plugin-authorization-browser-first-party', () => {
104
109
  sinon.restore();
105
110
  });
106
111
 
112
+ it('exposes the initial authorization code grant outcome as readonly', () => {
113
+ const webex = makeWebex();
114
+ const changeSpy = sinon.spy();
115
+
116
+ webex.authorization.on('change:initialAuthorizationCodeGrantOutcome', changeSpy);
117
+
118
+ assert.equal(
119
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
120
+ InitialAuthorizationCodeGrantOutcomes.notAttempted
121
+ );
122
+ assert.throws(() => {
123
+ webex.authorization.initialAuthorizationCodeGrantOutcome =
124
+ InitialAuthorizationCodeGrantOutcomes.success;
125
+ }, /derived property, it can't be set directly/);
126
+
127
+ webex.authorization._initialAuthorizationCodeGrantOutcome =
128
+ InitialAuthorizationCodeGrantOutcomes.success;
129
+
130
+ assert.equal(
131
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
132
+ InitialAuthorizationCodeGrantOutcomes.success
133
+ );
134
+ assert.calledOnceWithExactly(
135
+ changeSpy,
136
+ webex.authorization,
137
+ InitialAuthorizationCodeGrantOutcomes.success
138
+ );
139
+ });
140
+
107
141
  describe('#initialize()', () => {
108
142
  describe('when there is a code in the url', () => {
143
+ const csrfToken = 'initialization-csrf-token';
144
+ const makeAuthorizationCallbackUrl = (code, state = {}) =>
145
+ `http://example.com/?code=${code}&state=${base64.encode(
146
+ JSON.stringify({...state, csrf_token: csrfToken})
147
+ )}`;
148
+
109
149
  it('exchanges it for an access token and sets ready', () => {
110
- const webex = makeWebex('http://example.com/?code=5');
150
+ const webex = makeWebex(makeAuthorizationCallbackUrl('5'), csrfToken);
111
151
 
112
152
  assert.isFalse(webex.authorization.ready);
113
153
  assert.isFalse(webex.credentials.canAuthorize);
@@ -119,9 +159,25 @@ describe('plugin-authorization-browser-first-party', () => {
119
159
  assert.calledTwice(webex.request);
120
160
  assert.isTrue(webex.authorization.ready);
121
161
  assert.isTrue(webex.credentials.canAuthorize);
162
+ assert.equal(
163
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
164
+ InitialAuthorizationCodeGrantOutcomes.success
165
+ );
122
166
  });
123
167
  });
124
168
 
169
+ it('retains the initialization exchange outcome after logout', async () => {
170
+ const webex = makeWebex(makeAuthorizationCallbackUrl('5'), csrfToken);
171
+
172
+ await webex.authorization.when('change:ready');
173
+ webex.authorization.logout({noRedirect: true});
174
+
175
+ assert.equal(
176
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
177
+ InitialAuthorizationCodeGrantOutcomes.success
178
+ );
179
+ });
180
+
125
181
  it('validates the csrf token', () => {
126
182
  const csrfToken = 'abcd';
127
183
 
@@ -185,9 +241,8 @@ describe('plugin-authorization-browser-first-party', () => {
185
241
  it('collects the preauth catalog when emailhash is present in the state', async () => {
186
242
  const code = 'authcode_clusterid_theOrgId';
187
243
  const webex = makeWebex(
188
- `http://example.com/?code=${code}&state=${base64.encode(
189
- JSON.stringify({emailhash: 'someemailhash'})
190
- )}`
244
+ makeAuthorizationCallbackUrl(code, {emailhash: 'someemailhash'}),
245
+ csrfToken
191
246
  );
192
247
 
193
248
  const requestAuthorizationCodeGrantStub = sinon.stub(
@@ -208,7 +263,7 @@ describe('plugin-authorization-browser-first-party', () => {
208
263
 
209
264
  it('collects the preauth catalog no emailhash is present in the state', async () => {
210
265
  const code = 'authcode_clusterid_theOrgId';
211
- const webex = makeWebex(`http://example.com/?code=${code}`);
266
+ const webex = makeWebex(makeAuthorizationCallbackUrl(code), csrfToken);
212
267
 
213
268
  const requestAuthorizationCodeGrantStub = sinon.stub(
214
269
  Authorization.prototype,
@@ -228,7 +283,7 @@ describe('plugin-authorization-browser-first-party', () => {
228
283
 
229
284
  it('collects the preauth catalog with no emailhash and no orgId', async () => {
230
285
  const code = 'authcode_clusterid';
231
- const webex = makeWebex(`http://example.com/?code=${code}`);
286
+ const webex = makeWebex(makeAuthorizationCallbackUrl(code), csrfToken);
232
287
 
233
288
  const requestAuthorizationCodeGrantStub = sinon.stub(
234
289
  Authorization.prototype,
@@ -253,7 +308,7 @@ describe('plugin-authorization-browser-first-party', () => {
253
308
  .stub(Authorization.prototype, 'requestAuthorizationCodeGrant')
254
309
  .throws(error);
255
310
 
256
- const webex = makeWebex(`http://example.com?code=${code}`);
311
+ const webex = makeWebex(makeAuthorizationCallbackUrl(code), csrfToken);
257
312
 
258
313
  return webex.authorization.when('change:ready').then(() => {
259
314
  assert.calledOnce(requestAuthorizationCodeGrantStub);
@@ -264,8 +319,32 @@ describe('plugin-authorization-browser-first-party', () => {
264
319
  'authorization: failed initial authorization code grant request',
265
320
  error
266
321
  );
322
+ assert.equal(
323
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
324
+ InitialAuthorizationCodeGrantOutcomes.failure
325
+ );
267
326
  });
268
327
  });
328
+
329
+ it('retains failure when the automatic exchange promise rejects', async () => {
330
+ const error = new Error('exchange rejected');
331
+
332
+ sinon.stub(Authorization.prototype, 'requestAuthorizationCodeGrant').rejects(error);
333
+
334
+ const webex = makeWebex(makeAuthorizationCallbackUrl('5'), csrfToken);
335
+
336
+ await webex.authorization.when('change:ready');
337
+
338
+ assert.equal(
339
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
340
+ InitialAuthorizationCodeGrantOutcomes.failure
341
+ );
342
+ assert.calledOnceWithExactly(
343
+ webex.logger.warn,
344
+ 'authorization: failed initial authorization code grant request',
345
+ error
346
+ );
347
+ });
269
348
  });
270
349
  describe('when the url contains an error', () => {
271
350
  it('throws a grant error', () => {
@@ -287,14 +366,35 @@ describe('plugin-authorization-browser-first-party', () => {
287
366
 
288
367
  assert.isTrue(webex.authorization.ready);
289
368
  assert.isFalse(webex.credentials.canAuthorize);
369
+ assert.equal(
370
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
371
+ InitialAuthorizationCodeGrantOutcomes.notAttempted
372
+ );
373
+ });
374
+
375
+ it('does not treat a later authorization-code grant as the initialization exchange', async () => {
376
+ const webex = makeWebex('http://example.com');
377
+
378
+ await webex.authorization.requestAuthorizationCodeGrant({code: 'later-code'});
379
+
380
+ assert.equal(
381
+ webex.authorization.initialAuthorizationCodeGrantOutcome,
382
+ InitialAuthorizationCodeGrantOutcomes.notAttempted
383
+ );
290
384
  });
291
385
  });
292
386
 
293
387
  describe('when code verifier is present in session storage', () => {
294
388
  it('passes codeVerifier to requestAuthorizationCodeGrant', () => {
295
389
  const expectedVerifier = 'test verifier';
390
+ const csrfToken = 'initialization-csrf-token';
391
+ const state = base64.encode(JSON.stringify({csrf_token: csrfToken}));
296
392
 
297
- const webex = makeWebex('http://example.com?code=5', undefined, expectedVerifier);
393
+ const webex = makeWebex(
394
+ `http://example.com?code=5&state=${state}`,
395
+ csrfToken,
396
+ expectedVerifier
397
+ );
298
398
 
299
399
  return webex.authorization.when('change:ready').then(() => {
300
400
  assert.calledTwice(webex.request);
@@ -306,6 +406,139 @@ describe('plugin-authorization-browser-first-party', () => {
306
406
  });
307
407
  });
308
408
 
409
+ describe('#requestAuthorizationCodeGrant()', () => {
410
+ it('uses the client ID in the form for a public client', async () => {
411
+ const webex = makeWebex('http://example.com', undefined, undefined, {
412
+ credentials: {
413
+ clientType: 'public',
414
+ client_id: 'public-client-id',
415
+ },
416
+ });
417
+
418
+ await webex.authorization.requestAuthorizationCodeGrant({
419
+ code: 'authorization-code',
420
+ codeVerifier: 'code-verifier',
421
+ });
422
+
423
+ assert.calledOnceWithExactly(webex.request, {
424
+ method: 'POST',
425
+ uri: webex.config.credentials.tokenUrl,
426
+ form: {
427
+ grant_type: 'authorization_code',
428
+ redirect_uri: 'http://example.com',
429
+ code: 'authorization-code',
430
+ self_contained_token: true,
431
+ code_verifier: 'code-verifier',
432
+ client_id: 'public-client-id',
433
+ },
434
+ addAuthHeader: false,
435
+ shouldRefreshAccessToken: false,
436
+ });
437
+ });
438
+
439
+ it('uses HTTP Basic authentication for a confidential client', async () => {
440
+ const webex = makeWebex('http://example.com', undefined, undefined, {
441
+ credentials: {
442
+ clientType: 'confidential',
443
+ client_id: 'confidential-client-id',
444
+ client_secret: 'confidential-client-secret',
445
+ },
446
+ });
447
+
448
+ await webex.authorization.requestAuthorizationCodeGrant({
449
+ code: 'authorization-code',
450
+ codeVerifier: 'code-verifier',
451
+ });
452
+
453
+ assert.calledOnceWithExactly(webex.request, {
454
+ method: 'POST',
455
+ uri: webex.config.credentials.tokenUrl,
456
+ form: {
457
+ grant_type: 'authorization_code',
458
+ redirect_uri: 'http://example.com',
459
+ code: 'authorization-code',
460
+ self_contained_token: true,
461
+ code_verifier: 'code-verifier',
462
+ },
463
+ auth: {
464
+ user: 'confidential-client-id',
465
+ pass: 'confidential-client-secret',
466
+ sendImmediately: true,
467
+ },
468
+ shouldRefreshAccessToken: false,
469
+ });
470
+ });
471
+ });
472
+
473
+ describe('refreshCallback()', () => {
474
+ const tokenResponse = {
475
+ access_token: 'access-token',
476
+ refresh_token: 'refresh-token',
477
+ };
478
+
479
+ it('uses the client ID in the form for a public client', async () => {
480
+ const webex = {request: sinon.stub().resolves({body: tokenResponse})};
481
+ const token = {
482
+ refresh_token: 'current-refresh-token',
483
+ config: {
484
+ clientType: 'public',
485
+ client_id: 'public-client-id',
486
+ redirect_uri: 'http://example.com',
487
+ tokenUrl: 'https://idbroker.example.com/access_token',
488
+ },
489
+ };
490
+
491
+ const response = await authorizationConfig.credentials.refreshCallback(webex, token);
492
+
493
+ assert.calledOnceWithExactly(webex.request, {
494
+ method: 'POST',
495
+ uri: 'https://idbroker.example.com/access_token',
496
+ form: {
497
+ grant_type: 'refresh_token',
498
+ redirect_uri: 'http://example.com',
499
+ refresh_token: 'current-refresh-token',
500
+ client_id: 'public-client-id',
501
+ },
502
+ addAuthHeader: false,
503
+ shouldRefreshAccessToken: false,
504
+ });
505
+ assert.deepEqual(response, tokenResponse);
506
+ });
507
+
508
+ it('uses HTTP Basic authentication for a confidential client', async () => {
509
+ const webex = {request: sinon.stub().resolves({body: tokenResponse})};
510
+ const token = {
511
+ refresh_token: 'current-refresh-token',
512
+ config: {
513
+ clientType: 'confidential',
514
+ client_id: 'confidential-client-id',
515
+ client_secret: 'confidential-client-secret',
516
+ redirect_uri: 'http://example.com',
517
+ tokenUrl: 'https://idbroker.example.com/access_token',
518
+ },
519
+ };
520
+
521
+ const response = await authorizationConfig.credentials.refreshCallback(webex, token);
522
+
523
+ assert.calledOnceWithExactly(webex.request, {
524
+ method: 'POST',
525
+ uri: 'https://idbroker.example.com/access_token',
526
+ form: {
527
+ grant_type: 'refresh_token',
528
+ redirect_uri: 'http://example.com',
529
+ refresh_token: 'current-refresh-token',
530
+ },
531
+ auth: {
532
+ user: 'confidential-client-id',
533
+ pass: 'confidential-client-secret',
534
+ sendImmediately: true,
535
+ },
536
+ shouldRefreshAccessToken: false,
537
+ });
538
+ assert.deepEqual(response, tokenResponse);
539
+ });
540
+ });
541
+
309
542
  describe('#initiateLogin()', () => {
310
543
  it('calls #initiateAuthorizationCodeGrant()', () => {
311
544
  const webex = makeWebex(undefined, undefined, {
@@ -430,12 +663,14 @@ describe('plugin-authorization-browser-first-party', () => {
430
663
  const webex = makeWebex();
431
664
 
432
665
  const emitSpy = sinon.spy(webex.authorization.eventEmitter, 'emit');
433
- sinon.stub(webex.authorization, 'initiateAuthorizationCodeGrant').returns(Promise.resolve());
666
+ sinon
667
+ .stub(webex.authorization, 'initiateAuthorizationCodeGrant')
668
+ .returns(Promise.resolve());
434
669
 
435
670
  return webex.authorization.initiateLogin().then(() => {
436
671
  assert.calledOnceWithExactly(emitSpy, Events.login, {
437
672
  eventType: 'initiateLogin',
438
- data: { hasEmail: false, hasState: false },
673
+ data: {hasEmail: false, hasState: false},
439
674
  });
440
675
  });
441
676
  });
@@ -444,12 +679,14 @@ describe('plugin-authorization-browser-first-party', () => {
444
679
  const webex = makeWebex();
445
680
 
446
681
  const emitSpy = sinon.spy(webex.authorization.eventEmitter, 'emit');
447
- sinon.stub(webex.authorization, 'initiateAuthorizationCodeGrant').returns(Promise.resolve());
682
+ sinon
683
+ .stub(webex.authorization, 'initiateAuthorizationCodeGrant')
684
+ .returns(Promise.resolve());
448
685
 
449
- return webex.authorization.initiateLogin({ email: 'test@abc.xyz' }).then(() => {
686
+ return webex.authorization.initiateLogin({email: 'test@abc.xyz'}).then(() => {
450
687
  assert.calledOnceWithExactly(emitSpy, Events.login, {
451
688
  eventType: 'initiateLogin',
452
- data: { hasEmail: true, hasState: false },
689
+ data: {hasEmail: true, hasState: false},
453
690
  });
454
691
  });
455
692
  });
@@ -458,12 +695,14 @@ describe('plugin-authorization-browser-first-party', () => {
458
695
  const webex = makeWebex();
459
696
 
460
697
  const emitSpy = sinon.spy(webex.authorization.eventEmitter, 'emit');
461
- sinon.stub(webex.authorization, 'initiateAuthorizationCodeGrant').returns(Promise.resolve());
698
+ sinon
699
+ .stub(webex.authorization, 'initiateAuthorizationCodeGrant')
700
+ .returns(Promise.resolve());
462
701
 
463
- return webex.authorization.initiateLogin({ state: {} }).then(() => {
702
+ return webex.authorization.initiateLogin({state: {}}).then(() => {
464
703
  assert.calledOnceWithExactly(emitSpy, Events.login, {
465
704
  eventType: 'initiateLogin',
466
- data: { hasEmail: false, hasState: true },
705
+ data: {hasEmail: false, hasState: true},
467
706
  });
468
707
  });
469
708
  });
@@ -471,81 +710,87 @@ describe('plugin-authorization-browser-first-party', () => {
471
710
 
472
711
  describe('#initiateAuthorizationCodeGrant()', () => {
473
712
  it('redirects to the login page with response_type=code', () => {
474
- const webex = makeWebex(undefined, undefined, {
475
- credentials: {
476
- clientType: 'confidential',
477
- },
478
- });
713
+ const webex = makeWebex(undefined, undefined, {
714
+ credentials: {
715
+ clientType: 'confidential',
716
+ },
717
+ });
479
718
 
480
- sinon.spy(webex.authorization, 'initiateAuthorizationCodeGrant');
719
+ sinon.spy(webex.authorization, 'initiateAuthorizationCodeGrant');
481
720
 
482
- return webex.authorization.initiateLogin().then(() => {
483
- assert.called(webex.authorization.initiateAuthorizationCodeGrant);
484
- assert.include(webex.getWindow().location, 'response_type=code');
485
- });
721
+ return webex.authorization.initiateLogin().then(() => {
722
+ assert.called(webex.authorization.initiateAuthorizationCodeGrant);
723
+ assert.include(webex.getWindow().location, 'response_type=code');
724
+ });
486
725
  });
487
726
 
488
727
  it('redirects to the login page in the same window by default', () => {
489
- const webex = makeWebex();
728
+ const webex = makeWebex();
490
729
 
491
- return webex.authorization.initiateAuthorizationCodeGrant().then(() => {
492
- assert.isDefined(webex.getWindow().location);
493
- assert.isUndefined(webex.getWindow().open);
494
- });
730
+ return webex.authorization.initiateAuthorizationCodeGrant().then(() => {
731
+ assert.isDefined(webex.getWindow().location);
732
+ assert.isUndefined(webex.getWindow().open);
733
+ });
495
734
  });
496
735
 
497
736
  it('opens login page in a new window when separateWindow is true', () => {
498
- const webex = makeWebex();
499
- webex.getWindow().open = sinon.spy();
500
-
501
- return webex.authorization.initiateAuthorizationCodeGrant({ separateWindow: true }).then(() => {
502
- assert.called(webex.getWindow().open);
503
- const openCall = webex.getWindow().open.getCall(0);
504
- assert.equal(openCall.args[1], '_blank');
505
- assert.equal(openCall.args[2], 'width=600,height=800');
506
- });
737
+ const webex = makeWebex();
738
+ webex.getWindow().open = sinon.spy();
739
+
740
+ return webex.authorization
741
+ .initiateAuthorizationCodeGrant({separateWindow: true})
742
+ .then(() => {
743
+ assert.called(webex.getWindow().open);
744
+ const openCall = webex.getWindow().open.getCall(0);
745
+ assert.equal(openCall.args[1], '_blank');
746
+ assert.equal(openCall.args[2], 'width=600,height=800');
747
+ });
507
748
  });
508
749
 
509
750
  it('opens login page in a new window with custom dimensions', () => {
510
- const webex = makeWebex();
511
- webex.getWindow().open = sinon.spy();
751
+ const webex = makeWebex();
752
+ webex.getWindow().open = sinon.spy();
512
753
 
513
- const customWindow = {
514
- width: 800,
515
- height: 600,
516
- menubar: 'no',
517
- toolbar: 'no'
518
- };
754
+ const customWindow = {
755
+ width: 800,
756
+ height: 600,
757
+ menubar: 'no',
758
+ toolbar: 'no',
759
+ };
519
760
 
520
- return webex.authorization.initiateAuthorizationCodeGrant({
521
- separateWindow: customWindow
522
- }).then(() => {
523
- assert.called(webex.getWindow().open);
524
- const openCall = webex.getWindow().open.getCall(0);
525
- assert.equal(openCall.args[1], '_blank');
526
- assert.equal(
527
- openCall.args[2],
528
- 'width=800,height=600,menubar=no,toolbar=no'
529
- );
530
- });
761
+ return webex.authorization
762
+ .initiateAuthorizationCodeGrant({
763
+ separateWindow: customWindow,
764
+ })
765
+ .then(() => {
766
+ assert.called(webex.getWindow().open);
767
+ const openCall = webex.getWindow().open.getCall(0);
768
+ assert.equal(openCall.args[1], '_blank');
769
+ assert.equal(openCall.args[2], 'width=800,height=600,menubar=no,toolbar=no');
770
+ });
531
771
  });
532
772
 
533
773
  it('preserves other options when using separateWindow', () => {
534
- const webex = makeWebex();
535
- webex.getWindow().open = sinon.spy();
536
-
537
- return webex.authorization.initiateAuthorizationCodeGrant({
538
- separateWindow: true,
539
- state: {}
540
- }).then(() => {
541
- assert.called(webex.getWindow().open);
542
- const url = webex.getWindow().open.getCall(0).args[0];
543
- assert.include(url, "https://idbrokerbts.webex.com/idb/oauth2/v1/authorize?response_type=code&separateWindow=true&client_id=fake&redirect_uri=http%3A%2F%2Fexample.com&scope=scope%3Aone");
544
- });
774
+ const webex = makeWebex();
775
+ webex.getWindow().open = sinon.spy();
776
+
777
+ return webex.authorization
778
+ .initiateAuthorizationCodeGrant({
779
+ separateWindow: true,
780
+ state: {},
781
+ })
782
+ .then(() => {
783
+ assert.called(webex.getWindow().open);
784
+ const url = webex.getWindow().open.getCall(0).args[0];
785
+ assert.include(
786
+ url,
787
+ 'https://idbrokerbts.webex.com/idb/oauth2/v1/authorize?response_type=code&separateWindow=true&client_id=fake&redirect_uri=http%3A%2F%2Fexample.com&scope=scope%3Aone'
788
+ );
789
+ });
545
790
  });
546
791
 
547
792
  it('Emits an event containing the login url', () => {
548
- const testLoginUrl = "https://test.example.com";
793
+ const testLoginUrl = 'https://test.example.com';
549
794
  const webex = makeWebex();
550
795
 
551
796
  sinon.stub(webex.credentials, 'buildLoginUrl').returns(testLoginUrl);
@@ -554,17 +799,266 @@ describe('plugin-authorization-browser-first-party', () => {
554
799
  return webex.authorization.initiateAuthorizationCodeGrant().then(() => {
555
800
  assert.calledOnceWithExactly(emitSpy, Events.login, {
556
801
  eventType: 'redirectToLoginUrl',
557
- data: { loginUrl: testLoginUrl },
802
+ data: {loginUrl: testLoginUrl},
558
803
  });
559
804
  });
560
805
  });
561
806
  });
562
807
 
808
+ describe('#initiateThirdPartyLogin()', () => {
809
+ it('generates a csrf_token, embeds it in state, and delegates to #initiateThirdPartyLoginRedirect', () => {
810
+ const webex = makeWebex();
811
+ const expected = Promise.resolve();
812
+ const stub = sinon
813
+ .stub(webex.authorization, 'initiateThirdPartyLoginRedirect')
814
+ .returns(expected);
815
+ sinon.stub(webex.authorization, '_generateSecurityToken').returns('csrf-1234');
816
+ const options = {
817
+ oauth2provider: 'google',
818
+ returnURL: 'https://web.webex.com',
819
+ };
820
+
821
+ const result = webex.authorization.initiateThirdPartyLogin(options);
822
+
823
+ assert.equal(result, expected);
824
+ assert.calledOnce(webex.authorization._generateSecurityToken);
825
+ assert.calledOnce(stub);
826
+ const passed = stub.getCall(0).args[0];
827
+
828
+ assert.deepEqual(passed, {
829
+ oauth2provider: 'google',
830
+ returnURL: 'https://web.webex.com',
831
+ state: {csrf_token: 'csrf-1234'},
832
+ });
833
+ // Caller's options object is not mutated
834
+ assert.notProperty(options, 'state');
835
+
836
+ return result;
837
+ });
838
+
839
+ it('merges generated csrf_token into caller-supplied state without mutating the caller object', () => {
840
+ const webex = makeWebex();
841
+ sinon
842
+ .stub(webex.authorization, 'initiateThirdPartyLoginRedirect')
843
+ .returns(Promise.resolve());
844
+ sinon.stub(webex.authorization, '_generateSecurityToken').returns('csrf-1234');
845
+ const options = {
846
+ oauth2provider: 'google',
847
+ returnURL: 'https://web.webex.com',
848
+ state: {popUpSignIn: true, mode: 'meeting'},
849
+ };
850
+
851
+ return webex.authorization.initiateThirdPartyLogin(options).then(() => {
852
+ const passed = webex.authorization.initiateThirdPartyLoginRedirect.getCall(0).args[0];
853
+
854
+ assert.deepEqual(passed.state, {
855
+ popUpSignIn: true,
856
+ mode: 'meeting',
857
+ csrf_token: 'csrf-1234',
858
+ });
859
+ // Caller-supplied state is not mutated
860
+ assert.deepEqual(options.state, {popUpSignIn: true, mode: 'meeting'});
861
+ });
862
+ });
863
+
864
+ it('throws (before generating a csrf_token) when state is supplied but is not an object', () => {
865
+ const webex = makeWebex();
866
+ const redirectStub = sinon.stub(webex.authorization, 'initiateThirdPartyLoginRedirect');
867
+ const tokenStub = sinon.stub(webex.authorization, '_generateSecurityToken');
868
+
869
+ assert.throws(
870
+ () =>
871
+ webex.authorization.initiateThirdPartyLogin({
872
+ oauth2provider: 'google',
873
+ returnURL: 'https://web.webex.com',
874
+ state: 'not-an-object',
875
+ }),
876
+ /`options.state` must be an object/
877
+ );
878
+
879
+ assert.notCalled(tokenStub);
880
+ assert.notCalled(redirectStub);
881
+ });
882
+ });
883
+
884
+ describe('#initiateThirdPartyLoginRedirect()', () => {
885
+ it('builds the third-party login URL and assigns it to getWindow().location', () => {
886
+ const webex = makeWebex();
887
+ const builtUrl =
888
+ 'https://idbroker.webex.com/idb/ThirdPartyLogin?oauth2provider=google&returnURL=https%3A%2F%2Fweb.webex.com';
889
+ sinon.stub(webex.credentials, 'buildThirdPartyLoginUrl').returns(builtUrl);
890
+
891
+ return webex.authorization
892
+ .initiateThirdPartyLoginRedirect({
893
+ oauth2provider: 'google',
894
+ returnURL: 'https://web.webex.com',
895
+ })
896
+ .then(() => {
897
+ assert.calledOnceWithExactly(webex.credentials.buildThirdPartyLoginUrl, {
898
+ oauth2provider: 'google',
899
+ returnURL: 'https://web.webex.com',
900
+ });
901
+ assert.equal(webex.getWindow().location, builtUrl);
902
+ });
903
+ });
904
+
905
+ it('returns a rejected promise if buildThirdPartyLoginUrl throws', () => {
906
+ const webex = makeWebex();
907
+ sinon
908
+ .stub(webex.credentials, 'buildThirdPartyLoginUrl')
909
+ .throws(new Error('`options.oauth2provider` is required'));
910
+
911
+ return assert.isRejected(
912
+ webex.authorization.initiateThirdPartyLoginRedirect({}),
913
+ /`options.oauth2provider` is required/
914
+ );
915
+ });
916
+ });
917
+
918
+ describe('#_verifySecurityToken()', () => {
919
+ it('throws when no stored token exists', () => {
920
+ const webex = makeWebex();
921
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns(null);
922
+
923
+ assert.throws(() => {
924
+ webex.authorization._verifySecurityToken({});
925
+ }, /CSRF token missing from session storage/);
926
+ });
927
+ });
928
+
929
+ describe('#handleThirdPartyCallback()', () => {
930
+ const buildState = (state) => base64.toBase64Url(JSON.stringify(state));
931
+
932
+ // Mirror the SDK behaviour: replaceState writes the cleaned URL to
933
+ // location.href, so we can re-parse it and assert against named query
934
+ // params instead of substring-matching the raw URL.
935
+ const parseLocationQuery = (webex) => url.parse(webex.getWindow().location.href, true).query;
936
+
937
+ it('CSRF round-trip succeeds, scrubs sensitive params, and resolves with payload', () => {
938
+ const storedToken = 'csrf-abc';
939
+ const state = {csrf_token: storedToken, popUpSignIn: true, mode: 'meeting'};
940
+ const search = `?id_token=id-1&email=user%40example.com&state=${buildState(state)}`;
941
+ const webex = makeWebex(`http://example.com/${search}`, storedToken);
942
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns(storedToken);
943
+
944
+ const result = webex.authorization.handleThirdPartyCallback();
945
+
946
+ assert.deepEqual(result, {
947
+ idToken: 'id-1',
948
+ email: 'user@example.com',
949
+ error: undefined,
950
+ state: {popUpSignIn: true, mode: 'meeting'},
951
+ });
952
+ // Stored token consumed
953
+ assert.calledWith(webex.getWindow().sessionStorage.removeItem, 'oauth2-csrf-token');
954
+ // URL scrubbed: no id_token/email/csrf_token left, residual state re-encoded.
955
+ assert.called(webex.getWindow().history.replaceState);
956
+ const cleanedQuery = parseLocationQuery(webex);
957
+
958
+ assert.notProperty(cleanedQuery, 'id_token');
959
+ assert.notProperty(cleanedQuery, 'email');
960
+ assert.deepEqual(JSON.parse(base64.decode(cleanedQuery.state)), {
961
+ popUpSignIn: true,
962
+ mode: 'meeting',
963
+ });
964
+ });
965
+
966
+ it('throws when no stored CSRF token (treated as CSRF failure)', () => {
967
+ const search = `?id_token=id-1&state=${buildState({csrf_token: 'csrf-abc'})}`;
968
+ const webex = makeWebex(`http://example.com/${search}`);
969
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns(null);
970
+
971
+ assert.throws(
972
+ () => webex.authorization.handleThirdPartyCallback(),
973
+ /CSRF token missing from session storage/
974
+ );
975
+ });
976
+
977
+ it('throws when state.csrf_token does not match stored token', () => {
978
+ const search = `?id_token=id-1&state=${buildState({csrf_token: 'attacker'})}`;
979
+ const webex = makeWebex(`http://example.com/${search}`, 'real-token');
980
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns('real-token');
981
+
982
+ assert.throws(
983
+ () => webex.authorization.handleThirdPartyCallback(),
984
+ /CSRF token attacker does not match stored token real-token/
985
+ );
986
+ });
987
+
988
+ it('throws the native decode error (not a wrapped message) when state is malformed', () => {
989
+ // base64('not json') decodes to 'not json' which is not valid JSON
990
+ const search = `?id_token=id-1&state=bm90IGpzb24%3D`;
991
+ const webex = makeWebex(`http://example.com/${search}`, 'csrf-abc');
992
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns('csrf-abc');
993
+
994
+ // _verifySecurityToken is never reached because decode throws first;
995
+ // surface the underlying SyntaxError untouched.
996
+ assert.throws(() => webex.authorization.handleThirdPartyCallback(), SyntaxError);
997
+ });
998
+
999
+ it('throws on error responses that lack a valid state (still verifies CSRF)', () => {
1000
+ // Social provider returned ?error=... without echoing state. We must
1001
+ // not silently treat this as a successful callback.
1002
+ const search = `?error=FailedToCallOAuthProvider`;
1003
+ const webex = makeWebex('http://example.com', 'csrf-abc');
1004
+ webex.getWindow().location.href = `http://example.com/${search}`;
1005
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns('csrf-abc');
1006
+
1007
+ assert.throws(
1008
+ () => webex.authorization.handleThirdPartyCallback(),
1009
+ /Expected CSRF token csrf-abc, but not found in redirect query/
1010
+ );
1011
+ });
1012
+
1013
+ it('throws CSRF error when location has no query params at all', () => {
1014
+ const webex = makeWebex('http://example.com/', 'csrf-abc');
1015
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns('csrf-abc');
1016
+
1017
+ assert.throws(
1018
+ () => webex.authorization.handleThirdPartyCallback(),
1019
+ /Expected CSRF token csrf-abc, but not found in redirect query/
1020
+ );
1021
+ });
1022
+
1023
+ it('throws when state is absent and no stored CSRF token exists', () => {
1024
+ const webex = makeWebex('http://example.com/?id_token=id-1');
1025
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns(null);
1026
+
1027
+ assert.throws(
1028
+ () => webex.authorization.handleThirdPartyCallback(),
1029
+ /CSRF token missing from session storage/
1030
+ );
1031
+ });
1032
+
1033
+ it('returns error value in the result and preserves non-csrf state', () => {
1034
+ const storedToken = 'csrf-abc';
1035
+ const search = `?error=FailedToCallOAuthProvider&state=${buildState({
1036
+ csrf_token: storedToken,
1037
+ popUpSignIn: true,
1038
+ })}`;
1039
+ const webex = makeWebex('http://example.com', storedToken);
1040
+ webex.getWindow().location.href = `http://example.com/${search}`;
1041
+ webex.getWindow().sessionStorage.getItem = sinon.stub().returns(storedToken);
1042
+
1043
+ const result = webex.authorization.handleThirdPartyCallback();
1044
+
1045
+ assert.deepEqual(result, {
1046
+ idToken: undefined,
1047
+ email: undefined,
1048
+ error: 'FailedToCallOAuthProvider',
1049
+ state: {popUpSignIn: true},
1050
+ });
1051
+ // `error` is non-sensitive; not scrubbed from the URL.
1052
+ assert.equal(parseLocationQuery(webex).error, 'FailedToCallOAuthProvider');
1053
+ });
1054
+ });
1055
+
563
1056
  describe('#_generateQRCodeVerificationUrl()', () => {
564
1057
  it('should generate a QR code URL when a userCode is present', () => {
565
1058
  const verificationUrl = 'https://example.com/verify?userCode=123456';
566
1059
  const oauthHelperUrl = 'https://oauth-helper-a.wbx2.com/helperservice/v1';
567
- const expectedUrl = 'https://web.webex.com/deviceAuth?usercode=123456&oauthhelper=https%3A%2F%2Foauth-helper-a.wbx2.com%2Fhelperservice%2Fv1';
1060
+ const expectedUrl =
1061
+ 'https://web.webex.com/deviceAuth?usercode=123456&oauthhelper=https%3A%2F%2Foauth-helper-a.wbx2.com%2Fhelperservice%2Fv1';
568
1062
 
569
1063
  const webex = makeWebex('http://example.com');
570
1064
 
@@ -951,34 +1445,84 @@ describe('plugin-authorization-browser-first-party', () => {
951
1445
  });
952
1446
 
953
1447
  describe('#_generateCodeChallenge', () => {
954
- const expectedCodeChallenge = 'code challenge';
955
1448
  // eslint-disable-next-line no-underscore-dangle
956
1449
  const safeCharacterMap = CryptoJS.enc.Base64url._safe_map;
957
1450
 
958
- const expectedVerifier = times(128, () => safeCharacterMap[0]).join('');
1451
+ function makeWebexWithRandomValues(fillRandomValues) {
1452
+ const getRandomValuesStub = sinon.stub().callsFake((randomValues) => {
1453
+ fillRandomValues(randomValues);
959
1454
 
960
- it('generates a challenge code and stores it in session storage', () => {
961
- const webex = makeWebex('http://example.com');
1455
+ return randomValues;
1456
+ });
1457
+ const webex = makeWebex(
1458
+ 'http://example.com',
1459
+ undefined,
1460
+ undefined,
1461
+ {},
1462
+ getRandomValuesStub
1463
+ );
1464
+
1465
+ getRandomValuesStub.resetHistory();
1466
+ webex.getWindow().sessionStorage.setItem.resetHistory();
1467
+
1468
+ return {getRandomValuesStub, webex};
1469
+ }
1470
+
1471
+ it('uses a 128-byte CSPRNG and does not use insecure random generators', () => {
1472
+ const {getRandomValuesStub, webex} = makeWebexWithRandomValues((randomValues) => {
1473
+ randomValues.fill(0);
1474
+ });
1475
+ const mathRandomStub = sinon.stub(Math, 'random');
1476
+ const lodashRandomStub = sinon.stub(lodash, 'random');
1477
+
1478
+ // eslint-disable-next-line no-underscore-dangle
1479
+ webex.authorization._generateCodeChallenge();
1480
+
1481
+ const generatedRandomValues = getRandomValuesStub.firstCall.args[0];
1482
+
1483
+ assert.calledOnceWithExactly(getRandomValuesStub, generatedRandomValues);
1484
+ assert.instanceOf(generatedRandomValues, Uint8Array);
1485
+ assert.lengthOf(generatedRandomValues, 128);
1486
+ assert.notCalled(mathRandomStub);
1487
+ assert.notCalled(lodashRandomStub);
1488
+ });
962
1489
 
963
- const toStringStub = sinon.stub().returns(expectedCodeChallenge);
964
- const randomStub = sinon.stub(lodash, 'random').returns(0);
965
- const sha256Stub = sinon.stub(CryptoJS, 'SHA256').returns({
966
- toString: toStringStub,
1490
+ it('generates a 128-character verifier from the base64url-safe alphabet', () => {
1491
+ const {webex} = makeWebexWithRandomValues((randomValues) => {
1492
+ randomValues.set(times(128, (index) => index));
967
1493
  });
1494
+ const expectedVerifier = times(
1495
+ 128,
1496
+ (index) => safeCharacterMap[index & (safeCharacterMap.length - 1)]
1497
+ ).join('');
1498
+
1499
+ // eslint-disable-next-line no-underscore-dangle
1500
+ webex.authorization._generateCodeChallenge();
1501
+
1502
+ const storedVerifier = webex.getWindow().sessionStorage.setItem.firstCall.args[1];
1503
+
1504
+ assert.match(storedVerifier, /^[A-Za-z0-9_-]{128}$/);
1505
+ assert.equal(storedVerifier, expectedVerifier);
1506
+ });
1507
+
1508
+ it('stores the verifier and returns its SHA-256 base64url challenge', () => {
1509
+ const {webex} = makeWebexWithRandomValues((randomValues) => {
1510
+ randomValues.fill(42);
1511
+ });
1512
+ const expectedVerifier = safeCharacterMap[42 & (safeCharacterMap.length - 1)].repeat(128);
1513
+ const expectedChallenge = CryptoJS.SHA256(expectedVerifier).toString(
1514
+ CryptoJS.enc.Base64url
1515
+ );
968
1516
 
969
1517
  // eslint-disable-next-line no-underscore-dangle
970
1518
  const codeChallenge = webex.authorization._generateCodeChallenge();
971
1519
 
972
- assert.equal(codeChallenge, expectedCodeChallenge);
973
- assert.calledWith(sha256Stub, expectedVerifier);
974
- assert.calledWith(toStringStub, CryptoJS.enc.Base64url);
975
- assert.callCount(randomStub, 128);
976
- assert.calledWith(randomStub, 0, safeCharacterMap.length - 1);
977
- assert.calledWith(
1520
+ assert.calledOnceWithExactly(
978
1521
  webex.getWindow().sessionStorage.setItem,
979
1522
  'oauth2-code-verifier',
980
1523
  expectedVerifier
981
1524
  );
1525
+ assert.equal(codeChallenge, expectedChallenge);
982
1526
  });
983
1527
  });
984
1528
 
@@ -1027,7 +1571,33 @@ describe('plugin-authorization-browser-first-party', () => {
1027
1571
 
1028
1572
  assert.isDefined(href);
1029
1573
  assert.equal(href, `?state=${base64.encode(JSON.stringify({key: 'value'}))}`);
1030
- assert.notInclude(href, 'csrf_token');
1574
+ });
1575
+
1576
+ it('strips id_token and email from the query string', () => {
1577
+ const webex = makeWebex(undefined, undefined, {
1578
+ credentials: {
1579
+ clientType: 'confidential',
1580
+ },
1581
+ });
1582
+ const location = {
1583
+ query: {
1584
+ code: 'code',
1585
+ id_token: 'id-token-value',
1586
+ email: 'user@example.com',
1587
+ state: {
1588
+ csrf_token: 'token',
1589
+ key: 'value',
1590
+ },
1591
+ },
1592
+ };
1593
+
1594
+ webex.authorization._cleanUrl(location);
1595
+ assert.called(webex.getWindow().history.replaceState);
1596
+ const {href} = webex.getWindow().location;
1597
+
1598
+ assert.notInclude(href, 'id_token');
1599
+ assert.notInclude(href, 'email');
1600
+ assert.notInclude(href, 'code');
1031
1601
  });
1032
1602
  });
1033
1603