File: ip_protection_proxy_config_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 (554 lines) | stat: -rw-r--r-- 22,594 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
// 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_proxy_config_manager_impl.h"

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

#include "base/memory/raw_ptr.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_proxy_config_fetcher.h"
#include "components/ip_protection/common/ip_protection_proxy_config_manager.h"
#include "components/ip_protection/common/ip_protection_telemetry.h"
#include "net/base/features.h"
#include "net/base/network_anonymization_key.h"
#include "net/base/proxy_chain.h"
#include "net/base/proxy_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ip_protection {

namespace {

constexpr char kGetProxyListResultHistogram[] =
    "NetworkService.IpProtection.GetProxyListResult";
constexpr char kProxyListRefreshTimeHistogram[] =
    "NetworkService.IpProtection.ProxyListRefreshTime";

constexpr char kMountainViewGeoId[] = "US,US-CA,MOUNTAIN VIEW";
constexpr char kSunnyvaleGeoId[] = "US,US-CA,SUNNYVALE";

struct GetProxyConfigCall {
  std::optional<std::vector<net::ProxyChain>> proxy_chains;
  std::string geo_id;
};

class MockIpProtectionProxyConfigFetcher
    : public IpProtectionProxyConfigFetcher {
 public:
  ~MockIpProtectionProxyConfigFetcher() override = default;

  // Register an expectation of a call to `GetIpProtectionProxyList()`,
  // returning the given proxy list manager.
  void ExpectGetProxyConfigCall(const GetProxyConfigCall& expected_call) {
    expected_get_proxy_list_calls_.push_back(expected_call);
  }

  // Register an expectation of a call to `GetProxyConfig()`, returning nullopt.
  void ExpectGetProxyConfigCallFailure() {
    GetProxyConfigCall failure_call{.proxy_chains = std::nullopt, .geo_id = ""};
    expected_get_proxy_list_calls_.push_back(failure_call);
  }

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

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

  void GetProxyConfig(GetProxyConfigCallback callback) override {
    ASSERT_FALSE(expected_get_proxy_list_calls_.empty())
        << "Unexpected call to GetProxyConfig";
    auto& expected_call = expected_get_proxy_list_calls_.front();

    std::move(callback).Run(
        expected_call.proxy_chains,
        GetGeoHintFromGeoIdForTesting(expected_call.geo_id));

    expected_get_proxy_list_calls_.pop_front();
  }

 protected:
  std::deque<GetProxyConfigCall> expected_get_proxy_list_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 WereTokenCachesEverFilled() override { return false; }
  std::optional<BlindSignedAuthToken> GetAuthToken(
      size_t chain_index) override {
    return std::nullopt;
  }
  bool IsProbabilisticRevealTokenAvailable() override { NOTREACHED(); }
  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;
  }
};

class IpProtectionProxyConfigManagerImplTest : public testing::Test {
 protected:
  IpProtectionProxyConfigManagerImplTest() {
    // Default behavior for `GeoObserved`. The default is defined here
    // (instead of in the mock) to allow access to the local instances of the
    // proxy list manager.
    ON_CALL(mock_core_, GeoObserved(testing::_))
        .WillByDefault([this](const std::string& geo_id) {
          if (ipp_proxy_list_->CurrentGeo() != geo_id) {
            ipp_proxy_list_->RequestRefreshProxyList();
          }
        });

    auto mock_fetcher = std::make_unique<MockIpProtectionProxyConfigFetcher>();
    mock_fetcher_ = mock_fetcher.get();
    ipp_proxy_list_ = std::make_unique<IpProtectionProxyConfigManagerImpl>(
        &mock_core_, std::move(mock_fetcher),
        /* disable_proxy_refreshing_for_testing=*/true);

    // Disable proxy list fetch interval fuzzing for testing.
    ipp_proxy_list_->EnableProxyListFetchIntervalFuzzingForTesting(
        /*enable=*/false);
  }

  // Wait until the proxy list is refreshed.
  void QuitClosureOnRefresh() {
    // TODO(abhijithnair): Understand what QuitClosure and RunUntilQuit does
    // and refactor these tests.
    ipp_proxy_list_->SetOnProxyListRefreshedForTesting(
        task_environment_.QuitClosure());
  }

  void WaitTillClosureQuit() { task_environment_.RunUntilQuit(); }

  // Shortcut to create a ProxyChain from hostnames.
  net::ProxyChain MakeChain(std::vector<std::string> hostnames) {
    std::vector<net::ProxyServer> servers;
    for (auto& hostname : hostnames) {
      servers.push_back(net::ProxyServer::FromSchemeHostAndPort(
          net::ProxyServer::SCHEME_HTTPS, hostname, std::nullopt));
    }
    return net::ProxyChain::ForIpProtection(servers);
  }

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

  testing::NiceMock<MockIpProtectionCore> mock_core_;

  // The IpProtectionProxyListImpl being tested.
  std::unique_ptr<IpProtectionProxyConfigManagerImpl> ipp_proxy_list_;

  raw_ptr<MockIpProtectionProxyConfigFetcher> mock_fetcher_;

  base::HistogramTester histogram_tester_;
};

// The manager gets the proxy list on startup and once again on schedule.
TEST_F(IpProtectionProxyConfigManagerImplTest, ProxyListOnStartup) {
  // Called twice. Once for startup and once for the proxy list refresh.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(2);

  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->EnableAndTriggerProxyListRefreshingForTesting();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);

  base::Time start = base::Time::Now();

  expected_call =
      GetProxyConfigCall{.proxy_chains = std::vector{MakeChain({"b-proxy"})},
                         .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  WaitTillClosureQuit();
  base::TimeDelta delay = net::features::kIpPrivacyProxyListFetchInterval.Get();
  EXPECT_EQ(base::Time::Now() - start, delay);

  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

// The manager should continue scheduling refreshes even if the most recent
// fails.
TEST_F(IpProtectionProxyConfigManagerImplTest,
       ProxyListRefreshScheduledIfRefreshFails) {
  // Called once for the proxy list refresh after the first refresh fails.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  mock_fetcher_->ExpectGetProxyConfigCallFailure();
  QuitClosureOnRefresh();
  ipp_proxy_list_->EnableAndTriggerProxyListRefreshingForTesting();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());

  // First refresh was failure, but next refresh should occur on schedule.
  EXPECT_FALSE(ipp_proxy_list_->IsProxyListAvailable());

  base::Time start = base::Time::Now();

  GetProxyConfigCall expected_call =
      GetProxyConfigCall{.proxy_chains = std::vector{MakeChain({"b-proxy"})},
                         .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  WaitTillClosureQuit();
  base::TimeDelta delay = net::features::kIpPrivacyProxyListFetchInterval.Get();
  EXPECT_EQ(base::Time::Now() - start, delay);

  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());

  // After a successful call, the proxy list should be available.
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

// If a failure occurs, the minimum time between fetches does not apply.
TEST_F(IpProtectionProxyConfigManagerImplTest,
       ProxyListMinTimeIgnoredWhenRefreshFails) {
  // Called once for the proxy list refresh after the first refresh fails.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  mock_fetcher_->ExpectGetProxyConfigCallFailure();
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());

  // First refresh was failure, but next refresh should occur when requested.
  EXPECT_FALSE(ipp_proxy_list_->IsProxyListAvailable());

  GetProxyConfigCall expected_call =
      GetProxyConfigCall{.proxy_chains = std::vector{MakeChain({"b-proxy"})},
                         .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());

  // After a successful call, the proxy list should be available.
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

// The manager refreshes the proxy list on demand, but only once even if
// `RequestRefreshProxyList()` is called repeatedly.
TEST_F(IpProtectionProxyConfigManagerImplTest, ProxyListRefresh) {
  // Repeated calls should not impact how many times the geo change occurs.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(1);

  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->EnableProxyListRefreshingForTesting();
  ipp_proxy_list_->RequestRefreshProxyList();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

TEST_F(IpProtectionProxyConfigManagerImplTest,
       IsProxyListAvailableEvenIfEmpty) {
  mock_fetcher_->ExpectGetProxyConfigCall(GetProxyConfigCall{
      .proxy_chains = std::vector<net::ProxyChain>{},  // Empty ProxyList
  });
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());

  // Advance the clock by the min refresh interval, so that the test does not
  // hang.
  task_environment_.FastForwardBy(
      net::features::kIpPrivacyProxyListMinFetchInterval.Get());

  // Should show available even if geo is present and list is empty.
  mock_fetcher_->ExpectGetProxyConfigCall(GetProxyConfigCall{
      .proxy_chains = std::vector<net::ProxyChain>{},  // Empty ProxyList
      .geo_id = kMountainViewGeoId});
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
}

// The manager keeps its existing proxy list if it fails to fetch a new one.
TEST_F(IpProtectionProxyConfigManagerImplTest, ProxyListKeptAfterFailure) {
  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);

  // Advance the clock by the min refresh interval, so that the test does not
  // hang.
  task_environment_.FastForwardBy(
      net::features::kIpPrivacyProxyListMinFetchInterval.Get());

  mock_fetcher_->ExpectGetProxyConfigCallFailure();
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);

  // GeoHint is returned but ProxyChain is failure.
  // Advance the clock by the min refresh interval, so that the test does not
  // hang.
  task_environment_.FastForwardBy(
      net::features::kIpPrivacyProxyListMinFetchInterval.Get());

  GetProxyConfigCall expected_call_fail{.proxy_chains = std::nullopt,
                                        .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call_fail);
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

TEST_F(IpProtectionProxyConfigManagerImplTest, GetProxyConfigFailureRecorded) {
  mock_fetcher_->ExpectGetProxyConfigCallFailure();
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  histogram_tester_.ExpectUniqueSample(kGetProxyListResultHistogram,
                                       GetProxyListResult::kFailed, 1);
  histogram_tester_.ExpectTotalCount(kProxyListRefreshTimeHistogram, 0);
}

TEST_F(IpProtectionProxyConfigManagerImplTest, GotEmptyProxyListRecorded) {
  mock_fetcher_->ExpectGetProxyConfigCall(GetProxyConfigCall{
      .proxy_chains = std::vector<net::ProxyChain>{},  // Empty ProxyList
  });
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  histogram_tester_.ExpectUniqueSample(kGetProxyListResultHistogram,
                                       GetProxyListResult::kEmptyList, 1);
  histogram_tester_.ExpectTotalCount(kProxyListRefreshTimeHistogram, 1);
}

TEST_F(IpProtectionProxyConfigManagerImplTest, GotPopulatedProxyListRecorded) {
  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy", "b-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  histogram_tester_.ExpectUniqueSample(kGetProxyListResultHistogram,
                                       GetProxyListResult::kPopulatedList, 1);
  histogram_tester_.ExpectTotalCount(kProxyListRefreshTimeHistogram, 1);
}

TEST_F(IpProtectionProxyConfigManagerImplTest, CurrentGeo) {
  // Current Geo is not set on initialization, so empty geo should be
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), "");

  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy", "b-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

TEST_F(IpProtectionProxyConfigManagerImplTest, RequestRefreshProxyList) {
  // Current Geo is not set on initialization, so empty geo should be
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), "");

  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy", "b-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);

  // Simulate `IpProtectionCore.GeoObserved` being called from
  // outside this class which results in `RequestRefreshProxyList` being
  // called. Expected call will contain a different geo.
  expected_call = GetProxyConfigCall{
      .proxy_chains = std::vector{MakeChain({"a-proxy", "b-proxy"})},
      .geo_id = kSunnyvaleGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);

  // Advance the clock by the min refresh interval, so that the test does not
  // hang.
  task_environment_.FastForwardBy(
      net::features::kIpPrivacyProxyListMinFetchInterval.Get());

  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();

  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  // Refresh will contain new geo which will set the current geo.
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), kSunnyvaleGeoId);
}

// If `RequestRefreshProxyList` is called multiple times, the refresh is
// only requested once within the default interval.
TEST_F(IpProtectionProxyConfigManagerImplTest,
       RequestRefreshProxyList_MultipleCalls_RefreshOnlyOnce) {
  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy", "b-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();

  ipp_proxy_list_->RequestRefreshProxyList();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();

  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

// If a proxy list refresh returns the same geo as the current geo, no callbacks
// to `GeoObserved` are made.
TEST_F(IpProtectionProxyConfigManagerImplTest,
       RequestRefreshProxyList_SameGeo_NoGeoObserved) {
  // Each refresh will result in a new call.
  EXPECT_CALL(mock_core_, GeoObserved(testing::_)).Times(2);

  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy", "b-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);

  // An additional refresh is needed. This refresh contains the same geo, so
  // there should not be a call to `IpProtectionCore.GeoObserved`.
  expected_call = GetProxyConfigCall{
      .proxy_chains = std::vector{MakeChain({"a-proxy", "b-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);

  // Advance the clock by the min refresh interval, so that the test does not
  // hang.
  task_environment_.FastForwardBy(
      net::features::kIpPrivacyProxyListMinFetchInterval.Get());

  QuitClosureOnRefresh();
  ipp_proxy_list_->RequestRefreshProxyList();
  WaitTillClosureQuit();

  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  ASSERT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);
}

TEST_F(IpProtectionProxyConfigManagerImplTest,
       ProxyListRefreshFetchIntervalFuzzed) {
  GetProxyConfigCall expected_call{
      .proxy_chains = std::vector{MakeChain({"a-proxy"})},
      .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  ipp_proxy_list_->EnableProxyListFetchIntervalFuzzingForTesting(
      /*enable=*/true);
  ipp_proxy_list_->EnableAndTriggerProxyListRefreshingForTesting();
  WaitTillClosureQuit();
  ASSERT_TRUE(mock_fetcher_->GotAllExpectedMockCalls());
  EXPECT_TRUE(ipp_proxy_list_->IsProxyListAvailable());
  EXPECT_EQ(ipp_proxy_list_->ProxyList(), expected_call.proxy_chains);
  EXPECT_EQ(ipp_proxy_list_->CurrentGeo(), kMountainViewGeoId);

  base::Time start = base::Time::Now();
  expected_call =
      GetProxyConfigCall{.proxy_chains = std::vector{MakeChain({"b-proxy"})},
                         .geo_id = kMountainViewGeoId};
  mock_fetcher_->ExpectGetProxyConfigCall(expected_call);
  QuitClosureOnRefresh();
  WaitTillClosureQuit();

  base::TimeDelta delay = net::features::kIpPrivacyProxyListFetchInterval.Get();
  base::TimeDelta fuzz_range =
      net::features::kIpPrivacyProxyListFetchIntervalFuzz.Get();
  // Add 10s buffer to account for possible delays before the check
  EXPECT_LE(base::Time::Now() - start, delay + fuzz_range + base::Seconds(10));
  EXPECT_GE(base::Time::Now() - start, delay - fuzz_range - base::Seconds(10));
}

}  // namespace
}  // namespace ip_protection