File: proto_fetcher_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 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 (935 lines) | stat: -rw-r--r-- 37,715 bytes parent folder | download | duplicates (3)
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
// Copyright 2022 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/supervised_user/core/browser/proto_fetcher.h"

#include <memory>
#include <optional>
#include <string>
#include <string_view>

#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/strings/strcat.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "base/types/expected.h"
#include "base/version_info/channel.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
#include "components/supervised_user/core/browser/fetcher_config.h"
#include "components/supervised_user/core/browser/kids_management_api_fetcher.h"
#include "components/supervised_user/core/common/features.h"
#include "components/supervised_user/test_support/kids_management_api_server_mock.h"
#include "google_apis/common/api_key_request_test_util.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/base/backoff_entry.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/data_element.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace supervised_user {

bool operator==(const ProtoFetcherStatus& a, const ProtoFetcherStatus& b) {
  return a.state() == b.state();
}

namespace {

static const char* kMockEndpointDomain = "example.com";
static const char* kExampleURL = "https://example.com/";

using ::base::BindOnce;
using ::base::Time;
using ::kidsmanagement::ClassifyUrlRequest;
using ::kidsmanagement::ClassifyUrlResponse;
using ::kidsmanagement::CreatePermissionRequestResponse;
using ::kidsmanagement::FamilyRole;
using ::kidsmanagement::PermissionRequest;
using ::network::GetUploadData;
using ::network::TestURLLoaderFactory;
using ::signin::ConsentLevel;
using ::signin::IdentityTestEnvironment;

constexpr FetcherConfig kTestGetConfig{
    .service_path = "/superviser/user:get",
    .method = FetcherConfig::Method::kGet,
    .histogram_basename = "SupervisedUser.Request",
    .traffic_annotation =
        annotations::ClassifyUrlTag,  // traffic annotation is meaningless for
                                      // this tests since there's no real
                                      // traffic.
    .access_token_config =
        AccessTokenConfig{
            .credentials_requirement =
                AccessTokenConfig::CredentialsRequirement::kStrict,
            .mode = signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate,
            // TODO(b/284523446): Refer to GaiaConstants rather than literal.
            .oauth2_scope =
                "https://www.googleapis.com/auth/kid.permission",  // Real scope
                                                                   // required.

        },
};

constexpr FetcherConfig kTestGetConfigWithoutMetrics{
    .service_path = "/superviser/user:get",
    .method = FetcherConfig::Method::kGet,
    .traffic_annotation =
        annotations::ClassifyUrlTag,  // traffic annotation is meaningless for
                                      // this tests since there's no real
                                      // traffic.
    .access_token_config =
        AccessTokenConfig{
            .credentials_requirement =
                AccessTokenConfig::CredentialsRequirement::kStrict,
            .mode = signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate,
            // TODO(b/284523446): Refer to GaiaConstants rather than literal.
            .oauth2_scope =
                "https://www.googleapis.com/auth/kid.permission",  // Real scope
                                                                   // required.

        },
};

constexpr FetcherConfig kTestPostConfig{
    .service_path = "/superviser/user:post",
    .method = FetcherConfig::Method::kPost,
    .histogram_basename = "SupervisedUser.Request",
    .traffic_annotation =
        annotations::ClassifyUrlTag,  // traffic annotation is meaningless for
                                      // this tests since there's no real
                                      // traffic.
    .access_token_config =
        AccessTokenConfig{
            .credentials_requirement =
                AccessTokenConfig::CredentialsRequirement::kStrict,
            .mode = signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate,
            // TODO(b/284523446): Refer to GaiaConstants rather than literal.
            .oauth2_scope =
                "https://www.googleapis.com/auth/kid.permission",  // Real scope
                                                                   // required.

        },
};

constexpr FetcherConfig kTestRetryConfig{
    .service_path = "/superviser/user:retry",
    .method = FetcherConfig::Method::kGet,
    .histogram_basename = "SupervisedUser.Request",
    .traffic_annotation =
        annotations::ClassifyUrlTag,  // traffic annotation is meaningless for
                                      // this tests since there's no real
                                      // traffic.
    .backoff_policy =
        net::BackoffEntry::Policy{
            .initial_delay_ms = 1,
            .multiply_factor = 1,
            .maximum_backoff_ms = 1,
            .always_use_initial_delay = false,
        },
    .access_token_config =
        AccessTokenConfig{
            .credentials_requirement =
                AccessTokenConfig::CredentialsRequirement::kStrict,
            .mode = signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate,
            // TODO(b/284523446): Refer to GaiaConstants rather than literal.
            .oauth2_scope =
                "https://www.googleapis.com/auth/kid.permission",  // Real scope
                                                                   // required.

        },
};

constexpr FetcherConfig kTestGetConfigBestEffortAccessToken{
    .service_path = "/superviser/user:get",
    .method = FetcherConfig::Method::kGet,
    .histogram_basename = "SupervisedUser.Request",
    .traffic_annotation =
        annotations::ClassifyUrlTag,  // traffic annotation is meaningless for
                                      // this tests since there's no real
                                      // traffic.
    .access_token_config =
        AccessTokenConfig{
            .credentials_requirement =
                AccessTokenConfig::CredentialsRequirement::kBestEffort,
            .mode = signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate,
            // TODO(b/284523446): Refer to GaiaConstants rather than literal.
            .oauth2_scope =
                "https://www.googleapis.com/auth/kid.permission",  // Real scope
                                                                   // required.

        },
};

constexpr FetcherConfig kTestGetConfigWithoutCredentials{
    .service_path = "/superviser/user:get",
    .method = FetcherConfig::Method::kGet,
    .histogram_basename = "SupervisedUser.Request",
    .traffic_annotation =
        annotations::ClassifyUrlTag,  // traffic annotation is meaningless for
                                      // this tests since there's no real
                                      // traffic.
};

// Receiver is an artificial consumer of the fetch process. Typically, calling
// an RPC has the purpose of writing the data somewhere. Instances of this class
// serve as a general-purpose destination for fetched data.
class Receiver {
 public:
  const base::expected<std::unique_ptr<ClassifyUrlResponse>,
                       ProtoFetcherStatus>&
  GetResult() const {
    return *result_;
  }
  bool HasResultOrError() const { return result_.has_value(); }

  void Receive(const ProtoFetcherStatus& fetch_status,
               std::unique_ptr<ClassifyUrlResponse> response) {
    if (!fetch_status.IsOk()) {
      result_ = base::unexpected(fetch_status);
      return;
    }
    result_ = std::move(response);
  }

 private:
  std::optional<
      base::expected<std::unique_ptr<ClassifyUrlResponse>, ProtoFetcherStatus>>
      result_;
};

// Base of the test fixture for proto fetcher.
// Defines required runtime environment, and a collection of helper methods
// which are used to build initial test state and define behaviors.
//
// Simulate* methods are short-hands to put response with specific property in
// test url environment's queue;
//
// FastForward is important for retrying feature tests: make sure that the time
// skipped is greater than possible retry timeouts.
class ProtoFetcherTestBase {
 public:
  ProtoFetcherTestBase() = delete;
  explicit ProtoFetcherTestBase(const FetcherConfig& config) : config_(config) {
    SetHttpEndpointsForKidsManagementApis(feature_list_, kMockEndpointDomain);
  }

 protected:
  using Fetcher = ProtoFetcher<ClassifyUrlResponse>;

  const FetcherConfig& GetConfig() const { return config_; }

  // Receivers are not-copyable because of mocked method.
  std::unique_ptr<Receiver> MakeReceiver() const {
    return std::make_unique<Receiver>();
  }
  std::unique_ptr<Fetcher> MakeFetcher(Receiver& receiver) {
    ClassifyUrlRequest request;
    if (GetConfig().method == FetcherConfig::Method::kPost) {
      request.set_url(kExampleURL);
    }
    return CreateClassifyURLFetcher(
        *identity_test_env_.identity_manager(),
        test_url_loader_factory_.GetSafeWeakWrapper(), request,
        BindOnce(&Receiver::Receive, base::Unretained(&receiver)), GetConfig());
  }

  // Url loader helpers
  const GURL& GetUrlOfPendingRequest(size_t index) {
    return test_url_loader_factory_.GetPendingRequest(index)->request.url;
  }

  void SimulateDefaultResponseForPendingRequest(size_t index) {
    test_url_loader_factory_.SimulateResponseForPendingRequest(
        GetUrlOfPendingRequest(index).spec(),
        ClassifyUrlResponse().SerializeAsString());
  }
  void SimulateResponseForPendingRequest(size_t index,
                                         std::string_view content) {
    test_url_loader_factory_.SimulateResponseForPendingRequest(
        GetUrlOfPendingRequest(index).spec(), std::string(content));
  }
  void SimulateResponseForPendingRequestWithTransientError(size_t index) {
    net::HttpStatusCode error = net::HTTP_BAD_REQUEST;
    ASSERT_TRUE(
        ProtoFetcherStatus::HttpStatusOrNetError(error).IsTransientError());

    test_url_loader_factory_.SimulateResponseForPendingRequest(
        GetUrlOfPendingRequest(index).spec(), /*content=*/"", error);
  }
  void SimulateMalformedResponseForPendingRequest(size_t index) {
    test_url_loader_factory_.SimulateResponseForPendingRequest(
        GetUrlOfPendingRequest(index).spec(), "malformed-response");
  }
  void SimulateResponseForPendingRequestWithHttpAuthError(size_t index) {
    net::HttpStatusCode error = net::HTTP_UNAUTHORIZED;
    ASSERT_FALSE(
        ProtoFetcherStatus::HttpStatusOrNetError(error).IsTransientError());

    test_url_loader_factory_.SimulateResponseForPendingRequest(
        GetUrlOfPendingRequest(index).spec(), /*content=*/"", error);
  }

  // Some tests check backoff strategies which introduce delays, this method is
  // forwarding the time so that all operations scheduled in the future are
  // completed. See FetcherConfig::backoff_policy for details.
  void FastForward() {
    // Fast forward enough to schedule all retries, which for testing should be
    // configured as order of millisecond.
    task_environment_.FastForwardBy(base::Hours(1));
  }

  // Test identity environment helpers.
  void MakePrimaryAccountAvailable() {
    identity_test_env_.MakePrimaryAccountAvailable("bob@gmail.com",
                                                   ConsentLevel::kSignin);
  }
  void SetAutomaticIssueOfAccessTokens() {
    identity_test_env_.SetAutomaticIssueOfAccessTokens(/*grant=*/true);
  }

  bool MetricsAreExpected() const {
    return GetConfig().histogram_basename.has_value();
  }

 private:
  // Must be first attribute, see base::test::TaskEnvironment docs.
  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  FetcherConfig config_;

 protected:
  network::TestURLLoaderFactory test_url_loader_factory_;
  IdentityTestEnvironment identity_test_env_;
  base::test::ScopedFeatureList feature_list_;
};

class ProtoFetcherTest : public ProtoFetcherTestBase,
                         public ::testing::TestWithParam<FetcherConfig> {
 public:
  ProtoFetcherTest() : ProtoFetcherTestBase(GetConfig()) {}
  static const FetcherConfig& GetConfig() { return GetParam(); }

  void SetUp() override {
    CHECK(GetConfig().access_token_config.has_value() &&
          GetConfig().access_token_config->credentials_requirement ==
              AccessTokenConfig::CredentialsRequirement::kStrict)
        << "To test other credential requirements than strict mode (eg.: best "
           "effort mode), use BestEffortProtoFetcherTest suite below.";
  }
};

// Test whether the outgoing request has correctly set endpoint and method.
TEST_P(ProtoFetcherTest, ConfiguresEndpoint) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  TestURLLoaderFactory::PendingRequest* pending_request =
      test_url_loader_factory_.GetPendingRequest(0);

  GURL expected_url =
      GURL("http://" + std::string(kMockEndpointDomain) +
           std::string(GetConfig().StaticServicePath()) + "?alt=proto");
  EXPECT_EQ(pending_request->request.url, expected_url);
  EXPECT_EQ(pending_request->request.method, GetConfig().GetHttpMethod());
}

// Test whether the outgoing request has the HTTP payload, only for those HTTP
// verbs that support it.
TEST_P(ProtoFetcherTest, AddsPayload) {
  if (GetConfig().method != FetcherConfig::Method::kPost) {
    GTEST_SKIP() << "Payload not supported for " << GetConfig().GetHttpMethod()
                 << " requests.";
  }

  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  TestURLLoaderFactory::PendingRequest* pending_request =
      test_url_loader_factory_.GetPendingRequest(0);

  EXPECT_EQ(pending_request->request.headers.GetHeader(
                net::HttpRequestHeaders::kContentType),
            "application/x-protobuf");
}

// Tests a default flow, where an empty (default) proto is received.
TEST_P(ProtoFetcherTest, AcceptsRequests) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateDefaultResponseForPendingRequest(0);

  EXPECT_TRUE(receiver->GetResult().has_value());
}

// Tests a flow where the caller is denied access token. There should be
// response consumed, that indicated auth error and contains details about the
// reason for denying access.
TEST_P(ProtoFetcherTest, NoAccessTokenStrict) {
  MakePrimaryAccountAvailable();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  base::HistogramTester histogram_tester;

  identity_test_env_.WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      GoogleServiceAuthError(
          GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS));

  EXPECT_EQ(test_url_loader_factory_.NumPending(), 0);
  EXPECT_EQ(receiver->GetResult().error().state(),
            ProtoFetcherStatus::State::GOOGLE_SERVICE_AUTH_ERROR);

  if (MetricsAreExpected()) {
    // This tests just the metrics related to the auth error case; the rest of
    // the metrics are tested in other tests.
    histogram_tester.ExpectUniqueSample(
        base::StrCat({*GetConfig().histogram_basename, ".Status"}),
        ProtoFetcherStatus::State::GOOGLE_SERVICE_AUTH_ERROR, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat({*GetConfig().histogram_basename, ".AuthError"}),
        GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS, 1);
  }
}

// Tests a flow where incoming data from RPC can't be deserialized to a valid
// proto.
TEST_P(ProtoFetcherTest, HandlesMalformedResponse) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequest(0, "malformed-value");

  EXPECT_FALSE(receiver->GetResult().has_value());
  EXPECT_EQ(receiver->GetResult().error().state(),
            ProtoFetcherStatus::State::INVALID_RESPONSE);
}

// Tests whether access token information is added to the request in a right
// header.
TEST_P(ProtoFetcherTest, CreatesToken) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  // That's enough: request is pending, so token is accepted.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);

  // Only check header format here.
  EXPECT_EQ(
      test_url_loader_factory_.GetPendingRequest(0)->request.headers.GetHeader(
          net::HttpRequestHeaders::kAuthorization),
      "Bearer access_token");
}

// Tests a flow where the request couldn't be completed due to network
// infrastructure errors. The result must contain details about the error.
TEST_P(ProtoFetcherTest, HandlesNetworkError) {
  if (GetConfig().backoff_policy.has_value()) {
    GTEST_SKIP() << "Test not suitable for retrying fetchers: is serves "
                    "transient errors which do not produce results.";
  }

  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);

  test_url_loader_factory_.SimulateResponseForPendingRequest(
      GetUrlOfPendingRequest(0),
      network::URLLoaderCompletionStatus(net::ERR_UNEXPECTED),
      network::CreateURLResponseHead(net::HTTP_OK), /*content=*/"");
  EXPECT_FALSE(receiver->GetResult().has_value());
  EXPECT_EQ(receiver->GetResult().error().state(),
            ProtoFetcherStatus::State::HTTP_STATUS_OR_NET_ERROR);
  EXPECT_EQ(receiver->GetResult().error().http_status_or_net_error(),
            ProtoFetcherStatus::HttpStatusOrNetErrorType(net::ERR_UNEXPECTED));
}

// Tests a flow where the remote server couldn't process the request and
// responded with an error.
TEST_P(ProtoFetcherTest, HandlesServerError) {
  if (GetConfig().backoff_policy.has_value()) {
    GTEST_SKIP() << "Test not suitable for retrying fetchers: is serves "
                    "transient errors which do not produce results.";
  }

  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  test_url_loader_factory_.SimulateResponseForPendingRequest(
      GetUrlOfPendingRequest(0).spec(), /*content=*/"", net::HTTP_BAD_REQUEST);

  EXPECT_FALSE(receiver->GetResult().has_value());
  EXPECT_EQ(receiver->GetResult().error().state(),
            ProtoFetcherStatus::State::HTTP_STATUS_OR_NET_ERROR);
  EXPECT_EQ(
      receiver->GetResult().error().http_status_or_net_error(),
      ProtoFetcherStatus::HttpStatusOrNetErrorType(net::HTTP_BAD_REQUEST));
}

// Tests a flow where the remote server responds with an auth error (401).
TEST_P(ProtoFetcherTest, HandlesRepeatedServerAuthError) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequestWithHttpAuthError(0);

  // The request is failed.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 0);
  EXPECT_FALSE(receiver->GetResult().has_value());
  EXPECT_EQ(receiver->GetResult().error().state(),
            ProtoFetcherStatus::State::HTTP_STATUS_OR_NET_ERROR);
  EXPECT_EQ(
      receiver->GetResult().error().http_status_or_net_error(),
      ProtoFetcherStatus::HttpStatusOrNetErrorType(net::HTTP_UNAUTHORIZED));
}

// Tests a flow where the remote server responds with an auth error (401), and
// then the request succeeds on retry.
TEST_P(ProtoFetcherTest, HandlesServerAuthErrorThenSuccess) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequestWithHttpAuthError(0);

  // The request is failed.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 0);
  EXPECT_FALSE(receiver->GetResult().has_value());
  EXPECT_EQ(receiver->GetResult().error().state(),
            ProtoFetcherStatus::State::HTTP_STATUS_OR_NET_ERROR);
  EXPECT_EQ(
      receiver->GetResult().error().http_status_or_net_error(),
      ProtoFetcherStatus::HttpStatusOrNetErrorType(net::HTTP_UNAUTHORIZED));
}

// The fetchers are recording various metrics for the basic flow with default
// empty proto response. This test is checking whether all metrics receive
// right values.
TEST_P(ProtoFetcherTest, RecordsMetrics) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());
  base::HistogramTester histogram_tester;

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateDefaultResponseForPendingRequest(0);

  ASSERT_TRUE(receiver->GetResult().has_value());

  if (MetricsAreExpected()) {
    // The actual latency of mocked fetch is variable, so only expect that
    // some value was recorded.
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".Latency"}),
        /*expected_count(grew by)*/ 1);
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".NoError.Latency"}),
        /*expected_count(grew by)*/ 1);

    EXPECT_THAT(
        histogram_tester.GetAllSamples(
            base::StrCat({*GetConfig().histogram_basename, ".Status"})),
        base::BucketsInclude(
            base::Bucket(ProtoFetcherStatus::State::OK, /*count=*/1),
            base::Bucket(ProtoFetcherStatus::State::GOOGLE_SERVICE_AUTH_ERROR,
                         /*count=*/0)));
  }
}

// When retrying is configured, the fetch process is re-launched until a
// decisive status is received (OK or permanent error, see
// RetryingFetcherImpl::ShouldRetry for details). This tests checks that the
// compound fetch process eventually terminates and that related metrics are
// also recorded.
TEST_P(ProtoFetcherTest, RetryingFetcherTerminatesOnOkStatusAndRecordsMetrics) {
  if (!GetConfig().backoff_policy.has_value()) {
    GTEST_SKIP() << "Tests retrying features.";
  }

  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  base::HistogramTester histogram_tester;

  // First transient errors.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequestWithTransientError(0);
  FastForward();

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequestWithTransientError(0);
  FastForward();

  // Then success.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateDefaultResponseForPendingRequest(0);
  FastForward();

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 0);

  EXPECT_TRUE(receiver->HasResultOrError());
  EXPECT_TRUE(receiver->GetResult().has_value());

  if (MetricsAreExpected()) {
    // Expect that one sample with value 3 (number of requests) was recorded.
    EXPECT_THAT(histogram_tester.GetAllSamples(base::StrCat(
                    {*GetConfig().histogram_basename, ".RetryCount"})),
                base::BucketsInclude(base::Bucket(3, 1)));

    // The actual latency of mocked fetch is variable, so only expect that
    // some value was recorded.
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".OverallLatency"}),
        /*expected_count(grew by)*/ 1);

    EXPECT_THAT(histogram_tester.GetAllSamples(base::StrCat(
                    {*GetConfig().histogram_basename, ".OverallStatus"})),
                base::BucketsInclude(
                    base::Bucket(ProtoFetcherStatus::State::OK, /*count=*/1)));

    // Individual status and latencies were also recorded because the compound
    // fetcher consists of an individual fetchers. Note that the count of
    // individual metrics grew by the number related to number of responses
    // used.

    // The actual latency of mocked fetch is variable, so only expect that
    // some value was recorded.
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".Latency"}),
        /*expected_count(grew by)*/ 3);
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".NoError.Latency"}),
        /*expected_count(grew by)*/ 1);

    histogram_tester.ExpectTotalCount(
        base::StrCat(
            {*GetConfig().histogram_basename, ".HttpStatusOrNetError.Latency"}),
        /*expected_count(grew by)*/ 2);

    EXPECT_THAT(
        histogram_tester.GetAllSamples(
            base::StrCat({*GetConfig().histogram_basename, ".Status"})),
        base::BucketsInclude(
            base::Bucket(ProtoFetcherStatus::State::OK, /*count=*/1),
            base::Bucket(ProtoFetcherStatus::State::HTTP_STATUS_OR_NET_ERROR,
                         /*count=*/2)));
  }
}

// When retrying is configured, the fetch process is re-launched until a
// decisive status is received (OK or permanent error, see
// RetryingFetcherImpl::ShouldRetry for details). This tests checks that the
// compound fetch process eventually terminates and that related metrics are
// also recorded.
TEST_P(ProtoFetcherTest,
       RetryingFetcherTerminatesOnPersistentErrorAndRecordsMetrics) {
  if (!GetConfig().backoff_policy.has_value()) {
    GTEST_SKIP() << "Tests retrying features.";
  }

  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  base::HistogramTester histogram_tester;

  // First transient error.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequestWithTransientError(0);
  FastForward();

  // Then persistent error.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateMalformedResponseForPendingRequest(0);
  FastForward();

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 0);

  EXPECT_TRUE(receiver->HasResultOrError());
  EXPECT_TRUE(receiver->GetResult().error().IsPersistentError());

  if (MetricsAreExpected()) {
    // Expect that one sample with value 2 (number of requests) was recorded.
    EXPECT_THAT(histogram_tester.GetAllSamples(base::StrCat(
                    {*GetConfig().histogram_basename, ".RetryCount"})),
                base::BucketsInclude(base::Bucket(2, 1)));

    // The actual latency of mocked fetch is variable, so only expect that
    // some value was recorded.
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".OverallLatency"}),
        /*expected_count(grew by)*/ 1);

    EXPECT_THAT(histogram_tester.GetAllSamples(base::StrCat(
                    {*GetConfig().histogram_basename, ".OverallStatus"})),
                base::BucketsInclude(base::Bucket(
                    ProtoFetcherStatus::State::INVALID_RESPONSE, 1)));

    // Individual status and latencies were also recorded because the compound
    // fetcher consists of an individual fetchers. Note that the count of
    // individual metrics grew by the number related to number of responses
    // used.

    // The actual latency of mocked fetch is variable, so only expect that
    // some value was recorded.
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".Latency"}),
        /*expected_count(grew by)*/ 2);
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".ParseError.Latency"}),
        /*expected_count(grew by)*/ 1);

    histogram_tester.ExpectTotalCount(
        base::StrCat(
            {*GetConfig().histogram_basename, ".HttpStatusOrNetError.Latency"}),
        /*expected_count(grew by)*/ 1);

    EXPECT_THAT(
        histogram_tester.GetAllSamples(
            base::StrCat({*GetConfig().histogram_basename, ".Status"})),
        base::BucketsInclude(
            base::Bucket(ProtoFetcherStatus::State::INVALID_RESPONSE,
                         /*count=*/1),
            base::Bucket(ProtoFetcherStatus::State::HTTP_STATUS_OR_NET_ERROR,
                         /*count=*/1)));
  }
}

// When retrying is configured, the fetch process is re-launched until a
// decisive status is received (OK or permanent error, see
// RetryingFetcherImpl::ShouldRetry for details). This tests assumes only
// transient error responses from the server (eg. those that are expect to go
// away on their own soon). This means that no response will be received, and
// no extra retrying metrics recording, because the process is still not
// finished.
TEST_P(ProtoFetcherTest, RetryingFetcherContinuesOnTransientError) {
  if (!GetConfig().backoff_policy.has_value()) {
    GTEST_SKIP() << "Tests retrying features.";
  }

  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  base::HistogramTester histogram_tester;

  // Only transient errors.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequestWithTransientError(0);
  FastForward();

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  SimulateResponseForPendingRequestWithTransientError(0);
  FastForward();

  // Request is still pending, because the system keeps retrying.
  EXPECT_EQ(test_url_loader_factory_.NumPending(), 1);
  EXPECT_FALSE(receiver->HasResultOrError());

  if (MetricsAreExpected()) {
    // No final status was recorded as the fetcher is still pending.
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".OverallStatus"}),
        /*expected_count(grew by)*/ 0);

    // Individual status and latencies were also recorded because the compound
    // fetcher consists of an individual fetchers. Note that the count of
    // individual metrics grew by the number related to number of responses
    // used.

    // The actual latency of mocked fetch is variable, so only expect that
    // some value was recorded.
    histogram_tester.ExpectTotalCount(
        base::StrCat({*GetConfig().histogram_basename, ".Latency"}),
        /*expected_count(grew by)*/ 2);
    histogram_tester.ExpectTotalCount(
        base::StrCat(
            {*GetConfig().histogram_basename, ".HttpStatusOrNetError.Latency"}),
        /*expected_count(grew by)*/ 2);

    EXPECT_THAT(histogram_tester.GetAllSamples(
                    base::StrCat({*GetConfig().histogram_basename, ".Status"})),
                base::BucketsInclude(base::Bucket(
                    ProtoFetcherStatus::State::HTTP_STATUS_OR_NET_ERROR,
                    /*count=*/2)));
  }
}

// Instead of /0, /1... print human-readable description of the test: status
// of the retrying feature followed by http method.
std::string PrettyPrintFetcherTestCaseName(
    const ::testing::TestParamInfo<FetcherConfig>& info) {
  const FetcherConfig& fetcher_config = info.param;
  std::string base = fetcher_config.GetHttpMethod();
  if (fetcher_config.backoff_policy.has_value()) {
    base += "Retrying";
  }
  if (fetcher_config.histogram_basename.has_value()) {
    base += "WithMetrics";
  } else {
    base += "WithoutMetrics";
  }
  return base;
}

INSTANTIATE_TEST_SUITE_P(All,
                         ProtoFetcherTest,
                         testing::Values(kTestGetConfig,
                                         kTestPostConfig,
                                         kTestRetryConfig,
                                         kTestGetConfigWithoutMetrics),
                         &PrettyPrintFetcherTestCaseName);

class BestEffortProtoFetcherTest : public ProtoFetcherTestBase,
                                   public testing::Test {
 public:
  BestEffortProtoFetcherTest() : ProtoFetcherTestBase(GetConfig()) {}
  static const FetcherConfig& GetConfig() {
    return kTestGetConfigBestEffortAccessToken;
  }
};

// Tests a flow where the caller is denied access token.
//
// Since the fetcher config specifies best effort as the credentials
// requirement, the request proceeds.
TEST_F(BestEffortProtoFetcherTest, NoAccessToken) {
  MakePrimaryAccountAvailable();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  base::HistogramTester histogram_tester;

  identity_test_env_.WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
      GoogleServiceAuthError(
          GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS));

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  ASSERT_TRUE(google_apis::test_util::HasAPIKey(
      test_url_loader_factory_.GetPendingRequest(0)->request));

  SimulateDefaultResponseForPendingRequest(0);

  EXPECT_TRUE(receiver->GetResult().has_value());

  // Check that both the overall Status, and the detailed AuthError metrics
  // are recorded.
  EXPECT_THAT(
      histogram_tester.GetAllSamples(
          base::StrCat({*GetConfig().histogram_basename, ".Status"})),
      base::BucketsInclude(
          base::Bucket(ProtoFetcherStatus::State::GOOGLE_SERVICE_AUTH_ERROR,
                       /*count=*/1),
          base::Bucket(ProtoFetcherStatus::State::OK,
                       /*count=*/1)));

  histogram_tester.ExpectUniqueSample(
      base::StrCat({*GetConfig().histogram_basename, ".AuthError"}),
      GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS, 1);
}

// Tests a flow where the caller is denied access token.
//
// Since the fetcher config specifies best effort as the credentials
// requirement, the request proceeds.
TEST_F(BestEffortProtoFetcherTest, RetryAfterHttpAuthError) {
  MakePrimaryAccountAvailable();
  SetAutomaticIssueOfAccessTokens();
  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  ASSERT_FALSE(google_apis::test_util::HasAPIKey(
      test_url_loader_factory_.GetPendingRequest(0)->request));

  SimulateResponseForPendingRequestWithHttpAuthError(0);

  // The request is retried without EUC.
  ASSERT_EQ(test_url_loader_factory_.NumPending(), 1);
  ASSERT_TRUE(google_apis::test_util::HasAPIKey(
      test_url_loader_factory_.GetPendingRequest(0)->request));

  // The server responds OK.
  SimulateDefaultResponseForPendingRequest(0);

  // The response is successful.
  EXPECT_TRUE(receiver->GetResult().has_value());
}

class NoCredentialsProtoFetcherTest : public ProtoFetcherTestBase,
                                      public testing::Test {
 protected:
  NoCredentialsProtoFetcherTest() : ProtoFetcherTestBase(GetConfig()) {}
  static const FetcherConfig& GetConfig() {
    return kTestGetConfigWithoutCredentials;
  }
};

// Tests a flow where the caller never provided any credentials.
//
// Since the fetcher config is not requesting the access token, the request
// succeeds.
TEST_F(NoCredentialsProtoFetcherTest, SuccessWithoutAccessToken) {
  ASSERT_FALSE(identity_test_env_.identity_manager()->HasPrimaryAccount(
      signin::ConsentLevel::kSignin));

  std::unique_ptr<Receiver> receiver = MakeReceiver();
  std::unique_ptr<Fetcher> fetcher = MakeFetcher(*receiver.get());

  base::HistogramTester histogram_tester;

  EXPECT_EQ(test_url_loader_factory_.NumPending(), 1);
  ASSERT_TRUE(google_apis::test_util::HasAPIKey(
      test_url_loader_factory_.GetPendingRequest(0)->request));
  SimulateDefaultResponseForPendingRequest(0);

  EXPECT_TRUE(receiver->GetResult().has_value());
  EXPECT_THAT(histogram_tester.GetAllSamples(
                  base::StrCat({*GetConfig().histogram_basename, ".Status"})),
              base::BucketsInclude(base::Bucket(ProtoFetcherStatus::State::OK,
                                                /*count=*/1)));
}

}  // namespace
}  // namespace supervised_user