File: ip_protection_proxy_config_direct_fetcher_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 (483 lines) | stat: -rw-r--r-- 19,316 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
// Copyright 2024 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_direct_fetcher.h"

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

#include "base/functional/callback.h"
#include "base/memory/scoped_refptr.h"
#include "base/notreached.h"
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "base/time/time.h"
#include "base/types/expected.h"
#include "components/ip_protection/common/ip_protection_data_types.h"
#include "components/ip_protection/get_proxy_config.pb.h"
#include "net/base/features.h"
#include "net/base/net_errors.h"
#include "net/base/proxy_chain.h"
#include "net/base/proxy_server.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/test/test_shared_url_loader_factory.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 ip_protection {

namespace {

constexpr char kServiceType[] = "test_service_type";

const GeoHint kGeoHint = {.country_code = "US",
                          .iso_region = "US-AL",
                          .city_name = "ALABASTER"};
class MockIpProtectionProxyConfigRetriever
    : public IpProtectionProxyConfigDirectFetcher::Retriever {
 public:
  using MockGetProxyConfig = base::RepeatingCallback<
      base::expected<GetProxyConfigResponse, std::string>()>;
  // Construct a mock retriever that will call the given closure for each call
  // to GetProxyConfig.
  explicit MockIpProtectionProxyConfigRetriever(
      MockGetProxyConfig get_proxy_config)
      : IpProtectionProxyConfigDirectFetcher::Retriever(
            base::MakeRefCounted<network::TestSharedURLLoaderFactory>(),
            kServiceType,
            nullptr),
        get_proxy_config_(get_proxy_config) {}

  // Construct a mock retriever that always returns the same response.
  explicit MockIpProtectionProxyConfigRetriever(
      std::optional<GetProxyConfigResponse> proxy_config_response)
      : MockIpProtectionProxyConfigRetriever(base::BindLambdaForTesting(
            [proxy_config_response = std::move(proxy_config_response)]()
                -> base::expected<GetProxyConfigResponse, std::string> {
              if (!proxy_config_response.has_value()) {
                return base::unexpected("uhoh");
              }
              return base::ok(*proxy_config_response);
            })) {}

  void RetrieveProxyConfig(
      IpProtectionProxyConfigDirectFetcher::Retriever::RetrieveCallback
          callback) override {
    std::move(callback).Run(get_proxy_config_.Run());
  }

 private:
  MockGetProxyConfig get_proxy_config_;
};

}  // namespace

class IpProtectionProxyConfigDirectFetcherRetrieverTest
    : public testing::Test,
      public IpProtectionProxyConfigDirectFetcher::Delegate {
 protected:
  void SetUp() override {
    retriever_ =
        std::make_unique<IpProtectionProxyConfigDirectFetcher::Retriever>(
            test_url_loader_factory_.GetSafeWeakWrapper(), "test_service_type",
            this);
    token_server_get_proxy_config_url_ = GURL(base::StrCat(
        {net::features::kIpPrivacyTokenServer.Get(),
         net::features::kIpPrivacyTokenServerGetProxyConfigPath.Get()}));
    ASSERT_TRUE(token_server_get_proxy_config_url_.is_valid());
  }

  // IpProtectionProxyConfigDirectFetcher::Delegate implementation.
  bool IsProxyConfigFetchEnabled() override { return true; }
  void AuthenticateRequest(
      std::unique_ptr<network::ResourceRequest> resource_request,
      IpProtectionProxyConfigDirectFetcher::Delegate::
          AuthenticateRequestCallback callback) override {
    resource_request->headers.SetHeader("AuthenticationHeader", "Added");
    std::move(callback).Run(authenticate_callback_result_,
                            std::move(resource_request));
  }

  base::test::TaskEnvironment task_environment_;
  network::TestURLLoaderFactory test_url_loader_factory_;
  std::unique_ptr<IpProtectionProxyConfigDirectFetcher::Retriever> retriever_;
  GURL token_server_get_proxy_config_url_;
  bool authenticate_callback_result_ = true;
};

TEST_F(IpProtectionProxyConfigDirectFetcherRetrieverTest,
       GetProxyConfigSuccess) {
  std::map<std::string, std::string> parameters;
  parameters["IpPrivacyDebugExperimentArm"] = "42";
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      net::features::kEnableIpProtectionProxy, std::move(parameters));
  GetProxyConfigResponse response_proto;

  GetProxyConfigResponse_ProxyChain* proxyChain =
      response_proto.add_proxy_chain();
  proxyChain->set_proxy_a("proxyA");
  proxyChain->set_proxy_b("proxyB");
  std::string response_str = response_proto.SerializeAsString();

  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        ASSERT_TRUE(request.url.is_valid());
        ASSERT_EQ(request.url, token_server_get_proxy_config_url_);

        EXPECT_THAT(request.headers.GetHeader("AuthenticationHeader"),
                    testing::Optional(std::string("Added")));
        EXPECT_THAT(
            request.headers.GetHeader("Ip-Protection-Debug-Experiment-Arm"),
            testing::Optional(std::string("42")));

        auto head = network::mojom::URLResponseHead::New();
        test_url_loader_factory_.AddResponse(
            token_server_get_proxy_config_url_, std::move(head), response_str,
            network::URLLoaderCompletionStatus(net::OK));
      }));

  base::test::TestFuture<base::expected<GetProxyConfigResponse, std::string>>
      result_future;
  retriever_->RetrieveProxyConfig(result_future.GetCallback());

  base::expected<GetProxyConfigResponse, std::string> result =
      result_future.Get();

  ASSERT_TRUE(result.has_value());
  EXPECT_EQ("proxyA", result->proxy_chain().at(0).proxy_a());
  EXPECT_EQ("proxyB", result->proxy_chain().at(0).proxy_b());
}

TEST_F(IpProtectionProxyConfigDirectFetcherRetrieverTest,
       GetProxyConfigAuthCallbackFails) {
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeature(
      net::features::kEnableIpProtectionProxy);

  authenticate_callback_result_ = false;
  test_url_loader_factory_.SetInterceptor(base::BindLambdaForTesting(
      [&](const network::ResourceRequest& request) { FAIL(); }));

  base::test::TestFuture<base::expected<GetProxyConfigResponse, std::string>>
      result_future;
  retriever_->RetrieveProxyConfig(result_future.GetCallback());

  base::expected<GetProxyConfigResponse, std::string> result =
      result_future.Get();

  ASSERT_FALSE(result.has_value());
}

TEST_F(IpProtectionProxyConfigDirectFetcherRetrieverTest, GetProxyConfigEmpty) {
  GetProxyConfigResponse response_proto;
  std::string response_str = response_proto.SerializeAsString();

  auto head = network::mojom::URLResponseHead::New();
  test_url_loader_factory_.AddResponse(
      token_server_get_proxy_config_url_, std::move(head), response_str,
      network::URLLoaderCompletionStatus(net::OK));

  base::test::TestFuture<base::expected<GetProxyConfigResponse, std::string>>
      result_future;
  retriever_->RetrieveProxyConfig(result_future.GetCallback());

  base::expected<GetProxyConfigResponse, std::string> result =
      result_future.Get();

  ASSERT_TRUE(result.has_value());
  EXPECT_EQ(0, result->proxy_chain_size());
}

TEST_F(IpProtectionProxyConfigDirectFetcherRetrieverTest, GetProxyConfigFails) {
  auto head = network::mojom::URLResponseHead::New();

  test_url_loader_factory_.AddResponse(
      token_server_get_proxy_config_url_, std::move(head), "uhoh",
      network::URLLoaderCompletionStatus(net::HTTP_BAD_REQUEST));

  base::test::TestFuture<base::expected<GetProxyConfigResponse, std::string>>
      result_future;
  retriever_->RetrieveProxyConfig(result_future.GetCallback());

  base::expected<GetProxyConfigResponse, std::string> result =
      result_future.Get();

  ASSERT_FALSE(result.has_value());
}

class IpProtectionProxyConfigDirectFetcherTest
    : public testing::Test,
      public IpProtectionProxyConfigDirectFetcher::Delegate {
  // IpProtectionProxyConfigDirectFetcher::Delegate implementation.
  bool IsProxyConfigFetchEnabled() override { return true; }
  void AuthenticateRequest(
      std::unique_ptr<network::ResourceRequest> resource_request,
      IpProtectionProxyConfigDirectFetcher::Delegate::
          AuthenticateRequestCallback callback) override {
    NOTREACHED();
  }

 protected:
  base::test::TaskEnvironment task_environment_;
  base::test::TestFuture<const std::optional<std::vector<net::ProxyChain>>,
                         const std::optional<GeoHint>>
      proxy_list_future_;
};

TEST_F(IpProtectionProxyConfigDirectFetcherTest, GetProxyConfigProxyChains) {
  GetProxyConfigResponse response;
  auto* chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy1");
  chain->set_proxy_b("proxy1b");
  chain->set_chain_id(1);
  chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy2");
  chain->set_proxy_b("proxy2b");
  chain->set_chain_id(2);

  response.mutable_geo_hint()->set_country_code(kGeoHint.country_code);
  response.mutable_geo_hint()->set_iso_region(kGeoHint.iso_region);
  response.mutable_geo_hint()->set_city_name(kGeoHint.city_name);

  IpProtectionProxyConfigDirectFetcher fetcher(
      std::make_unique<MockIpProtectionProxyConfigRetriever>(response), this);
  base::Time initial_no_get_proxy_config_until_ =
      fetcher.GetNoGetProxyConfigUntilTimeForTesting();

  fetcher.GetProxyConfig(proxy_list_future_.GetCallback());
  ASSERT_TRUE(proxy_list_future_.Wait()) << "GetProxyConfig did not call back";
  // This is a successful response. Backoff should be reset.
  EXPECT_EQ(fetcher.GetNoGetProxyConfigUntilTimeForTesting(),
            initial_no_get_proxy_config_until_);
  EXPECT_EQ(
      fetcher.GetNextGetProxyConfigBackoffForTesting(),
      IpProtectionProxyConfigDirectFetcher::kGetProxyConfigFailureTimeout);

  std::vector<net::ProxyChain> exp_proxy_list = {
      IpProtectionProxyConfigDirectFetcher::MakeChainForTesting(
          {"proxy1", "proxy1b"}, 1),
      IpProtectionProxyConfigDirectFetcher::MakeChainForTesting(
          {"proxy2", "proxy2b"}, 2)};

  // Extract tuple elements for individual comparison.
  const auto& [proxy_list, geo_hint] = proxy_list_future_.Get();

  ASSERT_TRUE(proxy_list.has_value());  // Check if optional has value.
  EXPECT_THAT(proxy_list.value(), testing::ElementsAreArray(exp_proxy_list));

  ASSERT_TRUE(geo_hint);  // Check that GeoHintPtr is not null.
  EXPECT_TRUE(geo_hint == kGeoHint);
}

TEST_F(IpProtectionProxyConfigDirectFetcherTest,
       GetProxyConfigProxyChainsWithPorts) {
  GetProxyConfigResponse response;
  auto* chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy1");
  chain->set_proxy_b("proxy1b");
  chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy2:80");
  chain->set_proxy_b("proxy2");
  chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy3:0");
  chain->set_proxy_b("proxy4:443");
  chain->set_chain_id(3);

  response.mutable_geo_hint()->set_country_code(kGeoHint.country_code);
  response.mutable_geo_hint()->set_iso_region(kGeoHint.iso_region);
  response.mutable_geo_hint()->set_city_name(kGeoHint.city_name);

  IpProtectionProxyConfigDirectFetcher fetcher(
      std::make_unique<MockIpProtectionProxyConfigRetriever>(response), this);

  fetcher.GetProxyConfig(proxy_list_future_.GetCallback());
  ASSERT_TRUE(proxy_list_future_.Wait()) << "GetProxyConfig did not call back";

  std::vector<net::ProxyChain> exp_proxy_list = {
      IpProtectionProxyConfigDirectFetcher::MakeChainForTesting(
          {"proxy1", "proxy1b"})};
  exp_proxy_list.push_back(net::ProxyChain::ForIpProtection(
      {net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_HTTPS,
                                               "proxy2", 80),
       net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_HTTPS,
                                               "proxy2", std::nullopt)}));
  exp_proxy_list.push_back(net::ProxyChain::ForIpProtection(
      {net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_HTTPS,
                                               "proxy3", "0"),
       net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_HTTPS,
                                               "proxy4", "443")},
      3));

  // Extract tuple elements for individual comparison.
  const auto& [proxy_list, geo_hint] = proxy_list_future_.Get();

  ASSERT_TRUE(proxy_list.has_value());  // Check if optional has value.
  EXPECT_THAT(proxy_list.value(), testing::ElementsAreArray(exp_proxy_list));

  ASSERT_TRUE(geo_hint);  // Check that GeoHint is not null.
  EXPECT_TRUE(geo_hint == kGeoHint);
}

TEST_F(IpProtectionProxyConfigDirectFetcherTest, GetProxyConfigProxyInvalid) {
  GetProxyConfigResponse response;
  auto* chain = response.add_proxy_chain();
  chain->set_proxy_a("]INVALID[");
  chain->set_proxy_b("not-invalid");
  chain = response.add_proxy_chain();
  chain->set_proxy_a("valid");
  chain->set_proxy_b("valid");

  response.mutable_geo_hint()->set_country_code(kGeoHint.country_code);
  response.mutable_geo_hint()->set_iso_region(kGeoHint.iso_region);
  response.mutable_geo_hint()->set_city_name(kGeoHint.city_name);

  IpProtectionProxyConfigDirectFetcher fetcher(
      std::make_unique<MockIpProtectionProxyConfigRetriever>(response), this);

  fetcher.GetProxyConfig(proxy_list_future_.GetCallback());
  ASSERT_TRUE(proxy_list_future_.Wait()) << "GetProxyConfig did not call back";

  std::vector<net::ProxyChain> exp_proxy_list = {
      IpProtectionProxyConfigDirectFetcher::MakeChainForTesting(
          {"valid", "valid"})};

  // Extract tuple elements for individual comparison.
  const auto& [proxy_list, geo_hint] = proxy_list_future_.Get();

  ASSERT_TRUE(proxy_list.has_value());  // Check if optional has value.
  EXPECT_THAT(proxy_list.value(), testing::ElementsAreArray(exp_proxy_list));

  ASSERT_TRUE(geo_hint);  // Check that GeoHint is not null.
  EXPECT_TRUE(geo_hint == kGeoHint);
}

TEST_F(IpProtectionProxyConfigDirectFetcherTest,
       GetProxyConfigProxyInvalidChainId) {
  GetProxyConfigResponse response;
  auto* chain = response.add_proxy_chain();
  chain->set_proxy_a("proxya");
  chain->set_proxy_b("proxyb");
  chain->set_chain_id(999);

  response.mutable_geo_hint()->set_country_code(kGeoHint.country_code);
  response.mutable_geo_hint()->set_iso_region(kGeoHint.iso_region);
  response.mutable_geo_hint()->set_city_name(kGeoHint.city_name);

  IpProtectionProxyConfigDirectFetcher fetcher(
      std::make_unique<MockIpProtectionProxyConfigRetriever>(response), this);

  fetcher.GetProxyConfig(proxy_list_future_.GetCallback());
  ASSERT_TRUE(proxy_list_future_.Wait()) << "GetProxyConfig did not call back";

  // The proxy chain is still used, but the chain ID is set to the default.
  std::vector<net::ProxyChain> exp_proxy_list = {
      IpProtectionProxyConfigDirectFetcher::MakeChainForTesting(
          {"proxya", "proxyb"}, net::ProxyChain::kDefaultIpProtectionChainId)};

  // Extract tuple elements for individual comparison.
  const auto& [proxy_list, geo_hint] = proxy_list_future_.Get();

  ASSERT_TRUE(proxy_list.has_value());  // Check if optional has value.
  EXPECT_THAT(proxy_list.value(), testing::ElementsAreArray(exp_proxy_list));

  ASSERT_TRUE(geo_hint);  // Check that GeoHint is not null.
  EXPECT_TRUE(geo_hint == kGeoHint);
}

TEST_F(IpProtectionProxyConfigDirectFetcherTest,
       GetProxyConfigProxyCountryLevelGeo) {
  GetProxyConfigResponse response;
  auto* chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy1");
  chain->set_proxy_b("proxy1b");
  chain->set_chain_id(1);
  chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy2");
  chain->set_proxy_b("proxy2b");
  chain->set_chain_id(2);

  // Geo is only country level.
  response.mutable_geo_hint()->set_country_code("US");

  IpProtectionProxyConfigDirectFetcher fetcher(
      std::make_unique<MockIpProtectionProxyConfigRetriever>(response), this);

  fetcher.GetProxyConfig(proxy_list_future_.GetCallback());
  ASSERT_TRUE(proxy_list_future_.Wait()) << "GetProxyConfig did not call back";

  std::vector<net::ProxyChain> exp_proxy_list = {
      IpProtectionProxyConfigDirectFetcher::MakeChainForTesting(
          {"proxy1", "proxy1b"}, 1),
      IpProtectionProxyConfigDirectFetcher::MakeChainForTesting(
          {"proxy2", "proxy2b"}, 2)};

  // Country level geo only.
  GeoHint exp_geo_hint;
  exp_geo_hint.country_code = "US";

  // Extract tuple elements for individual comparison.
  const auto& [proxy_list, geo_hint] = proxy_list_future_.Get();

  ASSERT_TRUE(proxy_list.has_value());  // Check if optional has value.
  EXPECT_THAT(proxy_list.value(), testing::ElementsAreArray(exp_proxy_list));

  ASSERT_TRUE(geo_hint);  // Check that GeoHint is not null.
  EXPECT_TRUE(geo_hint == exp_geo_hint);
}

TEST_F(IpProtectionProxyConfigDirectFetcherTest,
       GetProxyConfigProxyGeoMissingFailure) {
  // The error case in this situation should be a valid response with a missing
  // geo hint and non-empty proxy chain vector.
  GetProxyConfigResponse response;
  auto* chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy1");
  chain->set_proxy_b("proxy1b");
  chain->set_chain_id(1);
  chain = response.add_proxy_chain();
  chain->set_proxy_a("proxy2");
  chain->set_proxy_b("proxy2b");
  chain->set_chain_id(2);

  IpProtectionProxyConfigDirectFetcher fetcher(
      std::make_unique<MockIpProtectionProxyConfigRetriever>(response), this);
  // No backoff set yet.
  EXPECT_LT(fetcher.GetNoGetProxyConfigUntilTimeForTesting(),
            base::Time::Now());

  fetcher.GetProxyConfig(proxy_list_future_.GetCallback());
  ASSERT_TRUE(proxy_list_future_.Wait()) << "GetProxyConfig did not call back";

  // This is a response error, hence a future time should be set.
  // It is impossible to get `Time::Now()` in the runtime. But since
  // test duration is much less than kGetProxyConfigFailureTimeout
  // (1min), safe to compare with the `Time::Now()` from the test harness.
  EXPECT_GT(fetcher.GetNoGetProxyConfigUntilTimeForTesting(),
            base::Time::Now());
  EXPECT_EQ(
      fetcher.GetNextGetProxyConfigBackoffForTesting(),
      IpProtectionProxyConfigDirectFetcher::kGetProxyConfigFailureTimeout * 2);

  // Extract tuple elements for individual comparison.
  const auto& [proxy_list, geo_hint] = proxy_list_future_.Get();

  // A failure means both of these values will be null.
  EXPECT_EQ(proxy_list, std::nullopt);
  EXPECT_FALSE(geo_hint.has_value());
}

}  // namespace ip_protection