File: plus_address_service_unittest.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (812 lines) | stat: -rw-r--r-- 36,650 bytes parent folder | download
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
// 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/plus_addresses/plus_address_service.h"

#include "base/test/mock_callback.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 "components/plus_addresses/features.h"
#include "components/plus_addresses/plus_address_client.h"
#include "components/plus_addresses/plus_address_prefs.h"
#include "components/plus_addresses/plus_address_service.h"
#include "components/plus_addresses/plus_address_test_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/testing_pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"

namespace plus_addresses {

class PlusAddressServiceTest : public ::testing::Test {
 protected:
  // Not used directly, but required for `IdentityTestEnvironment` to work.
  base::test::TaskEnvironment task_environment_;
};

TEST_F(PlusAddressServiceTest, BasicTest) {
  const url::Origin test_origin =
      url::Origin::Create(GURL("https://test.asdf.example"));
  const std::string test_address = "mattwashere";
  PlusAddressService service;
  EXPECT_FALSE(service.IsPlusAddress(test_address));
  service.SavePlusAddress(test_origin, test_address);
  EXPECT_TRUE(service.IsPlusAddress(test_address));
  EXPECT_EQ(service.GetPlusAddress(test_origin), test_address);
  EXPECT_EQ(service.GetPlusAddress(url::Origin()), absl::nullopt);
  EXPECT_EQ(service.GetPlusProfile(test_origin)->plus_address, test_address);
}

TEST_F(PlusAddressServiceTest, EnsureEtldPlusOneScope) {
  const url::Origin test_origin =
      url::Origin::Create(GURL("https://asdf.example"));
  const url::Origin test_origin_subdomain =
      url::Origin::Create(GURL("https://test.asdf.example"));
  const std::string test_address = "mattwashere";
  PlusAddressService service;
  service.SavePlusAddress(test_origin, test_address);
  EXPECT_EQ(service.GetPlusAddress(test_origin), test_address);
  EXPECT_EQ(service.GetPlusAddress(test_origin_subdomain), test_address);
  EXPECT_EQ(service.GetPlusProfile(test_origin)->plus_address, test_address);
  EXPECT_EQ(service.GetPlusProfile(test_origin_subdomain)->plus_address,
            test_address);
}

TEST_F(PlusAddressServiceTest, EnsureEtldPlusOneScopeSubdomainAddedFirst) {
  const url::Origin test_origin =
      url::Origin::Create(GURL("https://asdf.example"));
  const url::Origin test_origin_subdomain =
      url::Origin::Create(GURL("https://test.asdf.example"));
  const std::string test_address = "mattwashere";
  PlusAddressService service;
  service.SavePlusAddress(test_origin_subdomain, test_address);
  EXPECT_EQ(service.GetPlusAddress(test_origin), test_address);
  EXPECT_EQ(service.GetPlusAddress(test_origin_subdomain), test_address);
  EXPECT_EQ(service.GetPlusProfile(test_origin)->plus_address, test_address);
  EXPECT_EQ(service.GetPlusProfile(test_origin_subdomain)->plus_address,
            test_address);
}

TEST_F(PlusAddressServiceTest, DefaultSupportsPlusAddressesState) {
  // By default, the `SupportsPlusAddresses` function should return `false`.
  PlusAddressService service;
  EXPECT_FALSE(service.SupportsPlusAddresses(
      url::Origin::Create(GURL("https://test.example"))));
}

// Tests for the label overrides. These tests are not in the enabled/disabled
// fixtures as they vary parameters.
TEST_F(PlusAddressServiceTest, LabelOverrides) {
  base::test::ScopedFeatureList scoped_feature_list;
  // Setting the override should result in echoing the override back.
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      plus_addresses::kFeature,
      {{plus_addresses::kEnterprisePlusAddressLabelOverride.name,
        "mattwashere"}});
  PlusAddressService service;
  EXPECT_EQ(service.GetCreateSuggestionLabel(), u"mattwashere");
}

TEST_F(PlusAddressServiceTest, LabelOverrideWithSpaces) {
  base::test::ScopedFeatureList scoped_feature_list;
  // Setting the override should result in echoing the override back.
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      plus_addresses::kFeature,
      {{plus_addresses::kEnterprisePlusAddressLabelOverride.name,
        "matt was here"}});
  PlusAddressService service;
  EXPECT_EQ(service.GetCreateSuggestionLabel(), u"matt was here");
}

TEST_F(PlusAddressServiceTest, NoAccountPlusAddressCreation) {
  signin::IdentityTestEnvironment identity_test_env;
  PlusAddressService service(identity_test_env.identity_manager());
  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));

  base::MockOnceCallback<void(const std::string&)> offer_callback;
  base::MockOnceCallback<void(const PlusProfileOrError&)> reserve_callback;
  base::MockOnceCallback<void(const PlusProfileOrError&)> confirm_callback;
  // Ensure that the lambdas aren't called since there is no signed-in account.
  EXPECT_CALL(offer_callback, Run).Times(0);
  service.OfferPlusAddressCreation(no_subdomain_origin, offer_callback.Get());
  EXPECT_CALL(reserve_callback, Run).Times(0);
  service.ReservePlusAddress(no_subdomain_origin, reserve_callback.Get());
  EXPECT_CALL(confirm_callback, Run).Times(0);
  service.ConfirmPlusAddress(no_subdomain_origin, "unused",
                             confirm_callback.Get());
}

TEST_F(PlusAddressServiceTest, AbortPlusAddressCreation) {
  const std::string invalid_email = "plus";
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable(invalid_email,
                                         {signin::ConsentLevel::kSignin});

  PlusAddressService service(identity_test_env.identity_manager());
  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));

  base::MockOnceCallback<void(const std::string&)> offer_callback;
  base::MockOnceCallback<void(const PlusProfileOrError&)> reserve_callback;
  base::MockOnceCallback<void(const PlusProfileOrError&)> confirm_callback;
  // Ensure that the lambdas aren't called since there is no signed-in account.
  EXPECT_CALL(offer_callback, Run).Times(0);
  service.OfferPlusAddressCreation(no_subdomain_origin, offer_callback.Get());
  EXPECT_CALL(reserve_callback, Run).Times(0);
  service.ReservePlusAddress(no_subdomain_origin, reserve_callback.Get());
  EXPECT_CALL(confirm_callback, Run).Times(0);
  service.ConfirmPlusAddress(no_subdomain_origin, "unused",
                             confirm_callback.Get());
}

// Tests the PlusAddressService ability to make network requests.
class PlusAddressServiceRequestsTest : public ::testing::Test {
 public:
  explicit PlusAddressServiceRequestsTest() {
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        plus_addresses::kFeature,
        {{"server-url", server_url.spec()}, {"oauth-scope", "scope.example"}});
    test_shared_loader_factory =
        base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
            &test_url_loader_factory);
    plus_profiles_endpoint =
        server_url.Resolve(kServerPlusProfileEndpoint).spec();
    reserve_plus_address_endpoint =
        server_url.Resolve(kServerReservePlusAddressEndpoint).spec();
    confirm_plus_address_endpoint =
        server_url.Resolve(kServerCreatePlusAddressEndpoint).spec();
  }

 protected:
  base::test::ScopedFeatureList* features() { return &scoped_feature_list_; }

  GURL server_url = GURL("https://server.example");
  signin::AccessTokenInfo eternal_access_token_info =
      signin::AccessTokenInfo("auth-token", base::Time::Max(), "");
  network::TestURLLoaderFactory test_url_loader_factory;
  scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory;
  std::string plus_profiles_endpoint;
  std::string reserve_plus_address_endpoint;
  std::string confirm_plus_address_endpoint;

 private:
  // Required for `IdentityTestEnvironment` and `InProcessDataDecoder` to work.
  base::test::TaskEnvironment task_environment_;
  data_decoder::test::InProcessDataDecoder decoder_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_F(PlusAddressServiceRequestsTest, OfferPlusAddressCreation) {
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));

  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));
  const std::string site = "test.example";
  const std::string plus_address = "plus+remote@plus.plus";

  base::test::TestFuture<const std::string&> future;
  service.OfferPlusAddressCreation(no_subdomain_origin, future.GetCallback());

  // Check that the future callback is blocked and unblock it.
  ASSERT_FALSE(future.IsReady());
  test_url_loader_factory.SimulateResponseForPendingRequest(
      plus_profiles_endpoint,
      test::MakeCreationResponse(
          PlusProfile({.facet = site, .plus_address = plus_address})));
  ASSERT_TRUE(future.IsReady());
  EXPECT_EQ(future.Get(), plus_address);

  // Assert that ensuing calls to the same facet do not make a network request.
  const url::Origin subdomain_origin =
      url::Origin::Create(GURL("https://subdomain.test.example"));
  base::test::TestFuture<const std::string&> second_future;
  service.OfferPlusAddressCreation(no_subdomain_origin,
                                   second_future.GetCallback());
  ASSERT_TRUE(second_future.IsReady());
  EXPECT_EQ(second_future.Get(), plus_address);
}

TEST_F(PlusAddressServiceRequestsTest, ReservePlusAddress_ReturnsUnconfirmed) {
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));

  base::test::TestFuture<const PlusProfileOrError&> future;
  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));
  std::string site = "test.example";
  std::string plus_address = "plus+remote@plus.plus";

  service.ReservePlusAddress(no_subdomain_origin, future.GetCallback());

  // Check that the future callback is still blocked, and unblock it.
  ASSERT_FALSE(future.IsReady());
  test_url_loader_factory.SimulateResponseForPendingRequest(
      reserve_plus_address_endpoint,
      test::MakeCreationResponse(PlusProfile({.facet = site,
                                              .plus_address = plus_address,
                                              .is_confirmed = false})));
  ASSERT_TRUE(future.IsReady());
  EXPECT_EQ(future.Get()->plus_address, plus_address);

  // The service should not save plus_address if it hasn't been confirmed yet.
  EXPECT_FALSE(service.IsPlusAddress(plus_address));
}

TEST_F(PlusAddressServiceRequestsTest, ReservePlusAddress_ReturnsConfirmed) {
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));

  base::test::TestFuture<const PlusProfileOrError&> future;
  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));
  const std::string site = "test.example";
  const std::string plus_address = "plus+remote@plus.plus";

  service.ReservePlusAddress(no_subdomain_origin, future.GetCallback());

  // Check that the future callback is still blocked, and unblock it.
  ASSERT_FALSE(future.IsReady());
  test_url_loader_factory.SimulateResponseForPendingRequest(
      reserve_plus_address_endpoint,
      test::MakeCreationResponse(PlusProfile({.facet = site,
                                              .plus_address = plus_address,
                                              .is_confirmed = true})));
  ASSERT_TRUE(future.IsReady());
  EXPECT_EQ(future.Get()->plus_address, plus_address);

  // The service should save plus_address if it has already been confirmed.
  EXPECT_TRUE(service.IsPlusAddress(plus_address));
}

TEST_F(PlusAddressServiceRequestsTest, ReservePlusAddress_Fails) {
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));

  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));
  const std::string site = "test.example";
  const std::string plus_address = "plus+remote@plus.plus";

  base::test::TestFuture<const PlusProfileOrError&> future;
  service.ReservePlusAddress(no_subdomain_origin, future.GetCallback());

  // Check that the future callback is still blocked, and unblock it.
  ASSERT_FALSE(future.IsReady());
  test_url_loader_factory.SimulateResponseForPendingRequest(
      reserve_plus_address_endpoint, "", net::HTTP_BAD_REQUEST);
  ASSERT_TRUE(future.IsReady());
  EXPECT_FALSE(future.Get().has_value());
}

TEST_F(PlusAddressServiceRequestsTest, ConfirmPlusAddress_Successful) {
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));

  base::test::TestFuture<const PlusProfileOrError&> future;
  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));
  const std::string site = "test.example";
  const std::string plus_address = "plus+remote@plus.plus";

  service.ConfirmPlusAddress(no_subdomain_origin, plus_address,
                             future.GetCallback());

  // Check that the future callback is still blocked, and unblock it.
  ASSERT_FALSE(future.IsReady());
  test_url_loader_factory.SimulateResponseForPendingRequest(
      confirm_plus_address_endpoint,
      test::MakeCreationResponse(
          PlusProfile({.facet = site, .plus_address = plus_address})));
  ASSERT_TRUE(future.IsReady());
  EXPECT_EQ(future.Get()->plus_address, plus_address);
  // Verify that the plus_address is saved when confirmation is successful.
  EXPECT_TRUE(service.IsPlusAddress(plus_address));

  // Assert that ensuing calls to the same facet do not make a network request.
  const url::Origin subdomain_origin =
      url::Origin::Create(GURL("https://subdomain.test.example"));
  base::test::TestFuture<const PlusProfileOrError&> second_future;
  service.ConfirmPlusAddress(no_subdomain_origin, plus_address,
                             second_future.GetCallback());
  ASSERT_TRUE(second_future.IsReady());
  EXPECT_EQ(second_future.Get()->plus_address, plus_address);
}

TEST_F(PlusAddressServiceRequestsTest, ConfirmPlusAddress_Fails) {
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));
  std::string plus_address = "plus+remote@plus.plus";
  ASSERT_FALSE(service.IsPlusAddress(plus_address));

  base::test::TestFuture<const PlusProfileOrError&> future;
  const url::Origin no_subdomain_origin =
      url::Origin::Create(GURL("https://test.example"));
  service.ConfirmPlusAddress(no_subdomain_origin, plus_address,
                             future.GetCallback());

  // Check that the future callback is still blocked, and unblock it.
  ASSERT_FALSE(future.IsReady());
  test_url_loader_factory.SimulateResponseForPendingRequest(
      confirm_plus_address_endpoint, "", net::HTTP_BAD_REQUEST);
  ASSERT_TRUE(future.IsReady());

  // An error is propagated from the callback and plus_address is not saved.
  EXPECT_FALSE(future.Get().has_value());
  EXPECT_FALSE(service.IsPlusAddress(plus_address));
}

// Doesn't run on ChromeOS since ClearPrimaryAccount() doesn't exist for it.
#if !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(PlusAddressServiceRequestsTest,
       PrimaryAccountCleared_TogglesPlusAddressCreationOff) {
  // Setup state where the PlusAddressService would create a PlusAddress.
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakePrimaryAccountAvailable("plus@plus.plus",
                                                signin::ConsentLevel::kSignin);
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));
  const url::Origin test_origin =
      url::Origin::Create(GURL("https://test.example"));
  const std::string site = "test.example";
  const std::string plus_address = "plus+remote@plus.plus";
  // Toggle creation off by removing the primary account.
  identity_test_env.ClearPrimaryAccount();

  // Verify that Plus Address creation doesn't occur.
  service.ReservePlusAddress(test_origin, base::DoNothing());
  service.ConfirmPlusAddress(test_origin, plus_address, base::DoNothing());
  EXPECT_EQ(test_url_loader_factory.NumPending(), 0);

  // Toggle creation back on by signing in again.
  identity_test_env.MakePrimaryAccountAvailable("plus@plus.plus",
                                                signin::ConsentLevel::kSignin);

  // Verify that Plus Address creation occurs and makes a network request.
  base::test::TestFuture<const PlusProfileOrError&> reserve;
  service.ReservePlusAddress(test_origin, reserve.GetCallback());
  EXPECT_EQ(test_url_loader_factory.NumPending(), 1);
  test_url_loader_factory.SimulateResponseForPendingRequest(
      reserve_plus_address_endpoint,
      test::MakeCreationResponse(
          PlusProfile({.facet = site, .plus_address = plus_address})));
  EXPECT_EQ(reserve.Get()->plus_address, plus_address);

  base::test::TestFuture<const PlusProfileOrError&> confirm;
  service.ConfirmPlusAddress(test_origin, plus_address, confirm.GetCallback());
  EXPECT_EQ(test_url_loader_factory.NumPending(), 1);
  test_url_loader_factory.SimulateResponseForPendingRequest(
      confirm_plus_address_endpoint,
      test::MakeCreationResponse(
          PlusProfile({.facet = site, .plus_address = plus_address})));
  EXPECT_EQ(confirm.Get()->plus_address, plus_address);
}
#endif  // !BUILDFLAG(IS_CHROMEOS_ASH)

TEST_F(PlusAddressServiceRequestsTest,
       PrimaryRefreshTokenError_TogglesPlusAddressCreationOff) {
  // Setup state where the PlusAddressService would create a PlusAddress.
  signin::IdentityTestEnvironment identity_test_env;
  AccountInfo primary_account = identity_test_env.MakePrimaryAccountAvailable(
      "plus@plus.plus", signin::ConsentLevel::kSignin);
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressService service(
      identity_test_env.identity_manager(), nullptr,
      PlusAddressClient(identity_test_env.identity_manager(),
                        test_shared_loader_factory));
  const url::Origin test_origin =
      url::Origin::Create(GURL("https://test.example"));
  const std::string site = "test.example";
  const std::string plus_address = "plus+remote@plus.plus";

  // Toggle creation off by triggering an error for the primary refresh token.
  identity_test_env.UpdatePersistentErrorOfRefreshTokenForAccount(
      primary_account.account_id,
      GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));

  // Verify that Plus Address creation doesn't occur.
  service.ReservePlusAddress(test_origin, base::DoNothing());
  service.ConfirmPlusAddress(test_origin, plus_address, base::DoNothing());
  EXPECT_EQ(test_url_loader_factory.NumPending(), 0);

  // Toggle creation back on by removing the error.
  identity_test_env.UpdatePersistentErrorOfRefreshTokenForAccount(
      primary_account.account_id,
      GoogleServiceAuthError(GoogleServiceAuthError::NONE));

  // Verify that Plus Address creation occurs and makes a network request.
  base::test::TestFuture<const PlusProfileOrError&> reserve;
  service.ReservePlusAddress(test_origin, reserve.GetCallback());
  EXPECT_EQ(test_url_loader_factory.NumPending(), 1);
  test_url_loader_factory.SimulateResponseForPendingRequest(
      reserve_plus_address_endpoint,
      test::MakeCreationResponse(
          PlusProfile({.facet = site, .plus_address = plus_address})));
  EXPECT_EQ(reserve.Get()->plus_address, plus_address);

  base::test::TestFuture<const PlusProfileOrError&> confirm;
  service.ConfirmPlusAddress(test_origin, plus_address, confirm.GetCallback());
  EXPECT_EQ(test_url_loader_factory.NumPending(), 1);
  test_url_loader_factory.SimulateResponseForPendingRequest(
      confirm_plus_address_endpoint,
      test::MakeCreationResponse(
          PlusProfile({.facet = site, .plus_address = plus_address})));
  EXPECT_EQ(confirm.Get()->plus_address, plus_address);
}

// Tests the PlusAddressService ability to make network requests.
class PlusAddressServicePolling : public PlusAddressServiceRequestsTest {
 public:
  PlusAddressServicePolling() {
    features()->Reset();
    features()->InitAndEnableFeatureWithParameters(
        plus_addresses::kFeature, {
                                      {"server-url", server_url.spec()},
                                      {"oauth-scope", "scope.example"},
                                      {"sync-with-server", "true"},
                                  });
    plus_addresses::RegisterProfilePrefs(pref_service_.registry());
  }

 protected:
  PrefService* prefs() { return &pref_service_; }

 private:
  TestingPrefServiceSimple pref_service_;
};

// TODO: b/305696884 - Make this test simulate timer firing instead of
// directly calling SyncPlusAddressMapping.
TEST_F(PlusAddressServicePolling, CallsGetAllPlusAddresses) {
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressClient client(identity_test_env.identity_manager(),
                           test_shared_loader_factory);
  // The service starts the timer on construction and issues a request to
  // poll.
  PlusAddressService service(identity_test_env.identity_manager(), prefs(),
                             std::move(client));
  // Unblock the initial polling request.
  test_url_loader_factory.SimulateResponseForPendingRequest(
      plus_profiles_endpoint, test::MakeListResponse({}));

  EXPECT_FALSE(service.IsPlusAddress("plus+foo@plus.plus"));
  EXPECT_FALSE(service.IsPlusAddress("plus+bar@plus.plus"));

  service.SyncPlusAddressMapping();
  // Note: The above call blocks until we provide a response to the request.
  test_url_loader_factory.SimulateResponseForPendingRequest(
      plus_profiles_endpoint,
      test::MakeListResponse(
          {PlusProfile{.facet = "foo.com",
                       .plus_address = "plus+foo@plus.plus"},
           PlusProfile{.facet = "bar.com",
                       .plus_address = "plus+bar@plus.plus"}}));

  // The service's mapping should be updated now.
  url::Origin foo_origin = url::Origin::Create(GURL("https://foo.com"));
  ASSERT_TRUE(service.GetPlusAddress(foo_origin).has_value());
  EXPECT_EQ(service.GetPlusAddress(foo_origin).value(), "plus+foo@plus.plus");
  EXPECT_TRUE(service.IsPlusAddress("plus+foo@plus.plus"));

  url::Origin bar_origin = url::Origin::Create(GURL("https://bar.com"));
  ASSERT_TRUE(service.GetPlusAddress(bar_origin).has_value());
  EXPECT_EQ(service.GetPlusAddress(bar_origin).value(), "plus+bar@plus.plus");
  EXPECT_TRUE(service.IsPlusAddress("plus+bar@plus.plus"));
}

// Doesn't run on ChromeOS since ClearPrimaryAccount() doesn't exist for it.
#if !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(PlusAddressServicePolling, PrimaryAccountCleared_TogglesPollingOff) {
  // Setup state where the PlusAddressService begins polling on creation.
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakePrimaryAccountAvailable("plus1@plus.plus",
                                                signin::ConsentLevel::kSignin);
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressClient client(identity_test_env.identity_manager(),
                           test_shared_loader_factory);
  PlusAddressService service(identity_test_env.identity_manager(), prefs(),
                             std::move(client));
  // Unblock initial poll.
  test_url_loader_factory.SimulateResponseForPendingRequest(
      plus_profiles_endpoint, test::MakeListResponse({}));

  identity_test_env.ClearPrimaryAccount();
  service.SyncPlusAddressMapping();
  // The above doesn't block since it doesn't make network requests in this
  // state.

  // Toggle polling back on by signing into a primary account.
  identity_test_env.MakePrimaryAccountAvailable("plus2@plus.plus",
                                                signin::ConsentLevel::kSignin);
  service.SyncPlusAddressMapping();
  // TODO: b/305696884 - Remove above call to verify that observing
  // OnPrimaryAccountChanged will trigger this via CreateAndStartTimer().
  test_url_loader_factory.SimulateResponseForPendingRequest(
      plus_profiles_endpoint,
      test::MakeListResponse({PlusProfile{
          .facet = "foo.com", .plus_address = "plus+foo@plus.plus"}}));
  url::Origin foo_origin = url::Origin::Create(GURL("https://foo.com"));
  ASSERT_TRUE(service.GetPlusAddress(foo_origin).has_value());
  EXPECT_EQ(service.GetPlusAddress(foo_origin).value(), "plus+foo@plus.plus");
  EXPECT_TRUE(service.IsPlusAddress("plus+foo@plus.plus"));
}
#endif  // !BUILDFLAG(IS_CHROMEOS_ASH)

TEST_F(PlusAddressServicePolling, PrimaryRefreshTokenError_TogglesPollingOff) {
  // Setup state where the PlusAddressService begins polling on creation.
  signin::IdentityTestEnvironment identity_test_env;
  CoreAccountInfo primary_account =
      identity_test_env.MakePrimaryAccountAvailable(
          "plus1@plus.plus", signin::ConsentLevel::kSignin);
  identity_test_env.SetAutomaticIssueOfAccessTokens(true);

  PlusAddressClient client(identity_test_env.identity_manager(),
                           test_shared_loader_factory);
  PlusAddressService service(identity_test_env.identity_manager(), prefs(),
                             std::move(client));
  // Unblock initial poll.
  test_url_loader_factory.SimulateResponseForPendingRequest(
      plus_profiles_endpoint, test::MakeListResponse({}));

  // Toggle creation off by triggering an error for the primary refresh token.
  identity_test_env.UpdatePersistentErrorOfRefreshTokenForAccount(
      primary_account.account_id,
      GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
  service.SyncPlusAddressMapping();
  // The above doesn't block since it doesn't make network requests in this
  // state.

  // Toggle creation back on by removing the error.
  identity_test_env.UpdatePersistentErrorOfRefreshTokenForAccount(
      primary_account.account_id,
      GoogleServiceAuthError(GoogleServiceAuthError::NONE));
  service.SyncPlusAddressMapping();
  // TODO: b/305696884 - Remove above call to verify that observing
  // OnPrimaryAccountChanged will trigger this via CreateAndStartTimer().
  test_url_loader_factory.SimulateResponseForPendingRequest(
      plus_profiles_endpoint,
      test::MakeListResponse({PlusProfile{
          .facet = "foo.com", .plus_address = "plus+foo@plus.plus"}}));
  url::Origin foo_origin = url::Origin::Create(GURL("https://foo.com"));
  ASSERT_TRUE(service.GetPlusAddress(foo_origin).has_value());
  EXPECT_EQ(service.GetPlusAddress(foo_origin).value(), "plus+foo@plus.plus");
  EXPECT_TRUE(service.IsPlusAddress("plus+foo@plus.plus"));
}

class PlusAddressServiceDisabledTest : public PlusAddressServiceTest {
 protected:
  void SetUp() override {
    scoped_feature_list_.InitAndDisableFeature(plus_addresses::kFeature);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_F(PlusAddressServiceDisabledTest, FeatureExplicitlyDisabled) {
  // `SupportsPlusAddresses` should return `false`, even if there's a
  // signed-in user.
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  PlusAddressService service(identity_test_env.identity_manager());
  EXPECT_FALSE(service.SupportsPlusAddresses(
      url::Origin::Create(GURL("https://test.example"))));
}

TEST_F(PlusAddressServiceDisabledTest, DisabledFeatureLabel) {
  // Disabled feature? Show the default generic text.
  PlusAddressService service;
  EXPECT_EQ(service.GetCreateSuggestionLabel(), u"Lorem Ipsum");
}

class PlusAddressServiceEnabledTest : public PlusAddressServiceTest {
 private:
  base::test::ScopedFeatureList scoped_feature_list_{plus_addresses::kFeature};
};

TEST_F(PlusAddressServiceEnabledTest, NullIdentityManager) {
  // Without an identity manager, the `SupportsPlusAddresses` should return
  // `false`.
  PlusAddressService service;
  EXPECT_FALSE(service.SupportsPlusAddresses(
      url::Origin::Create(GURL("https://test.example"))));
}

TEST_F(PlusAddressServiceEnabledTest, NoSignedInUser) {
  // Without a signed in user, the `SupportsPlusAddresses` function should
  // return `false`.
  signin::IdentityTestEnvironment identity_test_env;
  PlusAddressService service(identity_test_env.identity_manager());
  EXPECT_FALSE(service.SupportsPlusAddresses(
      url::Origin::Create(GURL("https://test.example"))));
}

TEST_F(PlusAddressServiceEnabledTest, FullySupported) {
  // With a signed in user, the `SupportsPlusAddresses` function should return
  // `true`.
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable("plus@plus.plus",
                                         {signin::ConsentLevel::kSignin});
  PlusAddressService service(identity_test_env.identity_manager());
  EXPECT_TRUE(service.SupportsPlusAddresses(
      url::Origin::Create(GURL("https://test.example"))));
}

TEST_F(PlusAddressServiceEnabledTest, DefaultLabel) {
  // Override not set? Show the default generic text.
  PlusAddressService service;
  EXPECT_EQ(service.GetCreateSuggestionLabel(), u"Lorem Ipsum");
}

TEST_F(PlusAddressServiceEnabledTest, NoIdentityServiceGetEmail) {
  PlusAddressService service;
  EXPECT_EQ(service.GetPrimaryEmail(), absl::nullopt);
}

TEST_F(PlusAddressServiceEnabledTest, SignedOutGetEmail) {
  signin::IdentityTestEnvironment identity_test_env;
  PlusAddressService service(identity_test_env.identity_manager());
  EXPECT_EQ(service.GetPrimaryEmail(), absl::nullopt);
}

TEST_F(PlusAddressServiceEnabledTest, SignedInGetEmail) {
  const std::string expected_email = "plus@plus.plus";
  signin::IdentityTestEnvironment identity_test_env;
  identity_test_env.MakeAccountAvailable(expected_email,
                                         {signin::ConsentLevel::kSignin});
  PlusAddressService service(identity_test_env.identity_manager());
  EXPECT_EQ(service.GetPrimaryEmail(), expected_email);
}

// Tests that PlusAddresses is "disabled" in the following states:
// - When a primary account is unset after login.
// - When a primary account's refresh token has an auth error.
//
// If PlusAddressService is "disabled" it should stop offering the feature,
// clear any local storage, and not issue network requests.
class PlusAddressServiceSignoutTest : public ::testing::Test {
 public:
  PlusAddressServiceSignoutTest() {
    secondary_account = identity_test_env_.MakeAccountAvailable(
        "beta@plus.plus", {signin::ConsentLevel::kSignin});
    primary_account = identity_test_env_.MakePrimaryAccountAvailable(
        "alpha@plus.plus", signin::ConsentLevel::kSignin);
  }

  CoreAccountInfo primary_account;
  AccountInfo secondary_account;

  signin::IdentityTestEnvironment* identity_test_env() {
    return &identity_test_env_;
  }

 private:
  base::test::TaskEnvironment task_environment_;
  signin::IdentityTestEnvironment identity_test_env_;
  base::test::ScopedFeatureList scoped_feature_list_{plus_addresses::kFeature};
};

// Doesn't run on ChromeOS since ClearPrimaryAccount() doesn't exist for it.
#if !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(PlusAddressServiceSignoutTest, PrimaryAccountCleared_TogglesIsEnabled) {
  PlusAddressService service(identity_test_env()->identity_manager());
  ASSERT_TRUE(service.is_enabled());

  // Verify behaviors expected when service is enabled.
  url::Origin site = url::Origin::Create(GURL("https://foo.com"));
  service.SavePlusAddress(site, "plus@plus.plus");
  EXPECT_TRUE(service.SupportsPlusAddresses(site));
  EXPECT_TRUE(service.GetPlusAddress(site));
  EXPECT_EQ(service.GetPlusAddress(site).value(), "plus@plus.plus");
  EXPECT_TRUE(service.IsPlusAddress("plus@plus.plus"));

  identity_test_env()->ClearPrimaryAccount();
  EXPECT_FALSE(service.is_enabled());

  // Ensure that the local data is cleared on disabling.
  EXPECT_FALSE(service.SupportsPlusAddresses(site));
  EXPECT_FALSE(service.IsPlusAddress("plus@plus.plus"));
}
#endif  // !BUILDFLAG(IS_CHROMEOS_ASH)

TEST_F(PlusAddressServiceSignoutTest,
       PrimaryRefreshTokenError_TogglesIsEnabled) {
  PlusAddressService service(identity_test_env()->identity_manager());
  ASSERT_TRUE(service.is_enabled());

  // Verify behaviors expected when service is enabled.
  url::Origin site = url::Origin::Create(GURL("https://foo.com"));
  service.SavePlusAddress(site, "plus@plus.plus");
  EXPECT_TRUE(service.SupportsPlusAddresses(site));
  EXPECT_TRUE(service.GetPlusAddress(site));
  EXPECT_EQ(service.GetPlusAddress(site).value(), "plus@plus.plus");
  EXPECT_TRUE(service.IsPlusAddress("plus@plus.plus"));

  // Setting to NONE doesn't disable the service.
  identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount(
      primary_account.account_id,
      GoogleServiceAuthError(GoogleServiceAuthError::NONE));
  EXPECT_TRUE(service.is_enabled());

  // The PlusAddressService isn't disabled for secondary account auth errors.
  identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount(
      secondary_account.account_id,
      GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
  EXPECT_TRUE(service.is_enabled());

  // Being in the "sync-paused" state results in this error.
  identity_test_env()->UpdatePersistentErrorOfRefreshTokenForAccount(
      primary_account.account_id,
      GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
  EXPECT_FALSE(service.is_enabled());

  // Ensure that the local data is cleared on disabling.
  EXPECT_FALSE(service.SupportsPlusAddresses(site));
  EXPECT_FALSE(service.IsPlusAddress("plus@plus.plus"));
}

}  // namespace plus_addresses