File: btm_service_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1315 lines) | stat: -rw-r--r-- 56,067 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
// 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 "content/public/browser/btm_service.h"

#include <optional>
#include <string_view>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/test/test_file_util.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/types/pass_key.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/browser/browser_context_impl.h"
#include "content/browser/btm/btm_bounce_detector.h"
#include "content/browser/btm/btm_service_impl.h"
#include "content/browser/btm/btm_state.h"
#include "content/browser/btm/btm_test_utils.h"
#include "content/browser/btm/btm_utils.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/btm_redirect_info.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/btm_service_test_utils.h"
#include "content/public/test/mock_browsing_data_remover_delegate.h"
#include "content/public/test/test_browser_context.h"
#include "net/base/schemeful_site.h"
#include "net/cookies/cookie_partition_key.h"
#include "net/http/http_status_code.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features_generated.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "url/gurl.h"

using testing::AllOf;
using testing::ElementsAre;
using testing::IsEmpty;
using testing::Pair;

namespace content {

class BtmServiceTest : public testing::Test {
 protected:
  base::PassKey<BtmServiceTest> PassKey() { return {}; }

  void RecordBounce(
      BrowserContext* browser_context,
      std::string_view url,
      std::string_view initial_url,
      std::string_view final_url,
      base::Time time,
      bool stateful,
      base::RepeatingCallback<void(const GURL&)> stateful_bounce_callback) {
    BtmRedirectChainInfo chain(
        MakeUrlAndId(initial_url), MakeUrlAndId(final_url),
        /*length=*/3,
        /*is_partial_chain=*/false,
        btm::Are3PcsGenerallyEnabled(browser_context, nullptr));

    BtmRedirectInfoPtr redirect = BtmRedirectInfo::CreateForServer(
        MakeUrlAndId(url),
        stateful ? BtmDataAccessType::kWrite : BtmDataAccessType::kRead, time,
        /*was_response_cached=*/false,
        /*response_code=*/net::HTTP_FOUND,
        /*server_bounce_delay=*/base::TimeDelta());

    btm::Populate3PcExceptions(browser_context,
                               /*web_contents=*/nullptr, GURL(initial_url),
                               GURL(final_url), base::span_from_ref(redirect));
    redirect->chain_index = 1;
    redirect->chain_id = chain.chain_id;

    BtmServiceImpl::Get(browser_context)
        ->RecordBounceForTesting(*redirect, chain, stateful_bounce_callback);
  }

 private:
  BrowserTaskEnvironment task_environment_;
};

TEST_F(BtmServiceTest, CreateServiceIfFeatureEnabled) {
  ScopedInitBtmFeature init_btm(true);

  TestBrowserContext profile;
  EXPECT_NE(BtmServiceImpl::Get(&profile), nullptr);
}

TEST_F(BtmServiceTest, DontCreateServiceIfFeatureDisabled) {
  ScopedInitBtmFeature init_btm(false);

  TestBrowserContext profile;
  EXPECT_EQ(BtmServiceImpl::Get(&profile), nullptr);
}

// Verifies that if the BTM feature is enabled, BTM database files are created
// when a (non-OTR) profile is created.
TEST_F(BtmServiceTest, CreateDbFilesIfBtmEnabled) {
  base::FilePath data_path = base::CreateUniqueTempDirectoryScopedToTest();
  BtmServiceImpl* service;
  std::unique_ptr<TestBrowserContext> profile;

  // Ensure the BTM feature is enabled.
  base::test::ScopedFeatureList feature_list(features::kBtm);

  profile = std::make_unique<TestBrowserContext>(data_path);
  service = BtmServiceImpl::Get(profile.get());
  ASSERT_NE(service, nullptr);

  // Ensure the database files have been created since the BTM feature is
  // enabled.
  WaitOnStorage(service);
  BrowserContextImpl::From(profile.get())->WaitForBtmCleanupForTesting();
  EXPECT_TRUE(base::PathExists(GetBtmFilePath(profile.get())));
}

// Verifies that when an OTR profile is opened, the BTM database file for
// the underlying regular profile is NOT deleted.
TEST_F(BtmServiceTest, PreserveRegularProfileDbFiles) {
  base::FilePath data_path = base::CreateUniqueTempDirectoryScopedToTest();

  // Ensure the BTM feature is enabled.
  base::test::ScopedFeatureList feature_list(features::kBtm);

  // Build a regular profile.
  std::unique_ptr<TestBrowserContext> profile =
      std::make_unique<TestBrowserContext>(data_path);
  BtmServiceImpl* service = BtmServiceImpl::Get(profile.get());
  ASSERT_NE(service, nullptr);

  // Ensure the regular profile's database files have been created since the
  // BTM feature is enabled.
  WaitOnStorage(service);
  BrowserContextImpl::From(profile.get())->WaitForBtmCleanupForTesting();
  ASSERT_TRUE(base::PathExists(GetBtmFilePath(profile.get())));

  // Build an off-the-record profile based on `profile`.
  std::unique_ptr<TestBrowserContext> otr_profile =
      std::make_unique<TestBrowserContext>(profile->GetPath());
  otr_profile->set_is_off_the_record(true);
  BtmServiceImpl* otr_service = BtmServiceImpl::Get(otr_profile.get());
  ASSERT_NE(otr_service, nullptr);

  // Ensure the OTR profile's database has been initialized and any file
  // deletion tasks have finished (although there shouldn't be any).
  WaitOnStorage(otr_service);
  BrowserContextImpl::From(otr_profile.get())->WaitForBtmCleanupForTesting();

  // Ensure the regular profile's database files were NOT deleted.
  EXPECT_TRUE(base::PathExists(GetBtmFilePath(profile.get())));

  // Every TestBrowserContext normally deletes its folder when it's destroyed.
  // But since `otr_profile` is sharing `profile`'s directory, we don't want it
  // to delete that folder (`profile` will).
  otr_profile->TakePath();
}

TEST_F(BtmServiceTest, DatabaseFileIsDeletedIfFeatureIsDisabled) {
  base::FilePath user_data_dir;
  base::FilePath db_path;

  // First, create a browser context while BTM is enabled, and confirm a
  // database file is created.
  {
    TestBrowserContext browser_context;
    db_path = GetBtmFilePath(&browser_context);
    // Wait for the database to be created.
    BrowserContextImpl::From(&browser_context)
        ->GetBtmService()
        ->storage()
        ->FlushPostedTasksForTesting();
    ASSERT_TRUE(base::PathExists(db_path));

    // Take ownership of the browser context's directory so we can reuse it.
    user_data_dir = browser_context.TakePath();

    // Confirm that WaitForBtmCleanupForTesting() returns even if the file is
    // not deleted.
    BrowserContextImpl::From(&browser_context)->WaitForBtmCleanupForTesting();
    ASSERT_TRUE(base::PathExists(db_path));
  }

  // Confirm the file still exists after the browser context is destroyed.
  ASSERT_TRUE(base::PathExists(db_path));

  // Create another browser context for the same directory, while BTM is
  // disabled. Confirm the database file is deleted.
  {
    ScopedInitBtmFeature disable_btm(false);
    TestBrowserContext browser_context(user_data_dir);
    ASSERT_FALSE(BrowserContextImpl::From(&browser_context)->GetBtmService());
    BrowserContextImpl::From(&browser_context)->WaitForBtmCleanupForTesting();
    ASSERT_FALSE(base::PathExists(db_path));
  }
}

TEST_F(BtmServiceTest, EmptySiteEventsIgnored) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeature(features::kBtm);
  std::unique_ptr<TestBrowserContext> profile =
      std::make_unique<TestBrowserContext>();
  BtmServiceImpl* service = BtmServiceImpl::Get(profile.get());

  // Record a bounce for an empty URL.
  GURL url;
  base::Time bounce = base::Time::FromSecondsSinceUnixEpoch(2);
  RecordBounce(profile.get(), url.spec(), "https://initial.com",
               "https://final.com", bounce, false,
               base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(service);

  // Verify that an entry is not returned when querying for an empty URL,
  StateForURLCallback callback = base::BindLambdaForTesting(
      [&](BtmState state) { EXPECT_FALSE(state.was_loaded()); });
  service->storage()
      ->AsyncCall(&BtmStorage::Read)
      .WithArgs(url)
      .Then(std::move(callback));
  WaitOnStorage(service);
}

class BtmServiceStateRemovalTest : public testing::Test {
 public:
  BtmServiceStateRemovalTest()
      : profile_(std::make_unique<TestBrowserContext>()),
        service_(BtmServiceImpl::Get(GetProfile())) {
    SetBrowserClientForTesting(&browser_client_);
  }

  base::TimeDelta grace_period;
  base::TimeDelta interaction_ttl;
  base::TimeDelta tiny_delta = base::Milliseconds(1);

  BrowserContext* GetProfile() { return profile_.get(); }
  BtmServiceImpl* GetService() { return service_; }

 protected:
  TpcBlockingBrowserClient browser_client_;
  BrowserTaskEnvironment task_environment_;
  MockBrowsingDataRemoverDelegate delegate_;

  // Test setup.
  void SetUp() override {
    grace_period = features::kBtmGracePeriod.Get();
    interaction_ttl = features::kBtmInteractionTtl.Get();
    ASSERT_LT(tiny_delta, grace_period);

    GetProfile()->GetBrowsingDataRemover()->SetEmbedderDelegate(&delegate_);
    browser_client_.SetBlockThirdPartyCookiesByDefault(true);
    ASSERT_FALSE(Are3PcsGenerallyEnabled());

    DCHECK(service_);
    service_->SetStorageClockForTesting(&clock_);
    WaitOnStorage(GetService());
  }

  void TearDown() override {
    profile_.reset();
    base::RunLoop().RunUntilIdle();
  }

  void AdvanceTimeTo(base::Time now) {
    ASSERT_GE(now, clock_.Now());
    clock_.SetNow(now);
  }

  base::Time Now() { return clock_.Now(); }
  void SetNow(base::Time now) { clock_.SetNow(now); }

  void AdvanceTimeBy(base::TimeDelta delta) { clock_.Advance(delta); }

  void FireBtmTimer() {
    service_->OnTimerFiredForTesting();
    WaitOnStorage(GetService());
  }

  // Add an exception to the third-party cookie blocking rule for
  // |third_party_url| embedded by |first_party_url|.
  void Add3PCException(const GURL& first_party_url,
                       const GURL& third_party_url) {
    browser_client_.GrantCookieAccessDueToHeuristic(
        profile_.get(), net::SchemefulSite(first_party_url),
        net::SchemefulSite(third_party_url), base::Days(1),
        /*ignore_schemes=*/false);

    auto* client = GetContentClientForTesting()->browser();
    EXPECT_TRUE(client->IsFullCookieAccessAllowed(
        profile_.get(), nullptr, third_party_url,
        blink::StorageKey::CreateFirstParty(
            url::Origin::Create(first_party_url)),
        /*overrides=*/{}));
    EXPECT_FALSE(client->IsFullCookieAccessAllowed(
        profile_.get(), nullptr, first_party_url,
        blink::StorageKey::CreateFirstParty(
            url::Origin::Create(third_party_url)),
        /*overrides=*/{}));
  }

  void RecordBounce(
      std::string_view url,
      std::string_view initial_url,
      std::string_view final_url,
      base::Time time,
      bool stateful,
      base::RepeatingCallback<void(const GURL&)> stateful_bounce_callback) {
    BtmRedirectChainInfo chain(
        MakeUrlAndId(initial_url), MakeUrlAndId(final_url),
        /*length=*/3,
        /*is_partial_chain=*/false, Are3PcsGenerallyEnabled());

    BtmRedirectInfoPtr redirect = BtmRedirectInfo::CreateForServer(
        MakeUrlAndId(url),
        stateful ? BtmDataAccessType::kWrite : BtmDataAccessType::kRead, time,
        /*was_response_cached=*/false,
        /*response_code=*/net::HTTP_FOUND,
        /*server_bounce_delay=*/base::TimeDelta());

    btm::Populate3PcExceptions(GetProfile(),
                               /*web_contents=*/nullptr, GURL(initial_url),
                               GURL(final_url), base::span_from_ref(redirect));
    redirect->chain_index = 1;
    redirect->chain_id = chain.chain_id;

    GetService()->RecordBounceForTesting(*redirect, chain,
                                         stateful_bounce_callback);
  }

  bool Are3PcsGenerallyEnabled() {
    return btm::Are3PcsGenerallyEnabled(profile_.get(), nullptr);
  }

 private:
  base::SimpleTestClock clock_;

  std::unique_ptr<TestBrowserContext> profile_;
  raw_ptr<BtmServiceImpl, DanglingUntriaged> service_ = nullptr;
};

namespace {
class RedirectChainCounter : public BtmService::Observer {
 public:
  explicit RedirectChainCounter(BtmService* service) { obs_.Observe(service); }

  size_t count() const { return count_; }

 private:
  void OnChainHandled(const std::vector<BtmRedirectInfoPtr>& redirects,
                      const BtmRedirectChainInfoPtr& chain) override {
    count_++;
  }

  size_t count_ = 0;
  base::ScopedObservation<BtmService, Observer> obs_{this};
};
}  // namespace

TEST_F(BtmServiceStateRemovalTest,
       CompleteChain_NotifiesBtmRedirectChainObservers) {
  GetService()->SetStorageClockForTesting(base::DefaultClock::GetInstance());
  RedirectChainCounter chain_counter(GetService());

  std::vector<BtmRedirectInfoPtr> complete_redirects;
  complete_redirects.push_back(BtmRedirectInfo::CreateForServer(
      /*url=*/MakeUrlAndId("http://b.test/"),
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  auto complete_chain = std::make_unique<BtmRedirectChainInfo>(
      /*initial_url=*/MakeUrlAndId("http://a.test/"),
      /*final_url=*/MakeUrlAndId("http://c.test/"),
      /*length=*/1, /*is_partial_chain=*/false, Are3PcsGenerallyEnabled());

  btm::Populate3PcExceptions(GetProfile(), /*web_contents=*/nullptr,
                             complete_chain->initial_url.url,
                             complete_chain->final_url.url, complete_redirects);
  GetService()->HandleRedirectChain(
      std::move(complete_redirects), std::move(complete_chain),
      base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());
  // Expect one call to Observer.OnChainHandled when handling a complete chain.
  EXPECT_EQ(chain_counter.count(), 1u);
}

TEST_F(BtmServiceStateRemovalTest,
       PartialChain_DoesNotNotifyBtmRedirectChainObservers) {
  GetService()->SetStorageClockForTesting(base::DefaultClock::GetInstance());
  RedirectChainCounter chain_counter(GetService());

  std::vector<BtmRedirectInfoPtr> partial_redirects;
  partial_redirects.push_back(BtmRedirectInfo::CreateForServer(
      /*url=*/MakeUrlAndId("http://b.test/"),
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  auto partial_chain = std::make_unique<BtmRedirectChainInfo>(
      /*initial_url=*/MakeUrlAndId("http://a.test/"),
      /*final_url=*/MakeUrlAndId("http://c.test/"),
      /*length=*/1, /*is_partial_chain=*/true, Are3PcsGenerallyEnabled());

  btm::Populate3PcExceptions(GetProfile(), /*web_contents=*/nullptr,
                             partial_chain->initial_url.url,
                             partial_chain->final_url.url, partial_redirects);
  GetService()->HandleRedirectChain(
      std::move(partial_redirects), std::move(partial_chain),
      base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());
  // Expect no calls to Observer.OnChainHandled when handling a partial chain.
  EXPECT_EQ(chain_counter.count(), 0u);
}

// NOTE: The use of a MockBrowsingDataRemoverDelegate in this test fixture
// means that when BTM deletion is enabled, the row for 'url' is not actually
// removed from the BTM db since 'delegate_' doesn't actually carryout the
// removal task.
TEST_F(BtmServiceStateRemovalTest, DISABLED_BrowsingDataDeletion_Enabled) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "bounce"}});

  // Record a bounce.
  GURL url("https://example.com");
  base::Time bounce = base::Time::FromSecondsSinceUnixEpoch(2);
  RecordBounce(url.spec(), "https://initial.com", "https://final.com", bounce,
               false, base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());
  EXPECT_TRUE(GetBtmState(GetService(), url).has_value());

  // Set the current time to just after the bounce happened.
  AdvanceTimeTo(bounce + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify a removal task was not posted to the BrowsingDataRemover(Delegate).
  delegate_.VerifyAndClearExpectations();

  auto filter_builder = BrowsingDataFilterBuilder::Create(
      BrowsingDataFilterBuilder::Mode::kDelete);
  filter_builder->AddRegisterableDomain(GetSiteForBtm(url));
  filter_builder->SetCookiePartitionKeyCollection(
      net::CookiePartitionKeyCollection());
  delegate_.ExpectCall(
      base::Time::Min(), base::Time::Max(),
      (ContentBrowserClient::kDefaultBtmRemoveMask &
       ~BrowsingDataRemover::DATA_TYPE_PRIVACY_SANDBOX) |
          BrowsingDataRemover::DATA_TYPE_AVOID_CLOSING_CONNECTIONS,
      BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB |
          BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB,
      filter_builder.get());
  // We don't test the filter builder for partitioned cookies here because it's
  // messy. The browser tests ensure that it behaves as expected.
  delegate_.ExpectCallDontCareAboutFilterBuilder(
      base::Time::Min(), base::Time::Max(),
      BrowsingDataRemover::DATA_TYPE_COOKIES,
      BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB |
          BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB);

  // Time-travel to after the grace period has ended for the bounce.
  AdvanceTimeTo(bounce + grace_period + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify that a removal task was posted to the BrowsingDataRemover(Delegate)
  // for 'url'.
  delegate_.VerifyAndClearExpectations();
  // Because this test fixture uses a MockBrowsingDataRemoverDelegate the BTM
  // entry should not actually be removed. However, in practice it would be.
  EXPECT_TRUE(GetBtmState(GetService(), url).has_value());

  EXPECT_THAT(ukm_recorder,
              EntryUrlsAre("DIPS.Deletion", {"http://example.com/"}));
}

TEST_F(BtmServiceStateRemovalTest,
       BrowsingDataDeletion_Respects3PExceptionsFor3PC) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "bounce"}});

  GURL excepted_3p_url("https://excepted-as-3p.com");
  GURL non_excepted_url("https://not-excepted.com");

  browser_client_.GrantCookieAccessTo3pSite(excepted_3p_url);

  int stateful_bounce_count = 0;
  base::RepeatingCallback<void(const GURL&)> increment_bounce =
      base::BindLambdaForTesting(
          [&](const GURL& final_url) { stateful_bounce_count++; });

  // Bounce through both tracking sites.
  base::Time bounce = base::Time::FromSecondsSinceUnixEpoch(2);
  RecordBounce(excepted_3p_url.spec(), "https://initial.com",
               "https://final.com", bounce, true, increment_bounce);
  RecordBounce(non_excepted_url.spec(), "https://initial.com",
               "https://final.com", bounce, true, increment_bounce);
  WaitOnStorage(GetService());

  // Verify that the bounce was not recorded for the excepted 3P URL.
  EXPECT_FALSE(GetBtmState(GetService(), excepted_3p_url).has_value());
  EXPECT_TRUE(GetBtmState(GetService(), non_excepted_url).has_value());

  // Time-travel to after the grace period has ended for the bounce.
  AdvanceTimeTo(bounce + grace_period + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Only the non-excepted site should be reported to UKM.
  EXPECT_THAT(ukm_recorder,
              EntryUrlsAre("DIPS.Deletion", {"http://not-excepted.com/"}));

  // Expect one recorded bounce, for the stateful redirect through the
  // non-excepted site.
  EXPECT_EQ(stateful_bounce_count, 1);
}

TEST_F(BtmServiceStateRemovalTest,
       BrowsingDataDeletion_Respects1PExceptionsFor3PC) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "bounce"}});

  GURL excepted_1p_url("https://excepted-as-1p.com");
  GURL scoped_excepted_1p_url("https://excepted-as-1p-with-3p.com");
  GURL non_excepted_url("https://not-excepted.com");
  GURL redirect_url_1("https://redirect-1.com");
  GURL redirect_url_2("https://redirect-2.com");
  GURL redirect_url_3("https://redirect-3.com");

  browser_client_.AllowThirdPartyCookiesOnSite(excepted_1p_url);
  Add3PCException(scoped_excepted_1p_url, redirect_url_1);

  int stateful_bounce_count = 0;
  base::RepeatingCallback<void(const GURL&)> increment_bounce =
      base::BindLambdaForTesting(
          [&](const GURL& final_url) { stateful_bounce_count++; });

  base::Time bounce = base::Time::FromSecondsSinceUnixEpoch(2);
  // Record a bounce through redirect_url_1 that starts on an excepted
  // URL.
  RecordBounce(redirect_url_1.spec(), excepted_1p_url.spec(),
               non_excepted_url.spec(), bounce, true, increment_bounce);
  // Record a bounce through redirect_url_1 that ends on an excepted
  // URL.
  RecordBounce(redirect_url_1.spec(), non_excepted_url.spec(),
               excepted_1p_url.spec(), bounce, true, increment_bounce);
  // Record a bounce through redirect_url_1 that ends on a URL with an exception
  // scoped to redirect_url_1.
  RecordBounce(redirect_url_1.spec(), non_excepted_url.spec(),
               scoped_excepted_1p_url.spec(), bounce, true, increment_bounce);
  // Record a bounce through redirect_url_2 that does not start or
  // end on an excepted URL.
  RecordBounce(redirect_url_2.spec(), non_excepted_url.spec(),
               non_excepted_url.spec(), bounce, true, increment_bounce);
  // Record a bounce through redirect_url_3 that does not start or
  // end on an excepted URL. Record an interaction on this URL as well.
  RecordBounce(redirect_url_3.spec(), non_excepted_url.spec(),
               non_excepted_url.spec(), bounce, true, increment_bounce);
  GetService()
      ->storage()
      ->AsyncCall(&BtmStorage::RecordUserActivation)
      .WithArgs(redirect_url_3, bounce, GetService()->GetCookieMode());
  WaitOnStorage(GetService());

  // Expect no recorded BtmState for redirect_url_1, since every
  // recorded bounce started or ended on an excepted site.
  EXPECT_FALSE(GetBtmState(GetService(), redirect_url_1).has_value());
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_2).has_value());
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_3).has_value());

  // Record a bounce through redirect_url_2 that starts on an
  // excepted URL. This should clear the DB entry for redirect_url_2.
  RecordBounce(redirect_url_2.spec(), excepted_1p_url.spec(),
               non_excepted_url.spec(), bounce, true, increment_bounce);
  EXPECT_FALSE(GetBtmState(GetService(), redirect_url_2).has_value());

  // Record a bounce through redirect_url_3 that starts on an
  // excepted URL. This should not clear the DB entry for redirect_url_3 as it
  // has a recorded interaction.
  RecordBounce(redirect_url_3.spec(), excepted_1p_url.spec(),
               non_excepted_url.spec(), bounce, true, increment_bounce);
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_3).has_value());

  // Expect two non-excepted stateful redirects: the first bounces through
  // redirect_url_2 and redirect_url_3.
  EXPECT_EQ(stateful_bounce_count, 2);
}

// TODO: crbug.com/376625002 - temporarily disabled for the move to //content,
// where there's no HostContentSettingsMap. Find an appropriate way to implement
// this test in //content or move it back to //chrome.
TEST_F(BtmServiceStateRemovalTest,
       DISABLED_BrowsingDataDeletion_RespectsStorageAccessGrantExceptions) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  std::vector<base::test::FeatureRefAndParams> enabled_features;
  enabled_features.push_back(
      {features::kBtm, {{"triggering_action", "bounce"}}});
  base::test::ScopedFeatureList feature_list;
  feature_list.InitWithFeaturesAndParameters(enabled_features, {});

  GURL storage_access_grant_url("https://storage-access-granted.com");
  GURL top_level_storage_access_grant_url(
      "https://top-level-storage-access-granted.com");
  GURL no_grant_url("https://no-storage-access-grant.com");
  GURL redirect_url_1("https://redirect-1.com");
  GURL redirect_url_2("https://redirect-2.com");
  GURL redirect_url_3("https://redirect-3.com");

  // Create Storage Access grants for the required sites.
  /*
  HostContentSettingsMap* map =
      HostContentSettingsMapFactory::GetForProfile(GetProfile());
  map->SetContentSettingCustomScope(
      ContentSettingsPattern::Wildcard(),
      ContentSettingsPattern::FromString("[*.]" +
                                         storage_access_grant_url.host()),
      ContentSettingsType::STORAGE_ACCESS, CONTENT_SETTING_ALLOW);
  map->SetContentSettingCustomScope(
      ContentSettingsPattern::Wildcard(),
      ContentSettingsPattern::FromString(
          "[*.]" + top_level_storage_access_grant_url.host()),
      ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS, CONTENT_SETTING_ALLOW);
  */
  int stateful_bounce_count = 0;
  base::RepeatingCallback<void(const GURL&)> increment_bounce =
      base::BindLambdaForTesting(
          [&](const GURL& final_url) { stateful_bounce_count++; });

  base::Time bounce = base::Time::FromSecondsSinceUnixEpoch(2);
  // Record a bounce through redirect_url_1 that starts on a URL with an SA
  // grant.
  RecordBounce(redirect_url_1.spec(), storage_access_grant_url.spec(),
               no_grant_url.spec(), bounce, true, increment_bounce);
  // Record a bounce through redirect_url_1 that ends on a URL with a top-level
  // SA grant.
  RecordBounce(redirect_url_1.spec(), no_grant_url.spec(),
               top_level_storage_access_grant_url.spec(), bounce, true,
               increment_bounce);
  // Record a bounce through redirect_url_2 that does not start or
  // end on a URL with an SA grant.
  RecordBounce(redirect_url_2.spec(), no_grant_url.spec(), no_grant_url.spec(),
               bounce, true, increment_bounce);
  // Record a bounce through redirect_url_3 that does not start or
  // end on a URL with an SA grant. Record an interaction on this URL as well.
  RecordBounce(redirect_url_3.spec(), no_grant_url.spec(), no_grant_url.spec(),
               bounce, true, increment_bounce);
  GetService()
      ->storage()
      ->AsyncCall(&BtmStorage::RecordUserActivation)
      .WithArgs(redirect_url_3, bounce, GetService()->GetCookieMode());
  WaitOnStorage(GetService());

  // Expect no recorded BtmState for redirect_url_1, since every
  // recorded bounce started or ended on a site with an SA grant.
  EXPECT_FALSE(GetBtmState(GetService(), redirect_url_1).has_value());
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_2).has_value());
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_3).has_value());

  // Record a bounce through redirect_url_2 that starts on a URL with an SA
  // grant. This should clear the DB entry for redirect_url_2.
  RecordBounce(redirect_url_2.spec(), storage_access_grant_url.spec(),
               no_grant_url.spec(), bounce, true, increment_bounce);
  EXPECT_FALSE(GetBtmState(GetService(), redirect_url_2).has_value());

  // Record a bounce through redirect_url_3 that starts on a URL with an SA
  // grant. This should not clear the DB entry for redirect_url_3 as it has a
  // recorded interaction.
  RecordBounce(redirect_url_3.spec(), storage_access_grant_url.spec(),
               no_grant_url.spec(), bounce, true, increment_bounce);
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_3).has_value());

  // Expect two non-SA stateful redirects: the first bounces through
  // redirect_url_2 and redirect_url_3.
  EXPECT_EQ(stateful_bounce_count, 2);
}

// When third-party cookies are globally allowed, bounces should be recorded for
// sites which have an exception to block 3PC, but not by default.
TEST_F(
    BtmServiceStateRemovalTest,
    BrowsingDataDeletion_Respects1PExceptionsForBlocking3PCWhenDefaultAllowed) {
  browser_client_.SetBlockThirdPartyCookiesByDefault(false);
  ASSERT_TRUE(Are3PcsGenerallyEnabled());

  ukm::TestAutoSetUkmRecorder ukm_recorder;
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "bounce"}});

  GURL blocked_1p_url("https://excepted-as-1p.com");
  GURL scoped_blocked_1p_url("https://excepted-as-1p-with-3p.com");
  GURL non_blocked_url("https://not-excepted.com");
  GURL redirect_url_1("https://redirect-1.com");
  GURL redirect_url_2("https://redirect-2.com");
  GURL redirect_url_3("https://redirect-3.com");
  GURL redirect_url_4("https://redirect-4.com");

  // Exceptions to block third-party cookies.
  browser_client_.BlockThirdPartyCookiesOnSite(blocked_1p_url);
  browser_client_.BlockThirdPartyCookies(redirect_url_1, scoped_blocked_1p_url);

  int stateful_bounce_count = 0;
  base::RepeatingCallback<void(const GURL&)> increment_bounce =
      base::BindLambdaForTesting(
          [&](const GURL& final_url) { stateful_bounce_count++; });

  base::Time bounce = base::Time::FromSecondsSinceUnixEpoch(2);
  // Record a bounce through redirect_url_1 that starts and ends on blocked
  // URLs.
  RecordBounce(redirect_url_1.spec(), blocked_1p_url.spec(),
               scoped_blocked_1p_url.spec(), bounce, true, increment_bounce);
  // Record a bounce through redirect_url_2 that starts and ends on blocked
  // URLs. Record an interaction on this URL as well.
  RecordBounce(redirect_url_2.spec(), blocked_1p_url.spec(),
               blocked_1p_url.spec(), bounce, true, increment_bounce);
  GetService()
      ->storage()
      ->AsyncCall(&BtmStorage::RecordUserActivation)
      .WithArgs(redirect_url_2, bounce, GetService()->GetCookieMode());
  WaitOnStorage(GetService());
  // Record a bounce through redirect_url_3 that starts on a non-blocked URL.
  RecordBounce(redirect_url_3.spec(), non_blocked_url.spec(),
               blocked_1p_url.spec(), bounce, true, increment_bounce);
  // Record a bounce through redirect_url_4 that ends on a non-blocked URL.
  RecordBounce(redirect_url_4.spec(), blocked_1p_url.spec(),
               non_blocked_url.spec(), bounce, true, increment_bounce);

  // Expect a recorded BtmState for redirect_url_1 and redirect_url_2, since
  // they were bounced through with blocking exceptions on both the initial and
  // final URL. The other two trackers were only bounced through from
  // default-allowed sites.
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_1).has_value());
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_2).has_value());
  EXPECT_FALSE(GetBtmState(GetService(), redirect_url_3).has_value());
  EXPECT_FALSE(GetBtmState(GetService(), redirect_url_4).has_value());

  // Record a bounce through redirect_url_1 that starts on a non-blocked URL.
  // This should clear the DB entry for redirect_url_1.
  RecordBounce(redirect_url_1.spec(), non_blocked_url.spec(),
               blocked_1p_url.spec(), bounce, true, increment_bounce);
  EXPECT_FALSE(GetBtmState(GetService(), redirect_url_1).has_value());

  // Record a bounce through redirect_url_2 that starts on a
  // blocked URL. This should not clear the DB entry for redirect_url_2 as it
  // has a recorded interaction.
  RecordBounce(redirect_url_2.spec(), non_blocked_url.spec(),
               blocked_1p_url.spec(), bounce, true, increment_bounce);
  EXPECT_TRUE(GetBtmState(GetService(), redirect_url_2).has_value());

  // Expect two recorded stateful redirects: the first bounces through
  // redirect_url_1 and redirect_url_2.
  EXPECT_EQ(stateful_bounce_count, 2);
}

TEST_F(BtmServiceStateRemovalTest, ImmediateEnforcement) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "bounce"}});
  SetNow(base::Time::FromSecondsSinceUnixEpoch(2));
  ASSERT_FALSE(Are3PcsGenerallyEnabled());

  // Record a bounce.
  GURL url("https://example.com");
  base::Time bounce = Now();
  RecordBounce(url.spec(), "https://initial.com", "https://final.com", bounce,
               false, base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());
  EXPECT_TRUE(GetBtmState(GetService(), url).has_value());

  // Set the current time to just after the bounce happened and simulate firing
  // the BTM timer.
  AdvanceTimeTo(bounce + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify a removal task was not posted to the BrowsingDataRemover(Delegate).
  delegate_.VerifyAndClearExpectations();

  auto filter_builder = BrowsingDataFilterBuilder::Create(
      BrowsingDataFilterBuilder::Mode::kDelete);
  filter_builder->AddRegisterableDomain(GetSiteForBtm(url));
  filter_builder->SetCookiePartitionKeyCollection(
      net::CookiePartitionKeyCollection());
  delegate_.ExpectCall(
      base::Time::Min(), base::Time::Max(),
      (ContentBrowserClient::kDefaultBtmRemoveMask &
       ~BrowsingDataRemover::DATA_TYPE_PRIVACY_SANDBOX) |
          BrowsingDataRemover::DATA_TYPE_AVOID_CLOSING_CONNECTIONS,
      BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB |
          BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB,
      filter_builder.get());
  // We don't test the filter builder for partitioned cookies here because it's
  // messy. The browser tests ensure that it behaves as expected.
  delegate_.ExpectCallDontCareAboutFilterBuilder(
      base::Time::Min(), base::Time::Max(),
      BrowsingDataRemover::DATA_TYPE_COOKIES,
      BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB |
          BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB);

  // Perform immediate enforcement of deletion, without regard for grace period
  // and verify `url` is returned the `DeletedSitesCallback`.
  base::RunLoop run_loop;
  base::OnceCallback<void(const std::vector<std::string>& sites)> callback =
      base::BindLambdaForTesting(
          [&](const std::vector<std::string>& deleted_sites) {
            EXPECT_THAT(deleted_sites,
                        testing::UnorderedElementsAre(GetSiteForBtm(url)));
            run_loop.Quit();
          });
  GetService()->DeleteEligibleSitesImmediately(std::move(callback));
  task_environment_.RunUntilIdle();
  run_loop.Run();

  // Verify that a removal task was posted to the BrowsingDataRemover(Delegate)
  // for 'url'.
  delegate_.VerifyAndClearExpectations();
}

// A test class that verifies BtmService state deletion metrics collection
// behavior.
class BtmServiceHistogramTest : public BtmServiceStateRemovalTest {
 public:
  BtmServiceHistogramTest() = default;

  const base::HistogramTester& histograms() const { return histogram_tester_; }

 protected:
  const std::string kBlock3PC = "Block3PC";
  const std::string kUmaHistogramDeletionPrefix = "Privacy.DIPS.Deletion.";
  const std::string kServerRedirectsDelayHist =
      "Privacy.DIPS.ServerBounceDelay";
  const std::string kServerRedirectsChainDelayHist =
      "Privacy.DIPS.ServerBounceChainDelay";
  const std::string kServerRedirectsStatusCodePrefix =
      "Privacy.DIPS.BounceStatusCode.";
  const std::string kNoCache = "NoCache";
  const std::string kCached = "Cached";

  base::HistogramTester histogram_tester_;
};

TEST_F(BtmServiceHistogramTest, DeletionLatency) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "bounce"}});

  // Verify the histogram starts empty
  histograms().ExpectTotalCount("Privacy.DIPS.DeletionLatency2", 0);

  // Record a bounce.
  GURL url("https://example.com");
  base::Time bounce = base::Time::FromSecondsSinceUnixEpoch(2);
  RecordBounce(url.spec(), "https://initial.com", "https://final.com", bounce,
               false, base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());

  // Set the current time to just after the bounce happened.
  AdvanceTimeTo(bounce + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify deletion latency metrics were NOT emitted and the BTM entry was NOT
  // removed.
  histograms().ExpectTotalCount("Privacy.DIPS.DeletionLatency2", 0);
  EXPECT_TRUE(GetBtmState(GetService(), url).has_value());

  // Time-travel to after the grace period has ended for the bounce.
  AdvanceTimeTo(bounce + grace_period + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify a deletion latency metric was emitted and the BTM entry was
  // removed.
  histograms().ExpectTotalCount("Privacy.DIPS.DeletionLatency2", 1);
  EXPECT_FALSE(GetBtmState(GetService(), url).has_value());
}

TEST_F(BtmServiceHistogramTest, Deletion_ExceptedAs1P) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "stateful_bounce"}});

  // Verify the histogram is initially empty.
  EXPECT_TRUE(histograms()
                  .GetTotalCountsForPrefix(kUmaHistogramDeletionPrefix)
                  .empty());

  // Record a bounce.
  GURL url("https://example.com");
  GURL excepted_1p_url("https://initial.com");
  browser_client_.AllowThirdPartyCookiesOnSite(excepted_1p_url);
  base::Time bounce_time = base::Time::FromSecondsSinceUnixEpoch(2);
  RecordBounce(url.spec(), excepted_1p_url.spec(), "https://final.com",
               bounce_time, true,
               base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());

  // Time-travel to after the grace period has ended for the bounce.
  AdvanceTimeTo(bounce_time + grace_period + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify a deletion metric was emitted and the BTM entry was removed.
  base::HistogramTester::CountsMap expected_counts;
  expected_counts[kUmaHistogramDeletionPrefix + kBlock3PC] = 1;
  EXPECT_THAT(histograms().GetTotalCountsForPrefix(kUmaHistogramDeletionPrefix),
              testing::ContainerEq(expected_counts));
  histograms().ExpectUniqueSample(kUmaHistogramDeletionPrefix + kBlock3PC,
                                  BtmDeletionAction::kExcepted, 1);
  EXPECT_FALSE(GetBtmState(GetService(), url).has_value());
}

TEST_F(BtmServiceHistogramTest, Deletion_ExceptedAs3P) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "stateful_bounce"}});

  // Verify the histogram is initially empty.
  EXPECT_TRUE(histograms()
                  .GetTotalCountsForPrefix(kUmaHistogramDeletionPrefix)
                  .empty());

  // Record a bounce.
  GURL excepted_3p_url("https://example.com");
  browser_client_.GrantCookieAccessTo3pSite(excepted_3p_url);
  base::Time bounce_time = base::Time::FromSecondsSinceUnixEpoch(2);
  RecordBounce(excepted_3p_url.spec(), "https://initial.com",
               "https://final.com", bounce_time, true,
               base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());

  // Time-travel to after the grace period has ended for the bounce.
  AdvanceTimeTo(bounce_time + grace_period + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify a deletion metric was emitted and the BTM entry was removed.
  base::HistogramTester::CountsMap expected_counts;
  expected_counts[kUmaHistogramDeletionPrefix + kBlock3PC] = 1;
  EXPECT_THAT(histograms().GetTotalCountsForPrefix(kUmaHistogramDeletionPrefix),
              testing::ContainerEq(expected_counts));
  histograms().ExpectUniqueSample(kUmaHistogramDeletionPrefix + kBlock3PC,
                                  BtmDeletionAction::kExcepted, 1);
  EXPECT_FALSE(GetBtmState(GetService(), excepted_3p_url).has_value());
}

TEST_F(BtmServiceHistogramTest, DISABLED_Deletion_Enforced) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "stateful_bounce"}});

  // Verify the histogram is initially empty.
  EXPECT_TRUE(histograms()
                  .GetTotalCountsForPrefix(kUmaHistogramDeletionPrefix)
                  .empty());

  // Record a bounce.
  GURL url("https://example.com");
  base::Time bounce_time = base::Time::FromSecondsSinceUnixEpoch(2);
  RecordBounce(url.spec(), "https://initial.com", "https://final.com",
               bounce_time, true,
               base::BindRepeating([](const GURL& final_url) {}));
  WaitOnStorage(GetService());

  // Time-travel to after the grace period has ended for the bounce.
  AdvanceTimeTo(bounce_time + grace_period + tiny_delta);
  FireBtmTimer();
  task_environment_.RunUntilIdle();

  // Verify a deletion metric was emitted and the BTM entry was not removed.
  base::HistogramTester::CountsMap expected_counts;
  expected_counts[kUmaHistogramDeletionPrefix + kBlock3PC] = 1;
  EXPECT_THAT(histograms().GetTotalCountsForPrefix(kUmaHistogramDeletionPrefix),
              testing::ContainerEq(expected_counts));
  histograms().ExpectUniqueSample(kUmaHistogramDeletionPrefix + kBlock3PC,
                                  BtmDeletionAction::kEnforced, 1);
  EXPECT_TRUE(GetBtmState(GetService(), url).has_value());
}

TEST_F(BtmServiceHistogramTest, ServerBounceDelay) {
  base::test::ScopedFeatureList feature_list;
  feature_list.InitAndEnableFeatureWithParameters(
      features::kBtm, {{"triggering_action", "bounce"}});

  // Verify that the histograms start empty.
  histograms().ExpectTotalCount(kServerRedirectsDelayHist, 0);
  histograms().ExpectTotalCount(kServerRedirectsChainDelayHist, 0);
  EXPECT_TRUE(histograms()
                  .GetTotalCountsForPrefix(kServerRedirectsStatusCodePrefix)
                  .empty());

  TestBrowserContext profile;
  BtmServiceImpl* service = BtmServiceImpl::Get(&profile);

  UrlAndSourceId initial_url = MakeUrlAndId("http://a.test/");
  UrlAndSourceId first_redirect_url = MakeUrlAndId("http://b.test/");
  UrlAndSourceId second_redirect_url = MakeUrlAndId("http://c.test/");

  BtmRedirectChainObserver observer(service, GURL());
  std::vector<BtmRedirectInfoPtr> redirects;
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      first_redirect_url,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/true,
      /*response_code=*/net::HTTP_MOVED_PERMANENTLY,
      /*server_bounce_delay=*/base::Milliseconds(100)));
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      second_redirect_url,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::Milliseconds(100)));
  BtmRedirectChainInfoPtr chain = std::make_unique<BtmRedirectChainInfo>(
      initial_url, UrlAndSourceId(), redirects.size(),
      /*is_partial_chain=*/false, Are3PcsGenerallyEnabled());
  btm::Populate3PcExceptions(&profile, /*web_contents=*/nullptr,
                             chain->initial_url.url, chain->final_url.url,
                             redirects);
  service->HandleRedirectChain(std::move(redirects), std::move(chain),
                               base::DoNothing());
  observer.Wait();

  histograms().ExpectTotalCount(kServerRedirectsDelayHist, 2);
  histograms().ExpectTotalCount(kServerRedirectsChainDelayHist, 1);
  base::HistogramTester::CountsMap expected_counts = {
      {kServerRedirectsStatusCodePrefix + kNoCache, 1},
      {kServerRedirectsStatusCodePrefix + kCached, 1},
  };
  EXPECT_THAT(
      histograms().GetTotalCountsForPrefix(kServerRedirectsStatusCodePrefix),
      testing::ContainerEq(expected_counts));

  histograms().ExpectUniqueSample(kServerRedirectsStatusCodePrefix + kNoCache,
                                  net::HTTP_FOUND, 1);
  histograms().ExpectUniqueSample(kServerRedirectsStatusCodePrefix + kCached,
                                  net::HTTP_MOVED_PERMANENTLY, 1);
  histograms().ExpectUniqueSample(kServerRedirectsDelayHist, 100, 2);
  histograms().ExpectUniqueSample(kServerRedirectsChainDelayHist, 200, 1);
}

MATCHER_P(HasSourceId, id, "") {
  *result_listener << "where the source id is " << arg.source_id;
  return arg.source_id == id;
}

MATCHER_P(HasMetrics, matcher, "") {
  return ExplainMatchResult(matcher, arg.metrics, result_listener);
}

using BtmServiceUkmTest = BtmServiceTest;

TEST_F(BtmServiceUkmTest, BothChainBeginAndChainEnd) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  TestBrowserContext profile;
  BtmServiceImpl* service = BtmServiceImpl::Get(&profile);

  UrlAndSourceId initial_url = MakeUrlAndId("http://a.test/");
  UrlAndSourceId redirect_url1 = MakeUrlAndId("http://b.test/");
  UrlAndSourceId redirect_url2 = MakeUrlAndId("http://c.test/first");
  UrlAndSourceId final_url = MakeUrlAndId("http://c.test/second");

  BtmRedirectChainObserver observer(service, final_url.url);
  std::vector<BtmRedirectInfoPtr> redirects;
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      redirect_url1,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      redirect_url2,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  BtmRedirectChainInfoPtr chain = std::make_unique<BtmRedirectChainInfo>(
      initial_url, final_url,
      /*length=*/2, /*is_partial_chain=*/false,
      /*are_3pcs_generally_enabled=*/false);
  const int32_t chain_id = chain->chain_id;
  btm::Populate3PcExceptions(&profile, /*web_contents=*/nullptr,
                             initial_url.url, final_url.url, redirects);
  service->HandleRedirectChain(std::move(redirects), std::move(chain),
                               base::DoNothing());
  observer.Wait();

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainBegin",
                                      {"ChainId", "InitialAndFinalSitesSame"}),
              ElementsAre(AllOf(HasSourceId(initial_url.source_id),
                                HasMetrics(ElementsAre(
                                    Pair("ChainId", chain_id),
                                    Pair("InitialAndFinalSitesSame", 0))))));

  EXPECT_THAT(
      ukm_recorder.GetEntries("BTM.Redirect",
                              {"ChainId", "InitialAndFinalSitesSame"}),
      ElementsAre(
          AllOf(HasSourceId(redirect_url1.source_id),
                HasMetrics(ElementsAre(Pair("ChainId", chain_id),
                                       Pair("InitialAndFinalSitesSame", 0)))),
          AllOf(HasSourceId(redirect_url2.source_id),
                HasMetrics(ElementsAre(Pair("ChainId", chain_id),
                                       Pair("InitialAndFinalSitesSame", 0))))));

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainEnd",
                                      {"ChainId", "InitialAndFinalSitesSame"}),
              ElementsAre(AllOf(HasSourceId(final_url.source_id),
                                HasMetrics(ElementsAre(
                                    Pair("ChainId", chain_id),
                                    Pair("InitialAndFinalSitesSame", 0))))));
}

TEST_F(BtmServiceUkmTest, InitialAndFinalSitesSame_True) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  TestBrowserContext profile;
  BtmServiceImpl* service = BtmServiceImpl::Get(&profile);

  UrlAndSourceId initial_url = MakeUrlAndId("http://a.test/");
  UrlAndSourceId redirect_url = MakeUrlAndId("http://b.test/");
  UrlAndSourceId final_url = MakeUrlAndId("http://a.test/different-path");

  BtmRedirectChainObserver observer(service, final_url.url);
  std::vector<BtmRedirectInfoPtr> redirects;
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      redirect_url,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  BtmRedirectChainInfoPtr chain = std::make_unique<BtmRedirectChainInfo>(
      initial_url, final_url,
      /*length=*/1, /*is_partial_chain=*/false,
      /*are_3pcs_generally_enabled=*/false);
  btm::Populate3PcExceptions(&profile, /*web_contents=*/nullptr,
                             chain->initial_url.url, chain->final_url.url,
                             redirects);
  service->HandleRedirectChain(std::move(redirects), std::move(chain),
                               base::DoNothing());
  observer.Wait();

  EXPECT_THAT(
      ukm_recorder.GetEntries("BTM.ChainBegin", {"InitialAndFinalSitesSame"}),
      ElementsAre(
          AllOf(HasSourceId(initial_url.source_id),
                HasMetrics(ElementsAre(Pair("InitialAndFinalSitesSame", 1))))));

  EXPECT_THAT(
      ukm_recorder.GetEntries("BTM.Redirect", {"InitialAndFinalSitesSame"}),
      ElementsAre(
          AllOf(HasSourceId(redirect_url.source_id),
                HasMetrics(ElementsAre(Pair("InitialAndFinalSitesSame", 1))))));

  EXPECT_THAT(
      ukm_recorder.GetEntries("BTM.ChainEnd", {"InitialAndFinalSitesSame"}),
      ElementsAre(
          AllOf(HasSourceId(final_url.source_id),
                HasMetrics(ElementsAre(Pair("InitialAndFinalSitesSame", 1))))));
}

TEST_F(BtmServiceUkmTest, DontReportEmptyChainsAtAll) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  TestBrowserContext profile;
  BtmServiceImpl* service = BtmServiceImpl::Get(&profile);

  UrlAndSourceId initial_url = MakeUrlAndId("http://a.test/");
  UrlAndSourceId final_url = MakeUrlAndId("http://b.test/");

  BtmRedirectChainObserver observer(service, final_url.url);
  BtmRedirectChainInfoPtr chain = std::make_unique<BtmRedirectChainInfo>(
      initial_url, final_url,
      /*length=*/0, /*is_partial_chain=*/false,
      /*are_3pcs_generally_enabled*/ false);

  service->HandleRedirectChain({}, std::move(chain), base::DoNothing());
  observer.Wait();

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainBegin", {}), IsEmpty());
  EXPECT_THAT(ukm_recorder.GetEntries("BTM.Redirect", {}), IsEmpty());
  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainEnd", {}), IsEmpty());
}

TEST_F(BtmServiceUkmTest, DontReportChainBeginIfInvalidSourceId) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  TestBrowserContext profile;
  BtmServiceImpl* service = BtmServiceImpl::Get(&profile);

  UrlAndSourceId redirect_url = MakeUrlAndId("http://b.test/");
  UrlAndSourceId final_url = MakeUrlAndId("http://c.test/");

  BtmRedirectChainObserver observer(service, final_url.url);
  std::vector<BtmRedirectInfoPtr> redirects;
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      redirect_url,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  BtmRedirectChainInfoPtr chain = std::make_unique<BtmRedirectChainInfo>(
      UrlAndSourceId(), final_url,
      /*length=*/1, /*is_partial_chain=*/false,
      /*are_3pcs_generally_enabled=*/false);
  btm::Populate3PcExceptions(&profile, /*web_contents=*/nullptr,
                             chain->initial_url.url, chain->final_url.url,
                             redirects);
  service->HandleRedirectChain(std::move(redirects), std::move(chain),
                               base::DoNothing());
  observer.Wait();

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainBegin", {}), IsEmpty());

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.Redirect", {}),
              ElementsAre(AllOf(HasSourceId(redirect_url.source_id))));

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainEnd", {}),
              ElementsAre(AllOf(HasSourceId(final_url.source_id))));
}

TEST_F(BtmServiceUkmTest, DontReportChainEndIfInvalidSourceId) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  TestBrowserContext profile;
  BtmServiceImpl* service = BtmServiceImpl::Get(&profile);

  UrlAndSourceId initial_url = MakeUrlAndId("http://a.test/");
  UrlAndSourceId redirect_url = MakeUrlAndId("http://b.test/");

  BtmRedirectChainObserver observer(service, GURL());
  std::vector<BtmRedirectInfoPtr> redirects;
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      redirect_url,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  BtmRedirectChainInfoPtr chain = std::make_unique<BtmRedirectChainInfo>(
      initial_url, UrlAndSourceId(),
      /*length=*/1, /*is_partial_chain=*/false,
      /*are_3pcs_generally_enabled=*/false);
  btm::Populate3PcExceptions(&profile, /*web_contents=*/nullptr,
                             chain->initial_url.url, chain->final_url.url,
                             redirects);
  service->HandleRedirectChain(std::move(redirects), std::move(chain),
                               base::DoNothing());
  observer.Wait();

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainBegin", {}),
              ElementsAre(AllOf(HasSourceId(initial_url.source_id))));

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.Redirect", {}),
              ElementsAre(AllOf(HasSourceId(redirect_url.source_id))));

  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainEnd", {}), IsEmpty());
}

TEST_F(BtmServiceUkmTest, DontReportChainIfTpcsEnabled) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;
  TestBrowserContext profile;
  BtmServiceImpl* service = BtmServiceImpl::Get(&profile);

  UrlAndSourceId initial_url = MakeUrlAndId("http://a.test/");
  UrlAndSourceId redirect_url = MakeUrlAndId("http://b.test/");
  UrlAndSourceId final_url = MakeUrlAndId("http://c.test/");

  BtmRedirectChainObserver observer(service, final_url.url);
  std::vector<BtmRedirectInfoPtr> redirects;
  redirects.push_back(BtmRedirectInfo::CreateForServer(
      redirect_url,
      /*access_type=*/BtmDataAccessType::kNone,
      /*time=*/base::Time::Now(),
      /*was_response_cached=*/false,
      /*response_code=*/net::HTTP_FOUND,
      /*server_bounce_delay=*/base::TimeDelta()));
  BtmRedirectChainInfoPtr chain = std::make_unique<BtmRedirectChainInfo>(
      initial_url, final_url, redirects.size(), /*is_partial_chain=*/false,
      /*are_3pcs_generally_enabled=*/true);
  btm::Populate3PcExceptions(&profile, /*web_contents=*/nullptr,
                             initial_url.url, final_url.url, redirects);
  service->HandleRedirectChain(std::move(redirects), std::move(chain),
                               base::DoNothing());
  observer.Wait();

  // There should be no BTM chain UKMs, as processing gets short-circuited when
  // third-party cookies are enabled.
  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainBegin", {"ChainId"}),
              IsEmpty());
  EXPECT_THAT(ukm_recorder.GetEntries("BTM.Redirect", {"ChainId"}), IsEmpty());
  EXPECT_THAT(ukm_recorder.GetEntries("BTM.ChainEnd", {"ChainId"}), IsEmpty());
}

}  // namespace content