File: ip_protection_token_manager_impl_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 (1255 lines) | stat: -rw-r--r-- 56,464 bytes parent folder | download | duplicates (5)
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
// Copyright 2023 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/ip_protection/common/ip_protection_token_manager_impl.h"

#include <cstddef>
#include <cstdint>
#include <deque>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>

#include "base/strings/stringprintf.h"
#include "base/strings/to_string.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "components/ip_protection/common/ip_protection_core.h"
#include "components/ip_protection/common/ip_protection_data_types.h"
#include "components/ip_protection/common/ip_protection_telemetry.h"
#include "components/ip_protection/common/ip_protection_token_fetcher.h"
#include "components/ip_protection/common/ip_protection_token_manager.h"
#include "net/base/features.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ip_protection {

namespace {

constexpr char kGeoChangeTokenPresence[] =
    "NetworkService.IpProtection.GeoChangeTokenPresence";
constexpr char kGetAuthTokenResultHistogram[] =
    "NetworkService.IpProtection.GetAuthTokenResult";
constexpr char kProxyATokenSpendRateHistogram[] =
    "NetworkService.IpProtection.ProxyA.TokenSpendRate";
constexpr char kProxyATokenExpirationRateHistogram[] =
    "NetworkService.IpProtection.ProxyA.TokenExpirationRate";
constexpr char kProxyBTokenSpendRateHistogram[] =
    "NetworkService.IpProtection.ProxyB.TokenSpendRate";
constexpr char kProxyBTokenExpirationRateHistogram[] =
    "NetworkService.IpProtection.ProxyB.TokenExpirationRate";
constexpr char kTokenBatchGenerationTimeHistogram[] =
    "NetworkService.IpProtection.TokenBatchGenerationTime";
constexpr char kGetAuthTokenResultForGeoHistogram[] =
    "NetworkService.IpProtection.GetAuthTokenResultForGeo";
constexpr char kProxyATokenCountIssuedHistogram[] =
    "NetworkService.IpProtection.ProxyA.TokenCount.Issued";
constexpr char kProxyATokenCountSpentHistogram[] =
    "NetworkService.IpProtection.ProxyA.TokenCount.Spent";
constexpr char kProxyATokenCountExpiredHistogram[] =
    "NetworkService.IpProtection.ProxyA.TokenCount.Expired";
constexpr char kProxyBTokenCountIssuedHistogram[] =
    "NetworkService.IpProtection.ProxyB.TokenCount.Issued";
constexpr char kProxyBTokenCountSpentHistogram[] =
    "NetworkService.IpProtection.ProxyB.TokenCount.Spent";
constexpr char kProxyBTokenCountExpiredHistogram[] =
    "NetworkService.IpProtection.ProxyB.TokenCount.Expired";

constexpr base::TimeDelta kTokenLimitExceededDelay = base::Minutes(10);
constexpr base::TimeDelta kTokenRateMeasurementInterval = base::Minutes(5);

const GeoHint kMountainViewGeo = {.country_code = "US",
                                  .iso_region = "US-CA",
                                  .city_name = "MOUNTAIN VIEW"};
const std::string kMountainViewGeoId = GetGeoIdFromGeoHint(kMountainViewGeo);

const GeoHint kSunnyvaleGeo = {.country_code = "US",
                               .iso_region = "US-CA",
                               .city_name = "SUNNYVALE"};
const std::string kSunnyvaleGeoId = GetGeoIdFromGeoHint(kSunnyvaleGeo);

struct ExpectedTryGetAuthTokensCall {
  // The expected batch_size argument for the call.
  uint32_t batch_size;
  // The response to the call.
  std::optional<std::vector<BlindSignedAuthToken>> bsa_tokens;
  std::optional<base::Time> try_again_after;
};

class MockIpProtectionTokenFetcher : public IpProtectionTokenFetcher {
 public:
  ~MockIpProtectionTokenFetcher() override = default;

  // Register an expectation of a call to `TryGetAuthTokens()` returning the
  // given tokens.
  void ExpectTryGetAuthTokensCall(
      uint32_t batch_size,
      std::vector<BlindSignedAuthToken> bsa_tokens) {
    expected_try_get_auth_token_calls_.emplace_back(
        ExpectedTryGetAuthTokensCall{
            .batch_size = batch_size,
            .bsa_tokens = std::move(bsa_tokens),
            .try_again_after = std::nullopt,
        });
  }

  // Register an expectation of a call to `TryGetAuthTokens()` returning no
  // tokens and the given `try_again_after`.
  void ExpectTryGetAuthTokensCall(uint32_t batch_size,
                                  base::Time try_again_after) {
    expected_try_get_auth_token_calls_.emplace_back(
        ExpectedTryGetAuthTokensCall{
            .batch_size = batch_size,
            .bsa_tokens = std::nullopt,
            .try_again_after = try_again_after,
        });
  }

  // True if all expected `TryGetAuthTokens` calls have occurred.
  bool GotAllExpectedMockCalls() {
    return expected_try_get_auth_token_calls_.empty();
  }

  // Reset all test expectations.
  void Reset() { expected_try_get_auth_token_calls_.clear(); }

  void TryGetAuthTokens(uint32_t batch_size,
                        ProxyLayer proxy_layer,
                        TryGetAuthTokensCallback callback) override {
    ASSERT_FALSE(expected_try_get_auth_token_calls_.empty())
        << "Unexpected call to TryGetAuthTokens";
    auto& exp = expected_try_get_auth_token_calls_.front();
    EXPECT_EQ(batch_size, exp.batch_size);
    std::move(callback).Run(std::move(exp.bsa_tokens), exp.try_again_after);
    expected_try_get_auth_token_calls_.pop_front();
  }

 protected:
  std::deque<ExpectedTryGetAuthTokensCall> expected_try_get_auth_token_calls_;
};

class MockIpProtectionCore : public IpProtectionCore {
 public:
  MOCK_METHOD(void, GeoObserved, (const std::string& geo_id), (override));

  // Dummy implementations for functions not tested in this file.
  bool IsMdlPopulated() override { return false; }
  bool RequestShouldBeProxied(
      const GURL& request_url,
      const net::NetworkAnonymizationKey& network_anonymization_key) override {
    return false;
  }
  bool IsIpProtectionEnabled() override { return true; }
  bool AreAuthTokensAvailable() override { return false; }
  bool IsProbabilisticRevealTokenAvailable() override { NOTREACHED(); }
  bool WereTokenCachesEverFilled() override { return false; }
  std::optional<BlindSignedAuthToken> GetAuthToken(
      size_t chain_index) override {
    return std::nullopt;
  }
  std::optional<std::string> GetProbabilisticRevealToken(
      const std::string& top_level,
      const std::string& third_party) override {
    NOTREACHED();
  }
  bool IsProxyListAvailable() override { return false; }
  void QuicProxiesFailed() override {}
  std::vector<net::ProxyChain> GetProxyChainList() override { return {}; }
  void RequestRefreshProxyList() override {}
  bool HasTrackingProtectionException(
      const GURL& first_party_url) const override {
    return false;
  }
  void SetTrackingProtectionContentSetting(
      const ContentSettingsForOneType& settings) override {}
  bool ShouldRequestIncludeProbabilisticRevealToken(
      const GURL& request_url) override {
    return false;
  }
};

struct HistogramState {
  // Number of successful calls to GetAuthToken (true).
  int success;
  // Number of failed calls to GetAuthToken (false).
  int failure;
  // Number of successful token batch generations.
  int generated;
};

class IpProtectionTokenManagerImplTest : public testing::Test {
 protected:
  IpProtectionTokenManagerImplTest() {
    auto ipp_proxy_a_token_fetcher =
        std::make_unique<MockIpProtectionTokenFetcher>();
    ipp_proxy_a_token_fetcher_ = ipp_proxy_a_token_fetcher.get();
    auto ipp_proxy_b_token_fetcher =
        std::make_unique<MockIpProtectionTokenFetcher>();
    ipp_proxy_b_token_fetcher_ = ipp_proxy_b_token_fetcher.get();

    // Default behavior for `GeoObserved`. The default is defined here
    // (instead of in the mock) to allow access to the local instances of the
    // token cache managers.
    ON_CALL(mock_core_, GeoObserved(testing::_))
        .WillByDefault([this](const std::string& geo_id) {
          if (ipp_proxy_a_token_manager_->CurrentGeo() != geo_id) {
            ipp_proxy_a_token_manager_->SetCurrentGeo(geo_id);
          }
          if (ipp_proxy_b_token_manager_->CurrentGeo() != geo_id) {
            ipp_proxy_b_token_manager_->SetCurrentGeo(geo_id);
          }
        });

    ipp_proxy_a_token_manager_ = std::make_unique<IpProtectionTokenManagerImpl>(
        &mock_core_, std::move(ipp_proxy_a_token_fetcher), ProxyLayer::kProxyA,
        /* disable_cache_management_for_testing=*/true);
    ipp_proxy_b_token_manager_ = std::make_unique<IpProtectionTokenManagerImpl>(
        &mock_core_, std::move(ipp_proxy_b_token_fetcher), ProxyLayer::kProxyB,
        /* disable_cache_management_for_testing=*/true);

    // Default to disabling token expiration fuzzing.
    ipp_proxy_a_token_manager_->EnableTokenExpirationFuzzingForTesting(false);
    ipp_proxy_b_token_manager_->EnableTokenExpirationFuzzingForTesting(false);
  }

  void ExpectHistogramState(HistogramState state) {
    histogram_tester_.ExpectBucketCount(kGetAuthTokenResultHistogram, true,
                                        state.success);
    histogram_tester_.ExpectBucketCount(kGetAuthTokenResultHistogram, false,
                                        state.failure);
    histogram_tester_.ExpectTotalCount(kTokenBatchGenerationTimeHistogram,
                                       state.generated);
  }

  // Create a batch of tokens.
  std::vector<BlindSignedAuthToken> TokenBatch(
      int count,
      base::Time expiration,
      GeoHint geo_hint = kMountainViewGeo) {
    std::vector<BlindSignedAuthToken> tokens;
    for (int i = 0; i < count; i++) {
      tokens.emplace_back(
          BlindSignedAuthToken{.token = base::StringPrintf("token-%d", i),
                               .expiration = expiration,
                               .geo_hint = geo_hint});
    }
    return tokens;
  }

  void CallTryGetAuthTokensAndWait(ProxyLayer proxy_layer) {
    if (proxy_layer == ProxyLayer::kProxyA) {
      ipp_proxy_a_token_manager_->SetOnTryGetAuthTokensCompletedForTesting(
          task_environment_.QuitClosure());
      ipp_proxy_a_token_manager_->CallTryGetAuthTokensForTesting();
    } else {
      ipp_proxy_b_token_manager_->SetOnTryGetAuthTokensCompletedForTesting(
          task_environment_.QuitClosure());
      ipp_proxy_b_token_manager_->CallTryGetAuthTokensForTesting();
    }
    task_environment_.RunUntilQuit();
  }

  // Wait until the cache fills itself.
  void WaitForTryGetAuthTokensCompletion(ProxyLayer proxy_layer) {
    if (proxy_layer == ProxyLayer::kProxyA) {
      ipp_proxy_a_token_manager_->SetOnTryGetAuthTokensCompletedForTesting(
          task_environment_.QuitClosure());
    } else {
      ipp_proxy_b_token_manager_->SetOnTryGetAuthTokensCompletedForTesting(
          task_environment_.QuitClosure());
    }
    task_environment_.RunUntilQuit();
  }

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};

  int expected_batch_size_ =
      net::features::kIpPrivacyAuthTokenCacheBatchSize.Get();
  int cache_low_water_mark_ =
      net::features::kIpPrivacyAuthTokenCacheLowWaterMark.Get();

  // Expiration times with respect to the TaskEnvironment's mock time.
  const base::Time kFutureExpiration = base::Time::Now() + base::Hours(1);
  const base::Time kPastExpiration = base::Time::Now() - base::Hours(1);

  testing::NiceMock<MockIpProtectionCore> mock_core_;

  std::unique_ptr<IpProtectionTokenManagerImpl> ipp_proxy_a_token_manager_;
  std::unique_ptr<IpProtectionTokenManagerImpl> ipp_proxy_b_token_manager_;

  raw_ptr<MockIpProtectionTokenFetcher> ipp_proxy_a_token_fetcher_;
  raw_ptr<MockIpProtectionTokenFetcher> ipp_proxy_b_token_fetcher_;

  base::HistogramTester histogram_tester_;
};

// `IsAuthTokenAvailable()` returns false on an empty cache.
TEST_F(IpProtectionTokenManagerImplTest, IsAuthTokenAvailableFalseEmpty) {
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kFutureExpiration, kSunnyvaleGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Looking for geo that is not found in the token. In this case, only
  // sunnyvale tokens are available, thus, a check for Mountain View will be
  // false.
  EXPECT_FALSE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));

  // Although the tokens were not available for a given geo, the cache had
  // already been filled at some point.
  EXPECT_TRUE(ipp_proxy_a_token_manager_->WasTokenCacheEverFilled());
}

// `IsAuthTokenAvailable()` returns true on a cache containing unexpired
// tokens.
TEST_F(IpProtectionTokenManagerImplTest, IsAuthTokenAvailable_ReturnsTrue) {
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  EXPECT_TRUE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));
  EXPECT_TRUE(ipp_proxy_a_token_manager_->WasTokenCacheEverFilled());
}

// `IsAuthTokenAvailable()` returns false on a geo's cache containing expired
// tokens.
TEST_F(IpProtectionTokenManagerImplTest,
       IsAuthTokenAvailable_TokensExpired_ReturnsFalse) {
  // Expired tokens added
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kPastExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  EXPECT_FALSE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));

  // Cache has been filled at some point despite expired tokens.
  EXPECT_TRUE(ipp_proxy_a_token_manager_->WasTokenCacheEverFilled());
}

// `GetAuthToken()` returns nullopt on an empty cache for specified geo.
TEST_F(IpProtectionTokenManagerImplTest,
       GetAuthToken_EmptyCache_ReturnsEmptyOptional) {
  EXPECT_FALSE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
  ExpectHistogramState(HistogramState{.success = 0, .failure = 1});
  histogram_tester_.ExpectUniqueSample(
      kGetAuthTokenResultForGeoHistogram,
      AuthTokenResultForGeo::kUnavailableCacheEmpty, 1);
}

// `GetAuthToken()` returns a token cached by geo.
TEST_F(IpProtectionTokenManagerImplTest, GetAuthToken_ReturnsToken) {
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  std::optional<BlindSignedAuthToken> token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);

  ASSERT_TRUE(token);
  EXPECT_EQ(token->token, "token-0");
  EXPECT_EQ(token->expiration, kFutureExpiration);
  EXPECT_EQ(token->geo_hint, kMountainViewGeo);
  ExpectHistogramState(
      HistogramState{.success = 1, .failure = 0, .generated = 1});
  histogram_tester_.ExpectUniqueSample(
      kGetAuthTokenResultForGeoHistogram,
      AuthTokenResultForGeo::kAvailableForCurrentGeo, 1);
}

// `GetAuthToken()` requested for geo not available while other tokens are
// available.
TEST_F(IpProtectionTokenManagerImplTest,
       GetAuthToken_TokenForGeoNotAvailable_ReturnsEmptyOptional) {
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  // Cache contains Mountain view geo tokens.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Requesting token from geo that is not Mountain View.
  std::optional<BlindSignedAuthToken> token =
      ipp_proxy_a_token_manager_->GetAuthToken(kSunnyvaleGeoId);

  ASSERT_FALSE(token);
  ExpectHistogramState(
      HistogramState{.success = 0, .failure = 1, .generated = 1});
  histogram_tester_.ExpectUniqueSample(
      kGetAuthTokenResultForGeoHistogram,
      AuthTokenResultForGeo::kUnavailableButCacheContainsTokens, 1);
}

// `GetAuthToken()` returns nullopt for particular geo where tokens are
// expired.
TEST_F(IpProtectionTokenManagerImplTest,
       GetAuthToken_TokensExpired_ReturnsEmptyOptional) {
  // Expired tokens added.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kPastExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  EXPECT_FALSE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
  ExpectHistogramState(
      HistogramState{.success = 0, .failure = 1, .generated = 1});
}

// `CurrentGeo()` should return empty if no tokens have been requested yet and
// token caching by geo is enabled.
TEST_F(IpProtectionTokenManagerImplTest,
       CurrentGeo_TokensNeverFilled_ReturnsEmpty) {
  // If no tokens have been added, this should not be called.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(0);

  EXPECT_EQ(ipp_proxy_a_token_manager_->CurrentGeo(), "");
}

// `CurrentGeo()` should return the current geo of the most recently returned
// tokens.
TEST_F(IpProtectionTokenManagerImplTest, CurrentGeo_TokensFilled_ReturnsGeo) {
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  EXPECT_EQ(ipp_proxy_a_token_manager_->CurrentGeo(), kMountainViewGeoId);
}

// If `TryGetAuthTokens()` returns a batch smaller than the low-water mark,
// the cache does not immediately refill.
TEST_F(IpProtectionTokenManagerImplTest, SmallBatch) {
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(cache_low_water_mark_ - 1, kFutureExpiration));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  ASSERT_TRUE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  ASSERT_TRUE(
      ipp_proxy_a_token_manager_->try_get_auth_tokens_after_for_testing() >
      base::Time::Now());
  ExpectHistogramState(
      HistogramState{.success = 1, .failure = 0, .generated = 1});
}

// If `TryGetAuthTokens()` returns an backoff due to an error, the cache
// remains empty.
TEST_F(IpProtectionTokenManagerImplTest, ErrorBatch) {
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(0);

  const base::TimeDelta kBackoff = base::Seconds(10);
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, base::Time::Now() + kBackoff);
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  ASSERT_FALSE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));
  ASSERT_FALSE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // Cache was never filled due to error.
  ASSERT_FALSE(ipp_proxy_a_token_manager_->WasTokenCacheEverFilled());

  ExpectHistogramState(
      HistogramState{.success = 0, .failure = 1, .generated = 0});
}

// `GetAuthToken()` skips expired tokens and returns a non-expired token, if
// one is found in the cache.
TEST_F(IpProtectionTokenManagerImplTest, SkipExpiredTokens) {
  std::vector<BlindSignedAuthToken> tokens =
      TokenBatch(10, kPastExpiration, kMountainViewGeo);
  tokens.emplace_back(BlindSignedAuthToken{.token = "good-token",
                                           .expiration = kFutureExpiration,
                                           .geo_hint = kMountainViewGeo});
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(expected_batch_size_,
                                                         std::move(tokens));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
  EXPECT_EQ(got_token.value().token, "good-token");
  EXPECT_EQ(got_token.value().expiration, kFutureExpiration);
  EXPECT_EQ(got_token.value().geo_hint, kMountainViewGeo);
  ExpectHistogramState(
      HistogramState{.success = 1, .failure = 0, .generated = 1});
}

TEST_F(IpProtectionTokenManagerImplTest, TokenExpirationFuzzed) {
  ipp_proxy_a_token_manager_->EnableTokenExpirationFuzzingForTesting(true);

  std::vector<BlindSignedAuthToken> tokens =
      TokenBatch(1, kFutureExpiration, kMountainViewGeo);
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(expected_batch_size_,
                                                         std::move(tokens));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
  EXPECT_EQ(got_token.value().token, "token-0");
  EXPECT_LT(got_token.value().expiration, kFutureExpiration);
  EXPECT_EQ(got_token.value().geo_hint, kMountainViewGeo);
  base::TimeDelta fuzz_limit = net::features::kIpPrivacyExpirationFuzz.Get();
  EXPECT_GE(got_token.value().expiration, kFutureExpiration - fuzz_limit);
}

// If the `IpProtectionConfigGetter` is nullptr, no tokens are gotten, but
// things don't crash.
TEST_F(IpProtectionTokenManagerImplTest, NullGetter) {
  MockIpProtectionCore core;
  auto ipp_token_manager = IpProtectionTokenManagerImpl(
      &core, nullptr, ProxyLayer::kProxyA,
      /* disable_cache_management_for_testing=*/true);

  EXPECT_FALSE(ipp_token_manager.IsAuthTokenAvailable(kMountainViewGeoId));

  // Cache was never filled due to nullptr.
  EXPECT_FALSE(ipp_token_manager.WasTokenCacheEverFilled());

  auto token = ipp_token_manager.GetAuthToken(kMountainViewGeoId);
  ASSERT_FALSE(token);
  ExpectHistogramState(
      HistogramState{.success = 0, .failure = 1, .generated = 0});
}

// Verify that the token spend rate for ProxyA is measured correctly.
TEST_F(IpProtectionTokenManagerImplTest, ProxyATokenSpendRate) {
  std::vector<BlindSignedAuthToken> tokens;

  // Fill the cache with 5 tokens.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(5, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Get four tokens from the batch.
  for (int i = 0; i < 4; i++) {
    std::optional<BlindSignedAuthToken> got_token =
        ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
    EXPECT_EQ(got_token.value().token, base::StringPrintf("token-%d", i));
    EXPECT_EQ(got_token.value().expiration, kFutureExpiration);
  }

  // Fast-forward to run the measurement timer.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // Four tokens in five minutes is a rate of 36 tokens per hour.
  histogram_tester_.ExpectUniqueSample(kProxyATokenSpendRateHistogram, 48, 1);

  // Get the remaining token in the batch.
  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
  EXPECT_EQ(got_token.value().token, "token-4");
  EXPECT_EQ(got_token.value().expiration, kFutureExpiration);

  // Fast-forward to run the measurement timer again, for another interval.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // One token in five minutes is a rate of 12 tokens per hour.
  histogram_tester_.ExpectBucketCount(kProxyATokenSpendRateHistogram, 12, 1);
  histogram_tester_.ExpectTotalCount(kProxyATokenSpendRateHistogram, 2);
}

// Verify that the token expiration rate for ProxyA is measured correctly.
TEST_F(IpProtectionTokenManagerImplTest, ProxyATokenExpirationRate) {
  std::vector<BlindSignedAuthToken> tokens;

  // Fill the cache with 1024 expired tokens. An entire batch expiring
  // in one 5-minute interval is a very likely event.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(1024, kPastExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Try to get a token, which will incidentally record the expired tokens.
  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
  EXPECT_FALSE(got_token);

  // Fast-forward to run the measurement timer.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // 1024 tokens in five minutes is a rate of 12288 tokens per hour.
  histogram_tester_.ExpectUniqueSample(kProxyATokenExpirationRateHistogram,
                                       12288, 1);

  // Fast-forward to run the measurement timer again.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // Zero tokens expired in this interval.
  histogram_tester_.ExpectBucketCount(kProxyATokenExpirationRateHistogram, 0,
                                      1);
  histogram_tester_.ExpectTotalCount(kProxyATokenExpirationRateHistogram, 2);
}

// Verify that the token spend rate for ProxyB is measured correctly.
TEST_F(IpProtectionTokenManagerImplTest, ProxyBTokenSpendRate) {
  std::vector<BlindSignedAuthToken> tokens;

  // Fill the cache with 5 tokens.
  ipp_proxy_b_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(5, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyB);
  ASSERT_TRUE(ipp_proxy_b_token_fetcher_->GotAllExpectedMockCalls());

  // Get four tokens from the batch.
  for (int i = 0; i < 4; i++) {
    std::optional<BlindSignedAuthToken> got_token =
        ipp_proxy_b_token_manager_->GetAuthToken(kMountainViewGeoId);
    EXPECT_EQ(got_token.value().token, base::StringPrintf("token-%d", i));
    EXPECT_EQ(got_token.value().expiration, kFutureExpiration);
  }

  // Fast-forward to run the measurement timer.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // Four tokens in five minutes is a rate of 36 tokens per hour.
  histogram_tester_.ExpectUniqueSample(kProxyBTokenSpendRateHistogram, 48, 1);

  // Get the remaining token in the batch.
  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_b_token_manager_->GetAuthToken(kMountainViewGeoId);
  EXPECT_EQ(got_token.value().token, "token-4");
  EXPECT_EQ(got_token.value().expiration, kFutureExpiration);

  // Fast-forward to run the measurement timer again, for another interval.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // One token in five minutes is a rate of 12 tokens per hour.
  histogram_tester_.ExpectBucketCount(kProxyBTokenSpendRateHistogram, 12, 1);
  histogram_tester_.ExpectTotalCount(kProxyBTokenSpendRateHistogram, 2);
}

// Verify that the token expiration rate for ProxyB is measured correctly.
TEST_F(IpProtectionTokenManagerImplTest, ProxyBTokenExpirationRate) {
  std::vector<BlindSignedAuthToken> tokens;

  // Fill the cache with 1024 expired tokens. An entire batch expiring
  // in one 5-minute interval is a very likely event.
  ipp_proxy_b_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(1024, kPastExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyB);
  ASSERT_TRUE(ipp_proxy_b_token_fetcher_->GotAllExpectedMockCalls());

  // Try to get a token, which will incidentally record the expired tokens.
  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_b_token_manager_->GetAuthToken(kMountainViewGeoId);
  EXPECT_FALSE(got_token);

  // Fast-forward to run the measurement timer.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // 1024 tokens in five minutes is a rate of 12288 tokens per hour.
  histogram_tester_.ExpectUniqueSample(kProxyBTokenExpirationRateHistogram,
                                       12288, 1);

  // Fast-forward to run the measurement timer again.
  task_environment_.FastForwardBy(kTokenRateMeasurementInterval);

  // Zero tokens expired in this interval.
  histogram_tester_.ExpectBucketCount(kProxyBTokenExpirationRateHistogram, 0,
                                      1);
  histogram_tester_.ExpectTotalCount(kProxyBTokenExpirationRateHistogram, 2);
}

// The cache will pre-fill itself with a batch of tokens after a startup delay
TEST_F(IpProtectionTokenManagerImplTest, Prefill) {
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));

  // Histogram should have no samples for a prefill.
  histogram_tester_.ExpectTotalCount(kGeoChangeTokenPresence, 0);
}

// The cache will initiate a refill when it reaches the low-water mark.
TEST_F(IpProtectionTokenManagerImplTest, RefillLowWaterMark) {
  // A refill with tokens from the same geo should not trigger this function a
  // second time.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Spend tokens down to (but not below) the low-water mark.
  for (int i = expected_batch_size_ - 1; i > cache_low_water_mark_; i--) {
    ASSERT_TRUE(
        ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  }

  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));

  // Next call to `GetAuthToken()` should call `MaybeRefillCache()`.
  ipp_proxy_a_token_manager_->SetOnTryGetAuthTokensCompletedForTesting(
      task_environment_.QuitClosure());
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
  task_environment_.RunUntilQuit();

  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
}

// If a fill results in a backoff request, the cache will try again after that
// time.
TEST_F(IpProtectionTokenManagerImplTest, RefillAfterBackoff) {
  base::Time try_again_at = base::Time::Now() + base::Seconds(20);
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(expected_batch_size_,
                                                         try_again_at);
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  base::Time try_again_at_2 = base::Time::Now() + base::Seconds(20);
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(expected_batch_size_,
                                                         try_again_at_2);
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  EXPECT_EQ(base::Time::Now(), try_again_at);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  base::Time try_again_at_3 = base::Time::Now() + base::Seconds(20);
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(expected_batch_size_,
                                                         try_again_at_3);
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  EXPECT_EQ(base::Time::Now(), try_again_at_2);
}

// When enough tokens expire to bring the cache size below the low water mark,
// it will automatically refill.
TEST_F(IpProtectionTokenManagerImplTest, RefillAfterExpiration) {
  // A refill with tokens from the same geo should not trigger this function a
  // second time.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  // Make a batch of tokens almost all with `expiration2`, except one expiring
  // sooner and the one expiring later. These are returned in incorrect order
  // to verify that the cache sorts by expiration time.
  std::vector<BlindSignedAuthToken> tokens;
  base::Time expiration1 = base::Time::Now() + base::Minutes(10);
  base::Time expiration2 = base::Time::Now() + base::Minutes(15);
  base::Time expiration3 = base::Time::Now() + base::Minutes(20);

  for (int i = 0; i < expected_batch_size_ - 2; i++) {
    tokens.emplace_back(BlindSignedAuthToken{.token = "exp2",
                                             .expiration = expiration2,
                                             .geo_hint = kMountainViewGeo});
  }
  tokens.emplace_back(BlindSignedAuthToken{.token = "exp3",
                                           .expiration = expiration3,
                                           .geo_hint = kMountainViewGeo});
  tokens.emplace_back(BlindSignedAuthToken{.token = "exp1",
                                           .expiration = expiration1,
                                           .geo_hint = kMountainViewGeo});

  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(expected_batch_size_,
                                                         std::move(tokens));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // After the first expiration, tokens should still be available and no
  // refill should have begun (which would have caused an error).
  task_environment_.FastForwardBy(expiration1 - base::Time::Now());
  ASSERT_TRUE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));

  // After the second expiration, tokens should still be available, and
  // a second batch should have been requested.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  task_environment_.FastForwardBy(expiration2 - base::Time::Now());
  ASSERT_TRUE(
      ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));

  // The un-expired token should be returned.
  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
  EXPECT_EQ(got_token.value().token, "exp3");

  // Histogram should have no samples because after the initial fill there was
  // no geo change.
  histogram_tester_.ExpectTotalCount(kGeoChangeTokenPresence, 0);
}

// Once a geo changes, the new geo will have a key in the cache map meaning
// tokens are now available to be retrieved for new geo.
TEST_F(IpProtectionTokenManagerImplTest, GeoChangeNewGeoAvailableForGetToken) {
  // We have to re-mock this behavior b/c the default behavior mocks both proxy
  // A and B which would lead to incorrect histogram sampling.
  // A geo change means this is called twice: once for prefill and once for
  // second batch.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_))
      .Times(2)
      .WillRepeatedly([this](const std::string& geo_id) {
        if (ipp_proxy_a_token_manager_->CurrentGeo() != geo_id) {
          ipp_proxy_a_token_manager_->SetCurrentGeo(geo_id);
        }
      });

  // First batch should contain tokens for Mountain View geo.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Spend tokens down to (but not below) the low-water mark.
  for (int i = expected_batch_size_ - 1; i > cache_low_water_mark_; i--) {
    ASSERT_TRUE(
        ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  }

  // New Geo (Sunnyvale) that should be retrieved once the next
  // `GetAuthToken`is called.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kSunnyvaleGeo));

  // Triggers new token retrieval.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // Tokens should contain the new geo.
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // New geo should return a valid token.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kSunnyvaleGeoId));

  // There was a single geo change, but the new geo did not have any preexisting
  // tokens in the cache.
  histogram_tester_.ExpectUniqueSample(kGeoChangeTokenPresence, false, 1);
}

// Once a geo changes, the map will contain multiple geo's. Tokens from a
// prior geo are still valid to use as long as they are not expired.
TEST_F(IpProtectionTokenManagerImplTest, GeoChangeOldGeoTokensStillUsable) {
  // A geo change means this is called twice: once for prefill and once for
  // second batch.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(2);

  // First geo will be Mountain View.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Spend tokens down to (but not below) the low-water mark.
  for (int i = expected_batch_size_ - 1; i > cache_low_water_mark_; i--) {
    ASSERT_TRUE(
        ipp_proxy_a_token_manager_->IsAuthTokenAvailable(kMountainViewGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  }

  // New Geo (Sunnyvale).
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kSunnyvaleGeo));

  // Triggers token refill.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // New tokens should contain new geo.
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Old Geo can still be used if tokens are available.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // Metric should only be counted when the geo requested is not the current
  // geo.
  histogram_tester_.ExpectBucketCount(
      kGetAuthTokenResultForGeoHistogram,
      AuthTokenResultForGeo::kAvailableForOtherCachedGeo, 1);
}

// Existing state with valid non-expired tokens. `SetCurrentGeo` is called
// with geo not in current cache. cache should attempt to refill and will
// contain tokens from the new geo.
TEST_F(IpProtectionTokenManagerImplTest,
       SetCurrentGeoDifferentGeoRetrievesNewTokens) {
  // We have to re-mock this behavior b/c the default behavior mocks both proxy
  // A and B which would lead to incorrect histogram sampling.
  // The geo change to Sunnyvale occurs through a call to `SetCurrentGeo`
  // which means there will not be an additional call to `GeoObserved`
  // aside from the first one during the prefill.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_))
      .Times(1)
      .WillRepeatedly([this](const std::string& geo_id) {
        if (ipp_proxy_a_token_manager_->CurrentGeo() != geo_id) {
          ipp_proxy_a_token_manager_->SetCurrentGeo(geo_id);
        }
      });

  // Original geo will be Mountain View.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Contains Valid Tokens.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // New geo introduced by `SetCurrentGeo` (Sunnyvale).
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kSunnyvaleGeo));

  // Trigger refill.
  ipp_proxy_a_token_manager_->SetCurrentGeo(kSunnyvaleGeoId);

  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // New geo should return a valid token.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kSunnyvaleGeoId));

  // There was a single geo change, but the new geo did not have any preexisting
  // tokens in the cache.
  histogram_tester_.ExpectUniqueSample(kGeoChangeTokenPresence, false, 1);
}

// If setting new geo causes overflow of tokens in cache for certain geo,
// an extended backoff timer should stop more refills until the system can
// stabilize.
TEST_F(IpProtectionTokenManagerImplTest, SetCurrentGeoNewTokensHaveSameGeo) {
  // Expected 2 times:
  // 1. Original geo observed when first batch of tokens are filled ("" ->
  //    Mountain View).
  // 2. `SetCurrentGeo("Sunnyvale")` causes refill and current geo to change.
  //    Refill however returns "Mountain View" which causes an additional
  //    `GeoObserved`.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(2);

  // Mountain View geo that will be maintained from token refill requests.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Cache should have valid tokens now. New Sunnyvale geo will be set to
  // trigger token refill. Next batch of token will still return the Mountain
  // View geo in this test case.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->SetCurrentGeo(kSunnyvaleGeoId);

  // New tokens will still contain the old geo.
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Cache should have valid tokens now. New Sunnyvale geo will be set to
  // trigger token refill. Next batch of token will still return the Mountain
  // View geo in this test case.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->SetCurrentGeo(kSunnyvaleGeoId);

  // Due to the repeated triggers to refill tokens, the token limit exceeded
  // delay would have prevented an additional call to get more tokens. Thus,
  // this should return false.
  ASSERT_FALSE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  ASSERT_TRUE(
      ipp_proxy_a_token_manager_->try_get_auth_tokens_after_for_testing() -
          base::Time::Now() ==
      kTokenLimitExceededDelay);
}

// Testing the existence of tokens in the cache when a new geo matches a
// previous geo that was cached. This test mimics a geo change introduced from
// a token refill from within the class.
TEST_F(IpProtectionTokenManagerImplTest,
       GeoChangeFromWithinTokenManagerNewGeoAlreadyHasTokensPresent) {
  // We have to re-mock this behavior b/c the default behavior mocks both proxy
  // A and B which would lead to incorrect histogram sampling.
  // A geo change means this is called three times: once for prefill and twice
  // for the second and third batch.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_))
      .Times(3)
      .WillRepeatedly([this](const std::string& geo_id) {
        if (ipp_proxy_a_token_manager_->CurrentGeo() != geo_id) {
          ipp_proxy_a_token_manager_->SetCurrentGeo(geo_id);
        }
      });

  // First batch should contain tokens for Mountain View geo.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Spend tokens down to (but not below) the low-water mark.
  for (int i = expected_batch_size_ - 1; i > cache_low_water_mark_; i--) {
    ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  }

  // New Geo (Sunnyvale) that should be retrieved once the next
  // `GetAuthToken`is called.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kSunnyvaleGeo));
  // Triggers new token retrieval.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));
  // Tokens should contain the new geo.
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Spend tokens down to (but not below) the low-water mark.
  for (int i = expected_batch_size_ - 1; i > cache_low_water_mark_; i--) {
    ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kSunnyvaleGeoId));
    ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  }

  // New Geo (Mountain View) that should be retrieved once the next
  // `GetAuthToken`is called.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  // Triggers new token retrieval.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kSunnyvaleGeoId));
  // Tokens should contain the new geo.
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // There was a two geo changes not counting the prefill: Mountain View ->
  // Sunnyvale and Sunnyvale -> Mountain View. When the geo changed to Sunnyvale
  // there were no tokens matching in the cache, but the change back to Mountain
  // View contained previously cached tokens.
  histogram_tester_.ExpectBucketCount(kGeoChangeTokenPresence, true, 1);
  histogram_tester_.ExpectBucketCount(kGeoChangeTokenPresence, false, 1);
}

// Testing the existence of tokens in the cache when a new geo matches a
// previous geo that was cached. This test mimics a geo change introduced from
// outside of this class.
TEST_F(IpProtectionTokenManagerImplTest,
       GeoChangeFromOutsideTokenManagerNewGeoAlreadyHasTokensPresent) {
  // We have to re-mock this behavior b/c the default behavior mocks both proxy
  // A and B which would lead to incorrect histogram sampling.
  // The geo change to Sunnyvale and Mountain View (second time) occurs through
  // a call to `SetCurrentGeo` which means there will not be an additional call
  // to `GeoObserved` aside from the first one during the prefill.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_))
      .Times(1)
      .WillRepeatedly([this](const std::string& geo_id) {
        if (ipp_proxy_a_token_manager_->CurrentGeo() != geo_id) {
          ipp_proxy_a_token_manager_->SetCurrentGeo(geo_id);
        }
      });

  // Original geo will be Mountain View.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));
  ipp_proxy_a_token_manager_->EnableCacheManagementForTesting();
  WaitForTryGetAuthTokensCompletion(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Contains Valid Tokens.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // New geo introduced by `SetCurrentGeo` (Sunnyvale).
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kSunnyvaleGeo));

  // Trigger refill.
  ipp_proxy_a_token_manager_->SetCurrentGeo(kSunnyvaleGeoId);

  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // New geo should return a valid token.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kSunnyvaleGeoId));

  // Another new geo introduced by `SetCurrentGeo` but this time, the geo was
  // previously stored in our cache (Mountain View).
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expected_batch_size_, kFutureExpiration, kMountainViewGeo));

  // Trigger refill.
  ipp_proxy_a_token_manager_->SetCurrentGeo(kMountainViewGeoId);

  // New geo should return a valid token.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // There was a two geo changes not counting the prefill: Mountain View ->
  // Sunnyvale and Sunnyvale -> Mountain View. When the geo changed to Sunnyvale
  // there were no tokens matching in the cache, but the change back to Mountain
  // View contained previously cached tokens.
  histogram_tester_.ExpectBucketCount(kGeoChangeTokenPresence, true, 1);
  histogram_tester_.ExpectBucketCount(kGeoChangeTokenPresence, false, 1);
}

// Verify that requesting tokens logs the correct histogram count.
TEST_F(IpProtectionTokenManagerImplTest, TokenCountRequested) {
  const int batch_size = 5;
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(batch_size, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Verify that 5 tokens were recorded as issued for ProxyA.
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountIssuedHistogram,
                                       batch_size, 1);
  // Verify other histograms were not recorded.
  histogram_tester_.ExpectTotalCount(kProxyATokenCountSpentHistogram, 0);
  histogram_tester_.ExpectTotalCount(kProxyATokenCountExpiredHistogram, 0);
  histogram_tester_.ExpectTotalCount(kProxyBTokenCountIssuedHistogram, 0);
}

// Verify that spending a token logs the correct histogram count.
TEST_F(IpProtectionTokenManagerImplTest, TokenCountSpent) {
  // Fill the cache.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(1, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountIssuedHistogram, 1, 1);

  // Get the token.
  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
  ASSERT_TRUE(got_token);

  // Verify that 1 token was recorded as spent for ProxyA.
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountSpentHistogram, 1, 1);
  // Verify other histograms were not recorded (beyond the initial issue).
  histogram_tester_.ExpectTotalCount(kProxyATokenCountExpiredHistogram, 0);
  histogram_tester_.ExpectTotalCount(kProxyBTokenCountSpentHistogram, 0);
}

// Verify that expired tokens log the correct histogram count.
TEST_F(IpProtectionTokenManagerImplTest, TokenCountExpired) {
  const int expired_count = 3;
  // Fill the cache with expired tokens.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_,
      TokenBatch(expired_count, kPastExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountIssuedHistogram,
                                       expired_count, 1);

  // Attempt to get a token, which triggers RemoveExpiredTokens.
  std::optional<BlindSignedAuthToken> got_token =
      ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId);
  ASSERT_FALSE(got_token);

  // Verify that 3 tokens were recorded as expired (each logged individually).
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountExpiredHistogram,
                                       expired_count,
                                       /*expected_bucket_count=*/1);
  // Verify other histograms were not recorded (beyond the initial issue).
  histogram_tester_.ExpectTotalCount(kProxyATokenCountSpentHistogram, 0);
  histogram_tester_.ExpectTotalCount(kProxyBTokenCountExpiredHistogram, 0);
}

// Verify that events for different proxy layers are recorded separately.
TEST_F(IpProtectionTokenManagerImplTest, TokenCountProxyLayerSeparation) {
  // Issue 5 tokens for Proxy A.
  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(5, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Issue 3 tokens for Proxy B.
  ipp_proxy_b_token_fetcher_->ExpectTryGetAuthTokensCall(
      expected_batch_size_, TokenBatch(3, kFutureExpiration, kMountainViewGeo));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyB);
  ASSERT_TRUE(ipp_proxy_b_token_fetcher_->GotAllExpectedMockCalls());

  // Spend 1 token for Proxy A.
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // Spend 1 token for Proxy B.
  ASSERT_TRUE(ipp_proxy_b_token_manager_->GetAuthToken(kMountainViewGeoId));

  // Verify Proxy A counts.
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountIssuedHistogram, 5, 1);
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountSpentHistogram, 1, 1);
  histogram_tester_.ExpectTotalCount(kProxyATokenCountExpiredHistogram, 0);

  // Verify Proxy B counts.
  histogram_tester_.ExpectUniqueSample(kProxyBTokenCountIssuedHistogram, 3, 1);
  histogram_tester_.ExpectUniqueSample(kProxyBTokenCountSpentHistogram, 1, 1);
  histogram_tester_.ExpectTotalCount(kProxyBTokenCountExpiredHistogram, 0);
}

// Verify multiple event types are recorded correctly within one manager.
TEST_F(IpProtectionTokenManagerImplTest, TokenCountMultipleEvents) {
  // Issue 5 tokens, 2 of which are already expired.
  std::vector<BlindSignedAuthToken> tokens =
      TokenBatch(3, kFutureExpiration, kMountainViewGeo);
  std::vector<BlindSignedAuthToken> expired_tokens =
      TokenBatch(2, kPastExpiration, kMountainViewGeo);
  tokens.insert(tokens.end(), std::make_move_iterator(expired_tokens.begin()),
                std::make_move_iterator(expired_tokens.end()));

  ipp_proxy_a_token_fetcher_->ExpectTryGetAuthTokensCall(expected_batch_size_,
                                                         std::move(tokens));
  CallTryGetAuthTokensAndWait(ProxyLayer::kProxyA);
  ASSERT_TRUE(ipp_proxy_a_token_fetcher_->GotAllExpectedMockCalls());

  // Spend 1 token (this also triggers removal of expired tokens).
  ASSERT_TRUE(ipp_proxy_a_token_manager_->GetAuthToken(kMountainViewGeoId));

  // Verify counts.
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountIssuedHistogram, 5,
                                       1);  // 3 good + 2 expired
  histogram_tester_.ExpectUniqueSample(kProxyATokenCountSpentHistogram, 1, 1);
  histogram_tester_.ExpectUniqueSample(
      kProxyATokenCountExpiredHistogram, /*sample=*/2,
      /*expected_bucket_count=*/1);  // 2 expired tokens removed
}

}  // namespace
}  // namespace ip_protection