File: manager_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1156 lines) | stat: -rw-r--r-- 48,824 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <cstring>
#include <string>
#include <tuple>
#include <vector>

#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/net/storage_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_test_util.h"
#include "chrome/browser/tpcd/support/top_level_trial_service.h"
#include "chrome/browser/tpcd/support/top_level_trial_service_factory.h"
#include "chrome/browser/tpcd/support/validity_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/profile_waiter.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/common/content_settings_metadata.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/content_settings/core/common/features.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/privacy_sandbox/privacy_sandbox_features.h"
#include "components/privacy_sandbox/tracking_protection_prefs.h"
#include "components/tpcd/metadata/browser/parser.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_paths.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/base/features.h"
#include "net/cookies/cookie_partition_key.h"
#include "net/cookies/cookie_setting_override.h"
#include "net/cookies/site_for_cookies.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"

namespace tpcd::metadata {
namespace {
const base::FilePath::CharType kComponentFileName[] =
    FILE_PATH_LITERAL("metadata.pb");

const char* kFirstPartyHost = "a.test";
const char* kThirdPartyHost1 = "b.test";
const char* kThirdPartyHost1Sub = "sub.b.test";
const char* kThirdPartyHost2 = "c.test";
const char* kThirdPartyHost3 = "d.test";

#if !BUILDFLAG(IS_CHROMEOS)
// Creates a Original Guest Profile (not OTR Profile) for testing.
Profile& CreateOriginalGuestProfile() {
  Profile& original_guest_profile = profiles::testing::CreateProfileSync(
      g_browser_process->profile_manager(),
      ProfileManager::GetGuestProfilePath());

  return original_guest_profile;
}

// Creates a new regular profile for testing.
Profile* CreateRegularProfile() {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  base::FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();

  profiles::testing::CreateProfileSync(profile_manager, new_path);

  return profile_manager->GetProfile(new_path);
}
#endif

const char kThirdPartyCookieAllowMechanismHistogram[] =
    "PageLoad.Clients.TPCD.CookieAccess.ThirdPartyCookieAllowMechanism3";
using ThirdPartyCookieAllowMechanism =
    content_settings::CookieSettingsBase::ThirdPartyCookieAllowMechanism;
}  // namespace

class ManagerBrowserTest : public InProcessBrowserTest {
 public:
  ManagerBrowserTest() : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
    CHECK(fake_install_dir_.CreateUniqueTempDir());
    CHECK(fake_install_dir_.IsValid());
    scoped_feature_list_.InitWithFeatures(
        {content_settings::features::kTrackingProtection3pcd,
         net::features::kTpcdMetadataGrants,
         net::features::kTpcdMetadataStageControl,
         net::features::kTopLevelTpcdTrialSettings},
        {});

    // Disable the validity service so it doesn't remove manually created
    // trial settings.
    tpcd::trial::ValidityService::DisableForTesting();
  }
  ~ManagerBrowserTest() override = default;

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    base::FilePath path;
    base::PathService::Get(content::DIR_TEST_DATA, &path);
    https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
    https_server_.ServeFilesFromDirectory(path);
    https_server_.AddDefaultHandlers(GetChromeTestDataDir());
    EXPECT_TRUE(https_server_.Start());
  }

  net::test_server::EmbeddedTestServer* https_server() {
    return &https_server_;
  }

  Parser* parser() { return tpcd::metadata::Parser::GetInstance(); }

  void MockComponentInstallation(Metadata metadata) {
    base::FilePath path =
        fake_install_dir_.GetPath().Append(kComponentFileName);
    CHECK(base::WriteFile(path, metadata.SerializeAsString()));

    CHECK(base::PathExists(path));
    std::string raw_metadata;
    CHECK(base::ReadFileToString(path, &raw_metadata));

    parser()->ParseMetadata(raw_metadata);
  }

  PrefService* GetPrefs(Profile* profile = nullptr) {
    return (profile ? profile : browser()->profile())->GetPrefs();
  }

  content_settings::CookieSettings* GetCookieSettings(
      Profile* profile = nullptr) {
    return CookieSettingsFactory::GetForProfile(profile ? profile
                                                        : browser()->profile())
        .get();
  }

  void NavigateToPageWithFrame(const std::string& host,
                               Browser* alt_browser = nullptr) {
    GURL url(https_server()->GetURL(host, "/iframe.html"));
    EXPECT_TRUE(ui_test_utils::NavigateToURL(
        alt_browser ? alt_browser : browser(), url));
  }

  content::WebContents* GetWebContents(Browser* alt_browser = nullptr) {
    return (alt_browser ? alt_browser : browser())
        ->tab_strip_model()
        ->GetActiveWebContents();
  }

  void NavigateFrameTo(const std::string& host,
                       const std::string& path,
                       Browser* alt_browser = nullptr) {
    GURL url = https_server()->GetURL(host, path);
    EXPECT_TRUE(NavigateIframeToURL(GetWebContents(alt_browser), "test", url));
  }

  content::RenderFrameHost* GetFrame(Browser* alt_browser = nullptr) {
    return ChildFrameAt((alt_browser ? alt_browser : browser())
                            ->tab_strip_model()
                            ->GetActiveWebContents()
                            ->GetPrimaryMainFrame(),
                        0);
  }

  std::vector<std::string> ContentSettingsToString(ContentSettingsType type,
                                                   Profile* profile = nullptr) {
    std::vector<std::string> settings;
    for (const auto& setting :
         GetCookieSettings(profile)->GetTpcdMetadataGrants()) {
      settings.emplace_back(base::StringPrintf(
          "[%s,%s]:%d", setting.primary_pattern.ToString().c_str(),
          setting.secondary_pattern.ToString().c_str(),
          content_settings::ValueToContentSetting(setting.setting_value)));
    }
    return settings;
  }

  void ExpectCookie(content::RenderFrameHost* frame, bool expected) {
    // navigator.cookieEnabled only checks the browser setting, not if
    // unpartitioned cookies are enabled.
    EXPECT_TRUE(
        content::EvalJs(frame, "navigator.cookieEnabled").ExtractBool());
    // This returns true even if the cookie fails to be set because
    // unpartitioned cookies are blocked.
    EXPECT_TRUE(content::EvalJs(frame, "setCookie()").ExtractBool());
    // This is the only step that actually verifies if unpartitioned cookies
    // are accessible.
    EXPECT_EQ(content::EvalJs(frame, "hasCookie()").ExtractBool(), expected);
  }

  // third-party storage should only be accessible when:
  // - Third-party cookies are allowed by default,
  // - Access grants are given via third-party cookies deprecation metadata, or
  // - Third-party storage partitioning is enabled,
  // But will never be accessible if blocked by specific user cookie setting
  // preferences (`setting_source_user`).
  void ExpectStorage(content::RenderFrameHost* frame,
                     const bool expected,
                     const bool setting_source_user,
                     const bool is_3psp_enabled) {
    if (expected || (setting_source_user ? false : is_3psp_enabled)) {
      storage::test::SetStorageForFrame(frame, /*include_cookies=*/false, true);
      storage::test::ExpectStorageForFrame(frame, true);
    } else {
      storage::test::SetStorageForFrame(frame, /*include_cookies=*/false,
                                        false);
      storage::test::ExpectStorageForFrame(frame, false);
    }
  }

 private:
  base::ScopedTempDir fake_install_dir_;
  base::test::ScopedFeatureList scoped_feature_list_;
  net::test_server::EmbeddedTestServer https_server_;
};

IN_PROC_BROWSER_TEST_F(ManagerBrowserTest, GetTpcdMetadataGrants_Empty) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  ASSERT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 0u);

  Metadata metadata;
  ASSERT_EQ(metadata.metadata_entries_size(), 0);

  MockComponentInstallation(metadata);
  ASSERT_TRUE(GetCookieSettings()->GetTpcdMetadataGrants().empty());
}

IN_PROC_BROWSER_TEST_F(ManagerBrowserTest, GetTpcdMetadataGrants) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  const GURL kEmbedded = GURL("http://www.bar.com");
  const url::Origin kEmbedder = url::Origin::Create(GURL("http://www.foo.com"));
  net::CookiePartitionKey cookie_partition_key =
      net::CookiePartitionKey::FromURLForTesting(kEmbedder.GetURL());

  ASSERT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 0u);
  EXPECT_FALSE(GetCookieSettings()->IsFullCookieAccessAllowed(
      kEmbedded, net::SiteForCookies(), kEmbedder, {}, cookie_partition_key));

  Metadata metadata;
  tpcd::metadata::helpers::AddEntryToMetadata(metadata, "[*.]bar.com",
                                              "[*.]foo.com");
  ASSERT_EQ(metadata.metadata_entries_size(), 1);

  MockComponentInstallation(metadata);

  ASSERT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 1u);
  ASSERT_EQ(GetCookieSettings()
                ->GetTpcdMetadataGrants()
                .front()
                .metadata.tpcd_metadata_rule_source(),
            content_settings::mojom::TpcdMetadataRuleSource::SOURCE_TEST);
  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      kEmbedded, net::SiteForCookies(), kEmbedder, {}, cookie_partition_key));
}

IN_PROC_BROWSER_TEST_F(ManagerBrowserTest, SuccessfullyUpdated) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  const GURL kEmbedded1 = GURL("http://www.bar.com");
  const url::Origin kEmbedder1 =
      url::Origin::Create(GURL("http://www.foo.com"));
  net::CookiePartitionKey cookie_partition_key_1 =
      net::CookiePartitionKey::FromURLForTesting(kEmbedder1.GetURL());
  const GURL kEmbedded2 = GURL("http://www.baz.com");
  const url::Origin kEmbedder2 =
      url::Origin::Create(GURL("http://www.daz.com"));
  net::CookiePartitionKey cookie_partition_key_2 =
      net::CookiePartitionKey::FromURLForTesting(kEmbedder2.GetURL());

  {
    Metadata metadata;
    tpcd::metadata::helpers::AddEntryToMetadata(metadata, "[*.]bar.com",
                                                "[*.]foo.com");
    ASSERT_EQ(metadata.metadata_entries_size(), 1);

    ASSERT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 0u);
    EXPECT_FALSE(GetCookieSettings()->IsFullCookieAccessAllowed(
        kEmbedded1, net::SiteForCookies(), kEmbedder1, {},
        cookie_partition_key_1));

    MockComponentInstallation(metadata);

    ASSERT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 1u);
    EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
        kEmbedded1, net::SiteForCookies(), kEmbedder1, {},
        cookie_partition_key_1));
  }

  {
    Metadata metadata;
    tpcd::metadata::helpers::AddEntryToMetadata(metadata, "[*.]baz.com",
                                                "[*.]daz.com");
    ASSERT_EQ(metadata.metadata_entries_size(), 1);

    ASSERT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 1u);
    EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
        kEmbedded1, net::SiteForCookies(), kEmbedder1, {},
        cookie_partition_key_1));
    EXPECT_FALSE(GetCookieSettings()->IsFullCookieAccessAllowed(
        kEmbedded2, net::SiteForCookies(), kEmbedder2, {},
        cookie_partition_key_2));

    MockComponentInstallation(metadata);

    ASSERT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 1u);
    EXPECT_FALSE(GetCookieSettings()->IsFullCookieAccessAllowed(
        kEmbedded1, net::SiteForCookies(), kEmbedder1, {},
        cookie_partition_key_1));
    EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
        kEmbedded2, net::SiteForCookies(), kEmbedder2, {},
        cookie_partition_key_2));
  }
}

IN_PROC_BROWSER_TEST_F(ManagerBrowserTest,
                       TpcdDtGracePeriodEnforced_ValidDtToken) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  const GURL third_party_url_1 = https_server()->GetURL(kThirdPartyHost1, "/");
  const GURL third_party_url_2 = https_server()->GetURL(kThirdPartyHost2, "/");
  const GURL third_party_url_3 = https_server()->GetURL(kThirdPartyHost3, "/");

  const std::string secondary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();
  const std::string primary_pattern_spec_1 =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url_1).ToString();
  const std::string primary_pattern_spec_2 =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url_2).ToString();
  const std::string primary_pattern_spec_3 =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url_3).ToString();

  Metadata metadata;

  const uint32_t dtrp_guarantees_grace_period_forced_on = 0;
  tpcd::metadata::helpers::AddEntryToMetadata(
      metadata, primary_pattern_spec_1, secondary_pattern_spec,
      Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_on);

  const uint32_t dtrp_guarantees_grace_period_forced_off = 100;
  tpcd::metadata::helpers::AddEntryToMetadata(
      metadata, primary_pattern_spec_2, secondary_pattern_spec,
      Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_off);

  tpcd::metadata::helpers::AddEntryToMetadata(metadata, primary_pattern_spec_3,
                                              secondary_pattern_spec,
                                              Parser::kSourceCriticalSector);

  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 0u);
  MockComponentInstallation(metadata);
  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 3u);

  auto* service = tpcd::trial::TopLevelTrialServiceFactory::GetForProfile(
      browser()->profile());
  auto embedder_origin = url::Origin::Create(first_party_url);
  net::CookiePartitionKey cookie_partition_key =
      net::CookiePartitionKey::FromURLForTesting(embedder_origin.GetURL());
  service->UpdateTopLevelTrialSettingsForTesting(
      embedder_origin, /*match_subdomains=*/true, /*enabled=*/true);

  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_1, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;
    content::CookieChangeObserver observer(GetWebContents(),
                                           /*num_expected_calls=*/2);
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/true);
    observer.Wait();
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    histogram_tester.ExpectUniqueSample(
        kThirdPartyCookieAllowMechanismHistogram,
        ThirdPartyCookieAllowMechanism::kAllowBy3PCDMetadataSource1pDt, 2);
  }

  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_2, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;
    content::CookieChangeObserver observer(GetWebContents(),
                                           /*num_expected_calls=*/2);
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost2, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/true);
    observer.Wait();
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    histogram_tester.ExpectUniqueSample(
        kThirdPartyCookieAllowMechanismHistogram,
        ThirdPartyCookieAllowMechanism::kAllowByTopLevel3PCD, 2);
  }

  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_3, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;
    content::CookieChangeObserver observer(GetWebContents(),
                                           /*num_expected_calls=*/2);
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost3, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/true);
    observer.Wait();
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    histogram_tester.ExpectUniqueSample(
        kThirdPartyCookieAllowMechanismHistogram,
        ThirdPartyCookieAllowMechanism::
            kAllowBy3PCDMetadataSourceCriticalSector,
        2);
  }
}

// This test coverage ensures more specific patterns precede on others.
IN_PROC_BROWSER_TEST_F(ManagerBrowserTest,
                       TpcdDtGracePeriodEnforced_EntryPrecedence_1) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  const GURL third_party_url_1 = https_server()->GetURL(kThirdPartyHost1, "/");
  const GURL third_party_url_1_sub =
      https_server()->GetURL(kThirdPartyHost1Sub, "/");

  const std::string secondary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();

  const std::string wildcard = "[*.]";
  const std::string primary_pattern_spec_1 =
      base::StrCat({wildcard, kThirdPartyHost1});
  const std::string primary_pattern_spec_1_sub =
      base::StrCat({wildcard, kThirdPartyHost1Sub});

  Metadata metadata;

  // This order of insertion of entries should be maintained in order to have
  // the less specific entry first in the list.
  {
    const uint32_t dtrp_guarantees_grace_period_forced_on = 0;
    const uint32_t dtrp_guarantees_grace_period_forced_off = 100;

    tpcd::metadata::helpers::AddEntryToMetadata(
        metadata, primary_pattern_spec_1, secondary_pattern_spec,
        Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_on);

    tpcd::metadata::helpers::AddEntryToMetadata(
        metadata, primary_pattern_spec_1_sub, secondary_pattern_spec,
        Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_off);
  }

  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 0u);
  MockComponentInstallation(metadata);
  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 2u);

  auto embedder_origin = url::Origin::Create(first_party_url);
  net::CookiePartitionKey cookie_partition_key =
      net::CookiePartitionKey::FromURLForTesting(embedder_origin.GetURL());

  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_1, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;

    content::CookieChangeObserver observer(GetWebContents(),
                                           /*num_expected_calls=*/2);
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/true);
    observer.Wait();
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    histogram_tester.ExpectUniqueSample(
        kThirdPartyCookieAllowMechanismHistogram,
        ThirdPartyCookieAllowMechanism::kAllowBy3PCDMetadataSource1pDt, 2);
  }

  EXPECT_FALSE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_1_sub, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;

    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost1Sub, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/false);
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    EXPECT_EQ(
        histogram_tester.GetTotalSum(kThirdPartyCookieAllowMechanismHistogram),
        0);
  }
}

// This test coverage ensures more specific patterns precede on others.
IN_PROC_BROWSER_TEST_F(ManagerBrowserTest,
                       TpcdDtGracePeriodEnforced_EntryPrecedence_2) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  const GURL third_party_url_1 = https_server()->GetURL(kThirdPartyHost1, "/");
  const GURL third_party_url_1_sub =
      https_server()->GetURL(kThirdPartyHost1Sub, "/");

  const std::string secondary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();

  const std::string wildcard = "[*.]";
  const std::string primary_pattern_spec_1 =
      base::StrCat({wildcard, kThirdPartyHost1});
  const std::string primary_pattern_spec_1_sub =
      base::StrCat({wildcard, kThirdPartyHost1Sub});

  Metadata metadata;

  // This order of insertion of entries should be maintained in order to have
  // the less specific entry first in the list.
  {
    const uint32_t dtrp_guarantees_grace_period_forced_on = 0;
    const uint32_t dtrp_guarantees_grace_period_forced_off = 100;

    tpcd::metadata::helpers::AddEntryToMetadata(
        metadata, primary_pattern_spec_1, secondary_pattern_spec,
        Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_off);

    tpcd::metadata::helpers::AddEntryToMetadata(
        metadata, primary_pattern_spec_1_sub, secondary_pattern_spec,
        Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_on);
  }

  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 0u);
  MockComponentInstallation(metadata);
  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 2u);

  auto embedder_origin = url::Origin::Create(first_party_url);
  net::CookiePartitionKey cookie_partition_key =
      net::CookiePartitionKey::FromURLForTesting(embedder_origin.GetURL());

  EXPECT_FALSE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_1, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;

    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/false);
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    EXPECT_EQ(
        histogram_tester.GetTotalSum(kThirdPartyCookieAllowMechanismHistogram),
        0);
  }

  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_1_sub, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;

    content::CookieChangeObserver observer(GetWebContents(),
                                           /*num_expected_calls=*/2);
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost1Sub, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/true);
    observer.Wait();
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    histogram_tester.ExpectUniqueSample(
        kThirdPartyCookieAllowMechanismHistogram,
        ThirdPartyCookieAllowMechanism::kAllowBy3PCDMetadataSource1pDt, 2);
  }
}

IN_PROC_BROWSER_TEST_F(ManagerBrowserTest,
                       TpcdDtGracePeriodEnforced_InValidDtToken) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  const GURL third_party_url_1 = https_server()->GetURL(kThirdPartyHost1, "/");
  const GURL third_party_url_2 = https_server()->GetURL(kThirdPartyHost2, "/");
  const GURL third_party_url_3 = https_server()->GetURL(kThirdPartyHost3, "/");

  const std::string secondary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();
  const std::string primary_pattern_spec_1 =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url_1).ToString();
  const std::string primary_pattern_spec_2 =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url_2).ToString();
  const std::string primary_pattern_spec_3 =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url_3).ToString();

  Metadata metadata;

  const uint32_t dtrp_guarantees_grace_period_forced_on = 0;
  tpcd::metadata::helpers::AddEntryToMetadata(
      metadata, primary_pattern_spec_1, secondary_pattern_spec,
      Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_on);

  const uint32_t dtrp_guarantees_grace_period_forced_off = 100;
  tpcd::metadata::helpers::AddEntryToMetadata(
      metadata, primary_pattern_spec_2, secondary_pattern_spec,
      Parser::kSource1pDt, dtrp_guarantees_grace_period_forced_off);

  tpcd::metadata::helpers::AddEntryToMetadata(metadata, primary_pattern_spec_3,
                                              secondary_pattern_spec,
                                              Parser::kSourceCriticalSector);

  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 0u);
  MockComponentInstallation(metadata);
  EXPECT_EQ(GetCookieSettings()->GetTpcdMetadataGrants().size(), 3u);

  auto embedder_origin = url::Origin::Create(first_party_url);
  net::CookiePartitionKey cookie_partition_key =
      net::CookiePartitionKey::FromURLForTesting(embedder_origin.GetURL());

  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_1, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;
    content::CookieChangeObserver observer(GetWebContents(),
                                           /*num_expected_calls=*/2);
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/true);
    observer.Wait();
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    histogram_tester.ExpectUniqueSample(
        kThirdPartyCookieAllowMechanismHistogram,
        ThirdPartyCookieAllowMechanism::kAllowBy3PCDMetadataSource1pDt, 2);
  }

  EXPECT_FALSE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_2, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost2, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/false);
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    EXPECT_EQ(
        histogram_tester.GetTotalSum(kThirdPartyCookieAllowMechanismHistogram),
        0);
  }

  EXPECT_TRUE(GetCookieSettings()->IsFullCookieAccessAllowed(
      third_party_url_3, net::SiteForCookies(), embedder_origin, {},
      cookie_partition_key));
  {
    base::HistogramTester histogram_tester;
    content::CookieChangeObserver observer(GetWebContents(),
                                           /*num_expected_calls=*/2);
    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost3, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), /*expected=*/true);
    observer.Wait();
    EXPECT_TRUE(
        ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));

    histogram_tester.ExpectUniqueSample(
        kThirdPartyCookieAllowMechanismHistogram,
        ThirdPartyCookieAllowMechanism::
            kAllowBy3PCDMetadataSourceCriticalSector,
        2);
  }
}

class ManagerPrefsBrowserTest
    : public ManagerBrowserTest,
      public testing::WithParamInterface<
          std::tuple</*net::features::kThirdPartyStoragePartitioning*/ bool,
                     /*prefs::kBlockAll3pcToggleEnabled*/ bool>> {
 public:
  ManagerPrefsBrowserTest() {
    scoped_feature_list_.InitWithFeatureStates(
        {{net::features::kForceThirdPartyCookieBlocking, false},
         {net::features::kThirdPartyStoragePartitioning,
          ThirdPartyStoragePartitioningEnabled()},
         {net::features::kThirdPartyPartitionedStorageAllowedByDefault, true},
         {content_settings::features::kTrackingProtection3pcd, true}});
  }

  bool BlockAll3pcToggleEnabled() { return std::get<1>(GetParam()); }

  void SimulateTrackingProtectionSettings(Profile* profile = nullptr) {
    GetPrefs(profile)->SetDefaultPrefValue(
        prefs::kTrackingProtection3pcdEnabled, base::Value(true));
    EXPECT_TRUE(GetCookieSettings()->ShouldBlockThirdPartyCookies());

    GetPrefs(profile)->SetBoolean(prefs::kBlockAll3pcToggleEnabled,
                                  BlockAll3pcToggleEnabled());
  }

  bool GetTrackingProtection3pcdEnabledPref(Profile* profile = nullptr) {
    return GetPrefs(profile)->GetBoolean(prefs::kTrackingProtection3pcdEnabled);
  }

  bool GetBlockAll3pcToggleEnabledPref(Profile* profile = nullptr) {
    return GetPrefs(profile)->GetBoolean(prefs::kBlockAll3pcToggleEnabled);
  }

  bool ThirdPartyStoragePartitioningEnabled() const {
    return std::get<0>(GetParam());
  }

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

// The first Bool controls the enablement of
// `net::features::kThirdPartyStoragePartitioning`.
//
// The first Bool controls the
// enablement of `prefs::kBlockAll3pcToggleEnabled`.
INSTANTIATE_TEST_SUITE_P(All,
                         ManagerPrefsBrowserTest,
                         testing::Combine(testing::Bool(), testing::Bool()));

IN_PROC_BROWSER_TEST_P(ManagerPrefsBrowserTest,
                       RelevantUserCookieSpecsPrecede) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  SimulateTrackingProtectionSettings();

  GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  GURL third_party_url = https_server()->GetURL(kThirdPartyHost1, "/");

  // Simulates a user's preference: Blocks all requests to `third_party_url` to
  // access site data in 3P context.
  GetCookieSettings()->SetCookieSetting(third_party_url,
                                        ContentSetting::CONTENT_SETTING_BLOCK);
  EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                third_party_url, net::SiteForCookies(), GURL(),
                net::CookieSettingOverrides()),
            ContentSetting::CONTENT_SETTING_BLOCK);

  // Simulates a user's preference: Blocks all third parties requests on
  // `first_party_url` to access site data.
  GetCookieSettings()->SetThirdPartyCookieSetting(
      first_party_url, ContentSetting::CONTENT_SETTING_BLOCK);
  EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                GURL(), net::SiteForCookies(), first_party_url,
                net::CookieSettingOverrides()),
            ContentSetting::CONTENT_SETTING_BLOCK);

  const std::string wildcard_spec = "*";
  Metadata metadata;
  tpcd::metadata::helpers::AddEntryToMetadata(metadata, wildcard_spec,
                                              wildcard_spec);
  EXPECT_EQ(metadata.metadata_entries_size(), 1);
  MockComponentInstallation(metadata);
  EXPECT_THAT(
      ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS),
      testing::ElementsAre("[*,*]:1"));

  EXPECT_EQ(!BlockAll3pcToggleEnabled(),
            GetCookieSettings()->MitigationsEnabledFor3pcd());
  EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                third_party_url, net::SiteForCookies(), first_party_url,
                net::CookieSettingOverrides()),
            ContentSetting::CONTENT_SETTING_BLOCK);

  NavigateToPageWithFrame(kFirstPartyHost);
  NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html");
  ExpectCookie(GetFrame(), /*expected=*/false);
  ExpectStorage(GetFrame(), false, true,
                ThirdPartyStoragePartitioningEnabled());
}

IN_PROC_BROWSER_TEST_P(ManagerPrefsBrowserTest, NoSpecificBlockedCookieSpecs) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  SimulateTrackingProtectionSettings();

  {
    const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
    const GURL third_party_url = https_server()->GetURL(kThirdPartyHost1, "/");

    const std::string primary_pattern_spec =
        ContentSettingsPattern::FromURLNoWildcard(third_party_url).ToString();
    const std::string secondary_pattern_spec =
        ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();
    Metadata metadata;
    tpcd::metadata::helpers::AddEntryToMetadata(metadata, primary_pattern_spec,
                                                secondary_pattern_spec);
    EXPECT_EQ(metadata.metadata_entries_size(), 1);
    MockComponentInstallation(metadata);

    EXPECT_THAT(
        ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS),
        testing::UnorderedElementsAreArray(
            {base::StringPrintf("[%s,%s]:%d", primary_pattern_spec.c_str(),
                                secondary_pattern_spec.c_str(), 1)}));

    bool expected = !BlockAll3pcToggleEnabled();
    EXPECT_EQ(expected, GetCookieSettings()->MitigationsEnabledFor3pcd());
    EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                  third_party_url, net::SiteForCookies(), first_party_url,
                  net::CookieSettingOverrides()),
              expected ? ContentSetting::CONTENT_SETTING_ALLOW
                       : ContentSetting::CONTENT_SETTING_BLOCK);

    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), expected);
    ExpectStorage(GetFrame(), expected, false,
                  ThirdPartyStoragePartitioningEnabled());
  }

  // Make sure changes get propagated accordingly:
  {
    GetPrefs()->SetBoolean(prefs::kBlockAll3pcToggleEnabled, true);

    const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
    const GURL third_party_url = https_server()->GetURL(kThirdPartyHost2, "/");

    const std::string primary_pattern_spec =
        ContentSettingsPattern::FromURLNoWildcard(third_party_url).ToString();
    const std::string secondary_pattern_spec =
        ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();
    Metadata metadata;
    tpcd::metadata::helpers::AddEntryToMetadata(metadata, primary_pattern_spec,
                                                secondary_pattern_spec);
    EXPECT_EQ(metadata.metadata_entries_size(), 1);
    MockComponentInstallation(metadata);

    EXPECT_THAT(
        ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS),
        testing::UnorderedElementsAreArray(
            {base::StringPrintf("[%s,%s]:%d", primary_pattern_spec.c_str(),
                                secondary_pattern_spec.c_str(), 1)}));

    bool expected = false;
    EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                  third_party_url, net::SiteForCookies(), first_party_url,
                  net::CookieSettingOverrides()),
              expected ? ContentSetting::CONTENT_SETTING_ALLOW
                       : ContentSetting::CONTENT_SETTING_BLOCK);

    NavigateToPageWithFrame(kFirstPartyHost);
    NavigateFrameTo(kThirdPartyHost2, "/browsing_data/site_data.html");
    ExpectCookie(GetFrame(), expected);
    ExpectStorage(GetFrame(), expected, false,
                  ThirdPartyStoragePartitioningEnabled());
  }
}

// ChromeOS doesn't support multiple profiles.
#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_P(ManagerPrefsBrowserTest,
                       NoSpecificBlockedCookieSpecs_AltRegularProfile) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  const GURL third_party_url = https_server()->GetURL(kThirdPartyHost1, "/");

  const std::string primary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url).ToString();
  const std::string secondary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();
  Metadata metadata;
  tpcd::metadata::helpers::AddEntryToMetadata(metadata, primary_pattern_spec,
                                              secondary_pattern_spec);
  EXPECT_EQ(metadata.metadata_entries_size(), 1);
  MockComponentInstallation(metadata);

  // Regular profile 1:
  {
    SimulateTrackingProtectionSettings();

    // Expected to be updated by the TPCD metadata manager instance as soon as
    // the profiles are created.
    EXPECT_THAT(
        ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS),
        testing::UnorderedElementsAreArray(
            {base::StringPrintf("[%s,%s]:%d", primary_pattern_spec.c_str(),
                                secondary_pattern_spec.c_str(), 1)}));

    bool expected = !BlockAll3pcToggleEnabled();
    EXPECT_EQ(expected, GetCookieSettings()->MitigationsEnabledFor3pcd());
    EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                  third_party_url, net::SiteForCookies(), first_party_url,
                  net::CookieSettingOverrides()),
              expected ? ContentSetting::CONTENT_SETTING_ALLOW
                       : ContentSetting::CONTENT_SETTING_BLOCK);
  }

  // Regular profile 2:
  {
    Profile* profile = browser()->profile();
    Profile* alt_profile = CreateRegularProfile();
    EXPECT_NE(profile, alt_profile);
    EXPECT_NE(profile->GetProfileKey(), alt_profile->GetProfileKey());
    Browser* browser = CreateBrowser(alt_profile);

    SimulateTrackingProtectionSettings(alt_profile);

    // Expected to be updated by the TPCD metadata manager instance as soon as
    // the profiles are created.
    EXPECT_THAT(ContentSettingsToString(
                    ContentSettingsType::TPCD_METADATA_GRANTS, alt_profile),
                testing::UnorderedElementsAreArray({base::StringPrintf(
                    "[%s,%s]:%d", primary_pattern_spec.c_str(),
                    secondary_pattern_spec.c_str(), 1)}));

    bool expected = !BlockAll3pcToggleEnabled();
    EXPECT_EQ(expected,
              GetCookieSettings(alt_profile)->MitigationsEnabledFor3pcd());
    EXPECT_EQ(
        GetCookieSettings(alt_profile)
            ->GetCookieSetting(third_party_url, net::SiteForCookies(),
                               first_party_url, net::CookieSettingOverrides()),
        expected ? ContentSetting::CONTENT_SETTING_ALLOW
                 : ContentSetting::CONTENT_SETTING_BLOCK);

    NavigateToPageWithFrame(kFirstPartyHost, browser);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html", browser);
    ExpectCookie(GetFrame(browser), expected);
    ExpectStorage(GetFrame(browser), expected, /*setting_source_user=*/false,
                  ThirdPartyStoragePartitioningEnabled());
  }
}
#endif

IN_PROC_BROWSER_TEST_P(ManagerPrefsBrowserTest,
                       NoSpecificBlockedCookieSpecs_IncognitoProfile) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  SimulateTrackingProtectionSettings();

  const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  const GURL third_party_url = https_server()->GetURL(kThirdPartyHost1, "/");

  const std::string primary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url).ToString();
  const std::string secondary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();
  Metadata metadata;
  tpcd::metadata::helpers::AddEntryToMetadata(metadata, primary_pattern_spec,
                                              secondary_pattern_spec);
  EXPECT_EQ(metadata.metadata_entries_size(), 1);
  MockComponentInstallation(metadata);

  // Regular profile:
  {
    EXPECT_THAT(
        ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS),
        testing::UnorderedElementsAreArray(
            {base::StringPrintf("[%s,%s]:%d", primary_pattern_spec.c_str(),
                                secondary_pattern_spec.c_str(), 1)}));

    bool expected = !BlockAll3pcToggleEnabled();
    EXPECT_EQ(expected, GetCookieSettings()->MitigationsEnabledFor3pcd());
    EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                  third_party_url, net::SiteForCookies(), first_party_url,
                  net::CookieSettingOverrides()),
              expected ? ContentSetting::CONTENT_SETTING_ALLOW
                       : ContentSetting::CONTENT_SETTING_BLOCK);
  }

  // Incognito profile:
  {
    Profile* incognito_profile =
        browser()->profile()->GetPrimaryOTRProfile(true);
    EXPECT_TRUE(incognito_profile->IsIncognitoProfile());
    EXPECT_TRUE(incognito_profile->IsOffTheRecord());
    EXPECT_EQ(GetTrackingProtection3pcdEnabledPref(incognito_profile), true);
    EXPECT_EQ(GetBlockAll3pcToggleEnabledPref(incognito_profile),
              BlockAll3pcToggleEnabled());
    Browser* browser = CreateBrowser(incognito_profile);

    // Expected to be left unaffected by the TPCD metadata manager instance
    // is spawned for this profile. And, the content setting will only be
    // inherited by incognito if it's less permissive.
    EXPECT_TRUE(
        ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS,
                                incognito_profile)
            .empty());

    EXPECT_FALSE(
        GetCookieSettings(incognito_profile)->MitigationsEnabledFor3pcd());
    bool expected = false;
    EXPECT_EQ(
        GetCookieSettings(incognito_profile)
            ->GetCookieSetting(third_party_url, net::SiteForCookies(),
                               first_party_url, net::CookieSettingOverrides()),
        expected ? ContentSetting::CONTENT_SETTING_ALLOW
                 : ContentSetting::CONTENT_SETTING_BLOCK);

    NavigateToPageWithFrame(kFirstPartyHost, browser);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html", browser);
    ExpectCookie(GetFrame(browser), expected);
    ExpectStorage(GetFrame(browser), expected, /*setting_source_user=*/false,
                  ThirdPartyStoragePartitioningEnabled());
  }
}

// ChromeOS doesn't support multiple profiles.
#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_P(ManagerPrefsBrowserTest,
                       NoSpecificBlockedCookieSpecs_GuestProfile) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  SimulateTrackingProtectionSettings();

  const GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  const GURL third_party_url = https_server()->GetURL(kThirdPartyHost1, "/");

  const std::string primary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(third_party_url).ToString();
  const std::string secondary_pattern_spec =
      ContentSettingsPattern::FromURLNoWildcard(first_party_url).ToString();
  Metadata metadata;
  tpcd::metadata::helpers::AddEntryToMetadata(metadata, primary_pattern_spec,
                                              secondary_pattern_spec);
  EXPECT_EQ(metadata.metadata_entries_size(), 1);
  MockComponentInstallation(metadata);

  // Regular profile:
  {
    EXPECT_THAT(
        ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS),
        testing::UnorderedElementsAreArray(
            {base::StringPrintf("[%s,%s]:%d", primary_pattern_spec.c_str(),
                                secondary_pattern_spec.c_str(), 1)}));

    bool expected = !BlockAll3pcToggleEnabled();
    EXPECT_EQ(expected, GetCookieSettings()->MitigationsEnabledFor3pcd());
    EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                  third_party_url, net::SiteForCookies(), first_party_url,
                  net::CookieSettingOverrides()),
              expected ? ContentSetting::CONTENT_SETTING_ALLOW
                       : ContentSetting::CONTENT_SETTING_BLOCK);
  }

  // Guest profile:
  {
    auto& original_guest_profile = CreateOriginalGuestProfile();
    SimulateTrackingProtectionSettings(&original_guest_profile);

    auto* guest_profile = original_guest_profile.GetPrimaryOTRProfile(
        /*create_if_needed=*/true);
    EXPECT_FALSE(guest_profile->IsRegularProfile());
    EXPECT_FALSE(guest_profile->IsIncognitoProfile());
    EXPECT_TRUE(guest_profile->IsOffTheRecord());
    EXPECT_TRUE(guest_profile->IsGuestSession());
    EXPECT_EQ(GetTrackingProtection3pcdEnabledPref(guest_profile), true);
    EXPECT_EQ(GetBlockAll3pcToggleEnabledPref(guest_profile),
              BlockAll3pcToggleEnabled());
    Browser* browser = CreateBrowser(guest_profile);

    EXPECT_THAT(ContentSettingsToString(
                    ContentSettingsType::TPCD_METADATA_GRANTS, guest_profile),
                testing::UnorderedElementsAreArray({base::StringPrintf(
                    "[%s,%s]:%d", primary_pattern_spec.c_str(),
                    secondary_pattern_spec.c_str(), 1)}));

    bool expected = !BlockAll3pcToggleEnabled();
    EXPECT_EQ(expected,
              GetCookieSettings(guest_profile)->MitigationsEnabledFor3pcd());
    EXPECT_EQ(
        GetCookieSettings(guest_profile)
            ->GetCookieSetting(third_party_url, net::SiteForCookies(),
                               first_party_url, net::CookieSettingOverrides()),
        expected ? ContentSetting::CONTENT_SETTING_ALLOW
                 : ContentSetting::CONTENT_SETTING_BLOCK);

    NavigateToPageWithFrame(kFirstPartyHost, browser);
    NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html", browser);
    ExpectCookie(GetFrame(browser), expected);
    ExpectStorage(GetFrame(browser), expected, /*setting_source_user=*/false,
                  ThirdPartyStoragePartitioningEnabled());
  }
}

class CookieControlsModePrefManagerBrowserTest : public ManagerBrowserTest {
 public:
  CookieControlsModePrefManagerBrowserTest() {
    scoped_feature_list_.InitWithFeatureStates(
        {{net::features::kForceThirdPartyCookieBlocking, false},
         {net::features::kThirdPartyStoragePartitioning, false},
         {net::features::kThirdPartyPartitionedStorageAllowedByDefault, true},
         {content_settings::features::kTrackingProtection3pcd, false}});
  }

  void AddWildcardMetadataGrant() {
    const std::string wildcard_spec = "*";
    Metadata metadata;
    // Adds a wildcard spec to both primary (third party contexts) and secondary
    // (first party contexts) pattern specs.
    tpcd::metadata::helpers::AddEntryToMetadata(
        metadata, /*primary_pattern_spec=*/wildcard_spec,
        /*secondary_pattern_spec=*/wildcard_spec);
    EXPECT_EQ(metadata.metadata_entries_size(), 1);
    MockComponentInstallation(metadata);
    EXPECT_THAT(
        ContentSettingsToString(ContentSettingsType::TPCD_METADATA_GRANTS),
        testing::ElementsAre("[*,*]:1"));
  }

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

IN_PROC_BROWSER_TEST_F(CookieControlsModePrefManagerBrowserTest,
                       DisablesMitigationsWhenThirdPartyCookiesBlocked) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  GURL first_party_url = https_server()->GetURL(kFirstPartyHost, "/");
  GURL third_party_url = https_server()->GetURL(kThirdPartyHost1, "/");

  browser()->profile()->GetPrefs()->SetInteger(
      prefs::kCookieControlsMode,
      static_cast<int>(content_settings::CookieControlsMode::kBlockThirdParty));
  AddWildcardMetadataGrant();

  EXPECT_FALSE(GetCookieSettings()->MitigationsEnabledFor3pcd());
  EXPECT_EQ(GetCookieSettings()->GetCookieSetting(
                third_party_url, net::SiteForCookies(), first_party_url,
                net::CookieSettingOverrides()),
            ContentSetting::CONTENT_SETTING_BLOCK);

  NavigateToPageWithFrame(kFirstPartyHost);
  NavigateFrameTo(kThirdPartyHost1, "/browsing_data/site_data.html");
  ExpectCookie(GetFrame(), /*expected=*/false);
  ExpectStorage(GetFrame(), /*expected=*/false, /*setting_source_user=*/false,
                /*is_3psp_enabled=*/false);
}

#endif

}  // namespace tpcd::metadata