@webex/plugin-authorization-browser-first-party 3.12.0-next.6 → 3.12.0-next.61

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