File: sync_auth_manager_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (951 lines) | stat: -rw-r--r-- 40,952 bytes parent folder | download | duplicates (6)
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sync/service/sync_auth_manager.h"

#include "base/run_loop.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "components/sync/engine/connection_status.h"
#include "components/sync/engine/sync_credentials.h"
#include "net/base/net_errors.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace syncer {

namespace {

class MockDelegate : public SyncAuthManager::Delegate {
 public:
  MockDelegate() = default;
  ~MockDelegate() override = default;

  MOCK_METHOD(void, SyncAuthAccountStateChanged, (), (override));
  MOCK_METHOD(void, SyncAuthCredentialsChanged, (), (override));
};

class SyncAuthManagerTest : public testing::Test {
 protected:
  SyncAuthManagerTest() : identity_env_(&test_url_loader_factory_) {}

  ~SyncAuthManagerTest() override = default;

  std::unique_ptr<SyncAuthManager> CreateAuthManager() {
    return std::make_unique<SyncAuthManager>(identity_env_.identity_manager(),
                                             &delegate_);
  }

  std::unique_ptr<SyncAuthManager> CreateAuthManagerForLocalSync() {
    return std::make_unique<SyncAuthManager>(nullptr, &delegate_);
  }

  signin::IdentityTestEnvironment* identity_env() { return &identity_env_; }
  MockDelegate& delegate() { return delegate_; }

 private:
  base::test::SingleThreadTaskEnvironment task_environment_;
  network::TestURLLoaderFactory test_url_loader_factory_;
  signin::IdentityTestEnvironment identity_env_;
  testing::NiceMock<MockDelegate> delegate_;
};

TEST_F(SyncAuthManagerTest, ProvidesNothingInLocalSyncMode) {
  std::unique_ptr<SyncAuthManager> auth_manager =
      CreateAuthManagerForLocalSync();
  EXPECT_TRUE(auth_manager->GetActiveAccountInfo().account_info.IsEmpty());
  syncer::SyncCredentials credentials = auth_manager->GetCredentials();
  EXPECT_TRUE(credentials.email.empty());
  EXPECT_TRUE(credentials.access_token.empty());
  EXPECT_TRUE(auth_manager->access_token().empty());
  // Note: Calling RegisterForAuthNotifications or any of the Connection*()
  // methods is illegal in local Sync mode, so we don't test that.
}

TEST_F(SyncAuthManagerTest, IgnoresEventsIfNotRegistered) {
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged).Times(0);
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged).Times(0);

  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();

  // Fire some auth events. We haven't called RegisterForAuthNotifications, so
  // none of this should result in any callback calls.
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  // Without RegisterForAuthNotifications, the active account should always be
  // reported as empty.
  EXPECT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());
  identity_env()->SetRefreshTokenForPrimaryAccount();
  EXPECT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());

// ChromeOS doesn't support sign-out.
#if !BUILDFLAG(IS_CHROMEOS)
  identity_env()->ClearPrimaryAccount();
  EXPECT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());
#endif  // !BUILDFLAG(IS_CHROMEOS)
}

// ChromeOS doesn't support sign-out.
#if !BUILDFLAG(IS_CHROMEOS)
TEST_F(SyncAuthManagerTest, ForwardsPrimaryAccountEvents) {
  // Start out already signed in before the SyncAuthManager is created.
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;

  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged).Times(0);
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged).Times(0);
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();

  auth_manager->RegisterForAuthNotifications();

  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  // Sign out of the account.
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged);
  // Note: The ordering of removing the refresh token and the actual sign-out is
  // undefined, see comment on IdentityManager::Observer. So we might or might
  // not get a `credentials_changed` call here.
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged).Times(testing::AtMost(1));
  identity_env()->ClearPrimaryAccount();
  EXPECT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());

  // Sign in to a different account.
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged);
  CoreAccountId second_account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  EXPECT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            second_account_id);
}

TEST_F(SyncAuthManagerTest, NotifiesOfSignoutBeforeAccessTokenIsGone) {
  // Start out already signed in before the SyncAuthManager is created.
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;

  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();

  auth_manager->RegisterForAuthNotifications();

  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();

  // Make sure an access token is available.
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Sign out of the account.
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged).WillOnce([&]() {
    // At the time the callback gets run, the access token should still be here.
    EXPECT_FALSE(auth_manager->GetCredentials().access_token.empty());
  });
  identity_env()->ClearPrimaryAccount();
  // After the signout is complete, the access token should be gone.
  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());
  ASSERT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

// Unconsented primary accounts are only supported on Win/Mac/Linux.
#if !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
TEST_F(SyncAuthManagerTest, ForwardsUnconsentedAccountEvents) {
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged).Times(0);
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged).Times(0);
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();

  ASSERT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());

  // Make a primary account available without Sync consent.
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged);
  AccountInfo account_info = identity_env()->MakePrimaryAccountAvailable(
      "test@email.com", signin::ConsentLevel::kSignin);

  EXPECT_FALSE(auth_manager->GetActiveAccountInfo().is_sync_consented);
  EXPECT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_info.account_id);

  // Make the account Sync-consented.
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged);
  signin::PrimaryAccountMutator* primary_account_mutator =
      identity_env()->identity_manager()->GetPrimaryAccountMutator();
  primary_account_mutator->SetPrimaryAccount(account_info.account_id,
                                             signin::ConsentLevel::kSync);

  EXPECT_TRUE(auth_manager->GetActiveAccountInfo().is_sync_consented);
}
#endif  // !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID) &&
        // !BUILDFLAG(IS_IOS)

// ChromeOS doesn't support sign-out.
#if !BUILDFLAG(IS_CHROMEOS)
TEST_F(SyncAuthManagerTest, ClearsAuthErrorOnSignoutWithRefreshTokenRemoval) {
  // Start out already signed in before the SyncAuthManager is created.
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;

  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();

  auth_manager->RegisterForAuthNotifications();

  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);
  ASSERT_EQ(auth_manager->GetLastAuthError().state(),
            GoogleServiceAuthError::NONE);

  // Sign out of the account.
  // The ordering of removing the refresh token and the actual sign-out is
  // undefined, see comment on IdentityManager::Observer. Here, explicitly
  // revoke the refresh token first (see also other test below which does *not*
  // remove the refresh token first).
  identity_env()->RemoveRefreshTokenForPrimaryAccount();

  // Note: Things are now in an intermediate state, where the primary account
  // still exists, but doesn't have a refresh token anymore. It doesn't really
  // matter whether the auth error is still there at this point.

  // Actually signing out, i.e. removing the primary account, should clear the
  // auth error, since it's now not meaningful anymore.
  identity_env()->ClearPrimaryAccount();
  EXPECT_EQ(auth_manager->GetLastAuthError().state(),
            GoogleServiceAuthError::NONE);
}

TEST_F(SyncAuthManagerTest,
       ClearsAuthErrorOnSignoutWithoutRefreshTokenRemoval) {
  // Start out already signed in before the SyncAuthManager is created.
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;

  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();

  auth_manager->RegisterForAuthNotifications();

  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);
  ASSERT_EQ(auth_manager->GetLastAuthError().state(),
            GoogleServiceAuthError::NONE);

  // Sign out of the account.
  // The ordering of removing the refresh token and the actual sign-out is
  // undefined, see comment on IdentityManager::Observer. Here, do *not* remove
  // the refresh token first (see also other test above which does remove it).

  // Signing out, i.e. removing the primary account, should clear the auth
  // error, since it's now not meaningful anymore.
  identity_env()->ClearPrimaryAccount();
  EXPECT_EQ(auth_manager->GetLastAuthError().state(),
            GoogleServiceAuthError::NONE);
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

TEST_F(SyncAuthManagerTest, DoesNotClearAuthErrorOnSyncDisable) {
  // Start out already signed in before the SyncAuthManager is created.
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;

  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();

  auth_manager->RegisterForAuthNotifications();

  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);
  ASSERT_EQ(auth_manager->GetLastAuthError().state(),
            GoogleServiceAuthError::NONE);

  auth_manager->ConnectionOpened();

  // Force an auth error by revoking the refresh token.
  identity_env()->SetInvalidRefreshTokenForPrimaryAccount();
  ASSERT_NE(auth_manager->GetLastAuthError().state(),
            GoogleServiceAuthError::NONE);

  // Now Sync gets turned off, e.g. because the user disabled it.
  auth_manager->ConnectionClosed();

  // Since the user is still signed in, the auth error should have remained.
  EXPECT_NE(auth_manager->GetLastAuthError().state(),
            GoogleServiceAuthError::NONE);
}

TEST_F(SyncAuthManagerTest, ForwardsCredentialsEvents) {
  // Start out already signed in before the SyncAuthManager is created.
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;

  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged).Times(0);
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged).Times(0);
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();

  auth_manager->RegisterForAuthNotifications();

  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();

  // Once an access token is available, the callback should get run.
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged);
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Now the refresh token gets updated. The access token will get dropped, so
  // this should cause another notification.
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged);
  identity_env()->SetRefreshTokenForPrimaryAccount();
  ASSERT_TRUE(auth_manager->GetCredentials().access_token.empty());

  // Once a new token is available, there's another notification.
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged);
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token_2", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token_2");

  // Revoking the refresh token should also cause the access token to get
  // dropped.
  // Note: On ChromeOS-Ash, setting an invalid refresh token causes 2
  // "credentials changed" events, one for the token change itself, and another
  // one for the auth error caused by the invalid token.
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged)
      .Times(testing::AtLeast(1));
  identity_env()->SetInvalidRefreshTokenForPrimaryAccount();
  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());
}

TEST_F(SyncAuthManagerTest, RequestsAccessTokenOnSyncStartup) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();

  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));

  EXPECT_EQ(auth_manager->GetCredentials().access_token, "access_token");
}

TEST_F(SyncAuthManagerTest,
       RetriesAccessTokenFetchWithBackoffOnTransientFailure) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();

  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      GoogleServiceAuthError::FromConnectionError(net::ERR_TIMED_OUT));

  // The access token fetch should get retried (with backoff, hence no actual
  // request yet), without exposing an auth error.
  EXPECT_TRUE(auth_manager->IsRetryingAccessTokenFetchForTest());
  EXPECT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());
}

TEST_F(SyncAuthManagerTest,
       RetriesAccessTokenFetchWithoutBackoffOnceOnFirstCancelTransientFailure) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();

  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));

  // Expect no backoff the first time the request is canceled.
  EXPECT_FALSE(auth_manager->IsRetryingAccessTokenFetchForTest());

  // Cancel the retry as well.
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));

  // Expect retry with backoff when the first retry was also canceled.
  EXPECT_TRUE(auth_manager->IsRetryingAccessTokenFetchForTest());
}

TEST_F(SyncAuthManagerTest,
       RetriesAccessTokenFetchOnFirstCancelTransientFailure) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();

  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));

  // Expect no backoff the first time the request is canceled.
  EXPECT_FALSE(auth_manager->IsRetryingAccessTokenFetchForTest());

  // Retry is a success.
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));

  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  // Don't expect any backoff when the retry is a success.
  EXPECT_FALSE(auth_manager->IsRetryingAccessTokenFetchForTest());
}

TEST_F(SyncAuthManagerTest, AbortsAccessTokenFetchOnPersistentFailure) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();

  GoogleServiceAuthError auth_error =
      GoogleServiceAuthError::FromInvalidGaiaCredentialsReason(
          GoogleServiceAuthError::InvalidGaiaCredentialsReason::
              CREDENTIALS_REJECTED_BY_SERVER);
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      auth_error);

  // Auth error should get exposed; no retry.
  EXPECT_FALSE(auth_manager->IsRetryingAccessTokenFetchForTest());
  EXPECT_EQ(auth_manager->GetLastAuthError(), auth_error);
}

TEST_F(SyncAuthManagerTest, FetchesNewAccessTokenWithBackoffOnServerError) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // The server is returning AUTH_ERROR - maybe something's wrong with the
  // token we got.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_AUTH_ERROR);

  // The access token fetch should get retried (with backoff, hence no actual
  // request yet), without exposing an auth error.
  EXPECT_TRUE(auth_manager->IsRetryingAccessTokenFetchForTest());
  EXPECT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());
}

TEST_F(SyncAuthManagerTest, DoesNotExposeServerError) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Now a server error happens.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_SERVER_ERROR);

  // The error should not be reported as it is transient.
  EXPECT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());
  EXPECT_EQ(auth_manager->GetCredentials().access_token, "access_token");
}

TEST_F(SyncAuthManagerTest, ClearsServerErrorOnSyncDisable) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // The server returns an auth error.
  GoogleServiceAuthError auth_error =
      GoogleServiceAuthError::FromInvalidGaiaCredentialsReason(
          GoogleServiceAuthError::InvalidGaiaCredentialsReason::
              CREDENTIALS_REJECTED_BY_SERVER);
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_AUTH_ERROR);
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      auth_error);

  ASSERT_NE(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // Now Sync gets turned off, e.g. because the user disabled it.
  auth_manager->ConnectionClosed();

  // This should not have cleared the auth error.
  EXPECT_NE(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());
}

TEST_F(SyncAuthManagerTest, RequestsNewAccessTokenOnExpiry) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Now everything is okay for a while.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_OK);
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  ASSERT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // But then the token expires, resulting in an auth error from the server.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_AUTH_ERROR);

  // Should immediately drop the access token and fetch a new one (no backoff).
  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());

  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token_2", base::Time::Now() + base::Hours(1));
  EXPECT_EQ(auth_manager->GetCredentials().access_token, "access_token_2");
}

TEST_F(SyncAuthManagerTest, RequestsNewAccessTokenOnRefreshTokenUpdate) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Now everything is okay for a while.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_OK);
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  ASSERT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // But then the refresh token changes.
  identity_env()->SetRefreshTokenForPrimaryAccount();

  // Should immediately drop the access token and fetch a new one (no backoff).
  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());

  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token_2", base::Time::Now() + base::Hours(1));
  EXPECT_EQ(auth_manager->GetCredentials().access_token, "access_token_2");
}

TEST_F(SyncAuthManagerTest, DoesNotRequestAccessTokenAutonomously) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  // Do *not* call ConnectionStatusChanged here (which is what usually kicks off
  // the token fetch).

  // Now the refresh token gets updated. If we already had an access token
  // before, then this should trigger a new fetch. But since that initial fetch
  // never happened (e.g. because Sync is turned off), this should do nothing.
  base::MockCallback<base::OnceClosure> access_token_requested;
  EXPECT_CALL(access_token_requested, Run()).Times(0);
  identity_env()->SetCallbackForNextAccessTokenRequest(
      access_token_requested.Get());
  identity_env()->SetRefreshTokenForPrimaryAccount();

  // Make sure no access token request was sent. Since the request goes through
  // posted tasks, we have to spin the message loop.
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());
}

TEST_F(SyncAuthManagerTest, ClearsCredentialsOnRefreshTokenRemoval) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Now everything is okay for a while.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_OK);
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  ASSERT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // But then the refresh token gets revoked. No new access token should get
  // requested due to this.
  base::MockCallback<base::OnceClosure> access_token_requested;
  EXPECT_CALL(access_token_requested, Run()).Times(0);
  identity_env()->SetCallbackForNextAccessTokenRequest(
      access_token_requested.Get());
  identity_env()->SetInvalidRefreshTokenForPrimaryAccount();

  // Should immediately drop the access token and expose an auth error.
  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());
  EXPECT_NE(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // No new access token should have been requested. Since the request goes
  // through posted tasks, we have to spin the message loop.
  base::RunLoop().RunUntilIdle();
}

TEST_F(SyncAuthManagerTest, ClearsCredentialsOnInvalidRefreshToken) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Now everything is okay for a while.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_OK);
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  ASSERT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // But now an invalid refresh token gets set, i.e. we enter the "Sync paused"
  // state. No new access token should get requested due to this.
  base::MockCallback<base::OnceClosure> access_token_requested;
  EXPECT_CALL(access_token_requested, Run()).Times(0);
  identity_env()->SetCallbackForNextAccessTokenRequest(
      access_token_requested.Get());
  identity_env()->SetInvalidRefreshTokenForPrimaryAccount();

  // Should immediately drop the access token and expose a special auth error.
  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());
  GoogleServiceAuthError invalid_token_error =
      GoogleServiceAuthError::FromInvalidGaiaCredentialsReason(
          GoogleServiceAuthError::InvalidGaiaCredentialsReason::
              CREDENTIALS_REJECTED_BY_CLIENT);
  EXPECT_EQ(auth_manager->GetLastAuthError(), invalid_token_error);
  EXPECT_TRUE(auth_manager->IsSyncPaused());

  // No new access token should have been requested. Since the request goes
  // through posted tasks, we have to spin the message loop.
  base::RunLoop().RunUntilIdle();
}

TEST_F(SyncAuthManagerTest, EntersPausedStateOnPersistentAuthError) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");

  // Now everything is okay for a while.
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_OK);
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  ASSERT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // But now an auth error happens.
  identity_env()->UpdatePersistentErrorOfRefreshTokenForAccount(
      auth_manager->GetActiveAccountInfo().account_info.account_id,
      GoogleServiceAuthError::FromServiceError("Test error"));

  // Should immediately drop the access token and enter the sync-paused state.
  EXPECT_TRUE(auth_manager->GetCredentials().access_token.empty());
  EXPECT_TRUE(auth_manager->GetLastAuthError().IsPersistentError());
  EXPECT_TRUE(auth_manager->IsSyncPaused());
}

TEST_F(SyncAuthManagerTest,
       RequestsAccessTokenWhenInvalidRefreshTokenResolved) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  // Sync starts up normally.
  auth_manager->ConnectionOpened();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  auth_manager->ConnectionStatusChanged(syncer::CONNECTION_OK);
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token");
  ASSERT_EQ(auth_manager->GetLastAuthError(),
            GoogleServiceAuthError::AuthErrorNone());

  // But now an invalid refresh token gets set, i.e. we enter the "Sync paused"
  // state.
  identity_env()->SetInvalidRefreshTokenForPrimaryAccount();
  ASSERT_TRUE(auth_manager->GetCredentials().access_token.empty());
  ASSERT_TRUE(auth_manager->IsSyncPaused());

  // Once the user signs in again and we have a valid refresh token, we should
  // also request a new access token.
  identity_env()->SetRefreshTokenForPrimaryAccount();
  identity_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      "access_token_2", base::Time::Now() + base::Hours(1));
  ASSERT_EQ(auth_manager->GetCredentials().access_token, "access_token_2");
}

TEST_F(SyncAuthManagerTest, DoesNotRequestAccessTokenIfSyncInactive) {
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;

  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged).Times(0);
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged).Times(0);
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  // Sync is *not* enabled; in particular we don't call ConnectionOpened().

  // An invalid refresh token gets set, i.e. we enter the "Sync paused" state
  // (only from SyncAuthManager's point of view - Sync as a whole is still
  // disabled).
  // Note: Depending on the exact sequence of IdentityManager::Observer calls
  // (refresh token changed and/or auth error changed), the credentials-changed
  // callback might get run multiple times.
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged)
      .Times(testing::AtLeast(1));
  identity_env()->SetInvalidRefreshTokenForPrimaryAccount();
  ASSERT_TRUE(auth_manager->GetCredentials().access_token.empty());
  ASSERT_TRUE(auth_manager->IsSyncPaused());

  // Once the user signs in again and we have a valid refresh token, we should
  // *not* request a new access token, since Sync isn't active.
  base::MockCallback<base::OnceClosure> access_token_requested;
  EXPECT_CALL(access_token_requested, Run()).Times(0);
  identity_env()->SetCallbackForNextAccessTokenRequest(
      access_token_requested.Get());
  // This *should* notify about changed credentials though, so that the
  // SyncService can decide to start syncing.
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged);
  identity_env()->SetRefreshTokenForPrimaryAccount();
  ASSERT_FALSE(auth_manager->IsSyncPaused());

  // Since the access token request goes through posted tasks, we have to spin
  // the message loop to make sure it didn't happen.
  base::RunLoop().RunUntilIdle();
}

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
// Primary account with no sync consent is not supported on Android and iOS.
TEST_F(SyncAuthManagerTest, PrimaryAccountWithNoSyncConsent) {
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();

  ASSERT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());

  // Make a primary account with no sync consent available.
  AccountInfo account_info = identity_env()->MakePrimaryAccountAvailable(
      "test@email.com", signin::ConsentLevel::kSignin);

  // Since unconsented primary account support is enabled, SyncAuthManager
  // should have picked up this account.
  EXPECT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_info.account_id);
}
#endif  // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)

#if !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
// Primary account with no sync consent is not supported on Android and iOS.
// On CrOS the unconsented primary account can't be changed or removed, but can
// be granted sync consent.
TEST_F(SyncAuthManagerTest, PicksNewPrimaryAccountWithSyncConsent) {
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();

  ASSERT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());

  // Make a primary account with no sync consent available.
  AccountInfo unconsented_primary_account_info =
      identity_env()->MakePrimaryAccountAvailable(
          "test@email.com", signin::ConsentLevel::kSignin);
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            unconsented_primary_account_info.account_id);

  // Once a primary account with sync consent becomes available, the unconsented
  // primary account should be overridden.
  AccountInfo primary_account_info =
      identity_env()->MakePrimaryAccountAvailable("primary@email.com",
                                                  signin::ConsentLevel::kSync);
  EXPECT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            primary_account_info.account_id);
}

TEST_F(SyncAuthManagerTest,
       DropsAccountWhenPrimaryAccountWithNoSyncConsentGoesAway) {
  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();

  // Make a primary account with no sync consent available.
  AccountInfo account_info = identity_env()->MakePrimaryAccountAvailable(
      "test@email.com", signin::ConsentLevel::kSignin);
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_info.account_id);

  identity_env()->ClearPrimaryAccount();
  EXPECT_TRUE(
      auth_manager->GetActiveAccountInfo().account_info.account_id.empty());
}
#endif  // !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID) &&
        // !BUILDFLAG(IS_IOS)

TEST_F(SyncAuthManagerTest, DetectsInvalidRefreshTokenAtStartup) {
  // There is a primary account, but it has an invalid refresh token (with a
  // persistent auth error).
  CoreAccountId account_id =
      identity_env()
          ->MakePrimaryAccountAvailable("test@email.com",
                                        signin::ConsentLevel::kSync)
          .account_id;
  identity_env()->SetInvalidRefreshTokenForPrimaryAccount();

  // On initialization, SyncAuthManager should pick up the auth error. This
  // should not result in a notification.
  EXPECT_CALL(delegate(), SyncAuthAccountStateChanged).Times(0);
  EXPECT_CALL(delegate(), SyncAuthCredentialsChanged).Times(0);

  std::unique_ptr<SyncAuthManager> auth_manager = CreateAuthManager();
  auth_manager->RegisterForAuthNotifications();
  ASSERT_EQ(auth_manager->GetActiveAccountInfo().account_info.account_id,
            account_id);

  EXPECT_TRUE(auth_manager->GetLastAuthError().IsPersistentError());
}

}  // namespace

}  // namespace syncer