File: privacy_sandbox_settings_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 (1138 lines) | stat: -rw-r--r-- 47,292 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/privacy_sandbox/privacy_sandbox_settings.h"

#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/metrics/statistics_recorder.h"
#include "base/notreached.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_attestations/privacy_sandbox_attestations_mixin.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/privacy_sandbox/privacy_sandbox_features.h"
#include "components/privacy_sandbox/privacy_sandbox_test_util.h"
#include "content/public/browser/browser_context.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/browsing_data_remover_test_util.h"
#include "content/public/test/fenced_frame_reporter_observer.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/shared_storage_test_utils.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_host_resolver.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "services/network/public/cpp/features.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/fenced_frame/fenced_frame_utils.h"

namespace {

// The registerAdBeacon call in
// `chrome/test/data/interest_group/bidding_logic.js` will send
// "reserved.top_navigation" and "click" events to this URL.
constexpr char kReportingURL[] = "/_report_event_server.html";
// Used for event reporting to custom destination URLs.
constexpr char kCustomReportingURL[] = "/_custom_report_event_server.html";

// Used for reportWin() destination.
constexpr char kBidderReportURL[] = "/bidder_report";

// Used for reportResult() destination.
constexpr char kSellerReportURL[] = "/seller_report";

constexpr char kPrivateAggregationHostPipeResultHistogram[] =
    "PrivacySandbox.PrivateAggregation.Host.PipeResult";

// Used to pattern match console error message emitted from
// `FencedFrameReporter::SendReportInternal()`. This error applies to
// `reportEvent()` and automatic beacons.
constexpr char kFencedFrameReportingDestinationNotAttested[] =
    "The reporting destination * is not attested for *";

// Used to pattern match console error message emitted from
// `InterestGroupAuctionReporter::CheckReportUrl()`. This error applies to
// `reportWin()` and `reportResult()`.
constexpr char kInterestGroupReportingDestinationNotAttested[] =
    "Worklet error: The reporting destination * is not attested for Protected "
    "Audience.";

// The template to run `navigator.joinAdInterestGroup()`.
// $1: The ad render url.
// $2: The bidding logic url.
// $3: Name of the interest group.
// $4: Url that a custom macro reporting beacon is allowed to be sent to.
constexpr char kJoinAdInterestGroupScript[] = R"(
  (async() => {
    const page_origin = new URL($1).origin;
    const bidding_url = new URL($2, page_origin);
    const interest_group = {
      name: $3,
      owner: page_origin,
      biddingLogicUrl: bidding_url,
      ads: [{renderURL: $1, bid: 1, allowedReportingOrigins: [$4]}],
    };

    // Pick an arbitrarily high duration to guarantee that we never leave the
    // ad interest group while the test runs. This join will fail silently
    // because of attestations failure.
    await navigator.joinAdInterestGroup(
        interest_group, /*durationSeconds=*/3000000);
  })()
)";

// The template to run `navigator.runAdAuction()`. Upon success, it also
// navigates the existing fenced frame with id "fenced_frame" in the page to the
// winning ad url.
// $1: The ad render url.
// $2: The decision logic url.
// $3: The url a reportResult beacon will be sent to if the decision logic
// is `decision_logic_report_to_seller_signals.js`.
constexpr char kRunAdAuctionAndNavigateFencedFrameScript[] = R"(
  (async() => {
    const page_origin = new URL($1).origin;
    const auction_config = {
      seller: page_origin,
      interestGroupBuyers: [page_origin],
      decisionLogicURL: new URL($2, page_origin),
      sellerSignals: {reportTo: $3}
    };
    auction_config.resolveToConfig = true;

    const fenced_frame_config = await navigator.runAdAuction(auction_config);
    if (fenced_frame_config === null) {
      return "null auction result";
    } else if (!(fenced_frame_config instanceof FencedFrameConfig)) {
      return "did not return a FencedFrameConfig";
    } else {
      document.getElementById("fenced_frame").config = fenced_frame_config;
      return "success";
    }
  })()
)";

// Print more readable logs for PrivacySandboxSettingsEventReportingBrowserTest.
auto describe_params = [](const auto& info) {
  return base::StrCat(
      {"AttestedFor_", ConvertAttestedApiStatusToString(info.param)});
};

auto console_error_filter =
    [](const content::WebContentsConsoleObserver::Message& message) {
      return message.log_level == blink::mojom::ConsoleMessageLevel::kError;
    };

}  // namespace

class PrivacySandboxSettingsBrowserTest
    : public MixinBasedInProcessBrowserTest {
 public:
  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
    https_server_.AddDefaultHandlers(GetChromeTestDataDir());

    FinishSetUp();
  }

  // TODO(crbug.com/40285326): This fails with the field trial testing config.
  void SetUpCommandLine(base::CommandLine* command_line) override {
    MixinBasedInProcessBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch("disable-field-trial-config");
  }

  // Virtual so that derived classes can delay starting the server and/or
  // register different handlers.
  virtual void FinishSetUp() {
    https_server_.RegisterRequestHandler(
        base::BindRepeating(&PrivacySandboxSettingsBrowserTest::HandleRequest,
                            base::Unretained(this)));

    content::SetupCrossSiteRedirector(&https_server_);
    ASSERT_TRUE(https_server_.Start());
  }

  std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
      const net::test_server::HttpRequest& request) {
    const GURL& url = request.GetURL();

    if (url.path() == "/clear_site_data_header_cookies") {
      auto response = std::make_unique<net::test_server::BasicHttpResponse>();
      response->AddCustomHeader("Clear-Site-Data", "\"cookies\"");
      response->set_code(net::HTTP_OK);
      response->set_content_type("text/html");
      response->set_content(std::string());
      return std::move(response);
    }

    // Use the default handler for unrelated requests.
    return nullptr;
  }

  void ClearAllCookies() {
    content::BrowsingDataRemover* remover =
        browser()->profile()->GetBrowsingDataRemover();
    content::BrowsingDataRemoverCompletionObserver observer(remover);
    remover->RemoveAndReply(
        base::Time(), base::Time::Max(),
        content::BrowsingDataRemover::DATA_TYPE_COOKIES,
        content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, &observer);
    observer.BlockUntilCompletion();
  }

  privacy_sandbox::PrivacySandboxSettings* privacy_sandbox_settings() {
    return PrivacySandboxSettingsFactory::GetForProfile(browser()->profile());
  }

  content::WebContents* web_contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

 protected:
  net::EmbeddedTestServer https_server_{
      net::test_server::EmbeddedTestServer::TYPE_HTTPS};
};

// Test that cookie clearings triggered by "Clear browsing data" will trigger
// an update to topics-data-accessible-since and invoke the corresponding
// observer method.
IN_PROC_BROWSER_TEST_F(PrivacySandboxSettingsBrowserTest, ClearAllCookies) {
  EXPECT_EQ(base::Time(),
            privacy_sandbox_settings()->TopicsDataAccessibleSince());

  privacy_sandbox_test_util::MockPrivacySandboxObserver observer;
  privacy_sandbox_settings()->AddObserver(&observer);
  EXPECT_CALL(observer, OnTopicsDataAccessibleSinceUpdated());

  ClearAllCookies();

  EXPECT_NE(base::Time(),
            privacy_sandbox_settings()->TopicsDataAccessibleSince());
}

// Test that cookie clearings triggered by Clear-Site-Data header won't trigger
// an update to topics-data-accessible-since or invoke the corresponding
// observer method.
IN_PROC_BROWSER_TEST_F(PrivacySandboxSettingsBrowserTest,
                       ClearSiteDataCookies) {
  EXPECT_EQ(base::Time(),
            privacy_sandbox_settings()->TopicsDataAccessibleSince());

  privacy_sandbox_test_util::MockPrivacySandboxObserver observer;
  privacy_sandbox_settings()->AddObserver(&observer);
  EXPECT_CALL(observer, OnTopicsDataAccessibleSinceUpdated()).Times(0);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(),
      https_server_.GetURL("a.test", "/clear_site_data_header_cookies")));

  EXPECT_EQ(base::Time(),
            privacy_sandbox_settings()->TopicsDataAccessibleSince());
}

namespace {

enum class AttestedApiStatus {
  kSharedStorage,
  kProtectedAudience,
  kProtectedAudienceAndPrivateAggregation,
  kAttributionReporting,
  kNone,
};

std::string ConvertAttestedApiStatusToString(
    AttestedApiStatus attested_api_status) {
  switch (attested_api_status) {
    case AttestedApiStatus::kSharedStorage:
      return "SharedStorage";
    case AttestedApiStatus::kProtectedAudience:
      return "ProtectedAudience";
    case AttestedApiStatus::kProtectedAudienceAndPrivateAggregation:
      return "ProtectedAudience_and_PrivateAggregation";
    case AttestedApiStatus::kAttributionReporting:
      return "AttributionReporting";
    case AttestedApiStatus::kNone:
      return "None";
    default:
      NOTREACHED();
  }
}

}  // namespace

class PrivacySandboxSettingsAttestationsBrowserTestBase
    : public PrivacySandboxSettingsBrowserTest {
 public:
  PrivacySandboxSettingsAttestationsBrowserTestBase() = default;

  content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
    return fenced_frame_test_helper_;
  }

  privacy_sandbox::PrivacySandboxAttestationsGatedAPISet
  GetAttestationsGatedAPISet(AttestedApiStatus attested_api_status) {
    switch (attested_api_status) {
      case AttestedApiStatus::kSharedStorage:
        return {privacy_sandbox::PrivacySandboxAttestationsGatedAPI::
                    kSharedStorage};
      case AttestedApiStatus::kProtectedAudience:
        return {privacy_sandbox::PrivacySandboxAttestationsGatedAPI::
                    kProtectedAudience};
      case AttestedApiStatus::kProtectedAudienceAndPrivateAggregation:
        return {privacy_sandbox::PrivacySandboxAttestationsGatedAPI::
                    kProtectedAudience,
                privacy_sandbox::PrivacySandboxAttestationsGatedAPI::
                    kPrivateAggregation};
      case AttestedApiStatus::kAttributionReporting:
        return {privacy_sandbox::PrivacySandboxAttestationsGatedAPI::
                    kAttributionReporting};
      case AttestedApiStatus::kNone:
        return {};
      default:
        NOTREACHED();
    }
  }

  void SetAttestations(std::vector<std::pair<std::string, AttestedApiStatus>>
                           hostname_strings_with_attestation_statuses) {
    privacy_sandbox::PrivacySandboxAttestationsMap attestations_map;
    for (const auto& hostname_and_status :
         hostname_strings_with_attestation_statuses) {
      attestations_map[net::SchemefulSite(
          https_server_.GetOrigin(hostname_and_status.first))] =
          GetAttestationsGatedAPISet(hostname_and_status.second);
    }
    privacy_sandbox::PrivacySandboxAttestations::GetInstance()
        ->SetAttestationsForTesting(std::move(attestations_map));
  }

  // Navigates the main frame, loads a fenced frame, then navigates the fenced
  // frame by joining an ad interest group, running an ad auction, and setting
  // the fenced frame's config to be the result of the auction.
  // Note: The bidding and decision urls used in
  // `NavigateFencedFrameUsingFledge()` are pointing to files under
  // "content/test/data". This test file is in "browser/", so if the script is
  // copied and directly executed here, the bidding and decision urls will be
  // referring to files under "chrome/test/data".
  content::RenderFrameHost* LoadPageThenLoadAndNavigateFencedFrameViaAdAuction(
      const GURL& initial_url,
      const GURL& fenced_frame_url) {
    if (!ui_test_utils::NavigateToURL(browser(), initial_url)) {
      return nullptr;
    }

    EXPECT_TRUE(
        ExecJs(web_contents()->GetPrimaryMainFrame(),
               "var fenced_frame = document.createElement('fencedframe');"
               "fenced_frame.id = 'fenced_frame';"
               "document.body.appendChild(fenced_frame);"));
    auto* fenced_frame_rfh =
        fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
            web_contents()->GetPrimaryMainFrame());
    content::TestFrameNavigationObserver observer(fenced_frame_rfh);
    fenced_frame_test_helper().NavigateFencedFrameUsingFledge(
        web_contents()->GetPrimaryMainFrame(), fenced_frame_url,
        "fenced_frame");
    observer.Wait();

    // Embedder-initiated fenced frame navigation uses a new browsing instance.
    // Fenced frame RenderFrameHost is a new one after navigation, so we need
    // to retrieve it.
    return fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
        web_contents()->GetPrimaryMainFrame());
  }

  content::RenderFrameHost*
  LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionWithPrivateAggregation(
      const std::string& primary_main_frame_hostname,
      const std::string& fenced_frame_hostname) {
    GURL initial_url(https_server_.GetURL(
        primary_main_frame_hostname,
        "/allow-all-join-ad-interest-group-run-ad-auction.html"));
    GURL fenced_frame_url(https_server_.GetURL(
        fenced_frame_hostname,
        "/fenced_frames/"
        "ad_with_fenced_frame_private_aggregation_reporting.html"));

    return LoadPageThenLoadAndNavigateFencedFrameViaAdAuction(initial_url,
                                                              fenced_frame_url);
  }

  content::RenderFrameHost*
  LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionForEventReporting() {
    GURL initial_url(https_server_.GetURL("a.test", "/empty.html"));
    GURL fenced_frame_url(
        https_server_.GetURL("a.test", "/fenced_frames/title1.html"));

    return LoadPageThenLoadAndNavigateFencedFrameViaAdAuction(initial_url,
                                                              fenced_frame_url);
  }

 private:
  privacy_sandbox::PrivacySandboxAttestationsMixin
      privacy_sandbox_attestations_mixin_{&mixin_host_};
  content::test::FencedFrameTestHelper fenced_frame_test_helper_;
};

class PrivacySandboxSettingsEventReportingBrowserTest
    : public PrivacySandboxSettingsAttestationsBrowserTestBase,
      public testing::WithParamInterface<AttestedApiStatus> {
 public:
  PrivacySandboxSettingsEventReportingBrowserTest() = default;

  void FinishSetUp() override {
    // Do not start the https server at this point to allow the tests to set up
    // response listeners.
  }

  void SetUpOnMainThread() override {
    // Allows all Privacy Sandbox prefs for testing.
    privacy_sandbox_settings()->SetAllPrivacySandboxAllowedForTesting();
    EXPECT_TRUE(
        privacy_sandbox_settings()->IsAttributionReportingEverAllowed());

    // Set up the observer to listen for console error messages.
    PrivacySandboxSettingsAttestationsBrowserTestBase::SetUpOnMainThread();
    console_error_observer_ =
        std::make_unique<content::WebContentsConsoleObserver>(web_contents());
    console_error_observer_->SetFilter(
        base::BindRepeating(console_error_filter));
  }

  AttestedApiStatus GetReportingDestinationAttestationStatus() {
    return GetParam();
  }

  bool IsReportingDestinationEnrolled() {
    return GetReportingDestinationAttestationStatus() ==
           AttestedApiStatus::kProtectedAudience;
  }

 protected:
  std::unique_ptr<content::WebContentsConsoleObserver> console_error_observer_;
};

IN_PROC_BROWSER_TEST_P(PrivacySandboxSettingsEventReportingBrowserTest,
                       AutomaticBeaconDestinationEnrollment) {
  // In order to check events reported over the network, we register an HTTP
  // response interceptor for each reportEvent request we expect.
  net::test_server::ControllableHttpResponse response(&https_server_,
                                                      kReportingURL);

  ASSERT_TRUE(https_server_.Start());

  // Set automatic beacon reporting destination to be attested according to the
  // test parameter.
  SetAttestations(
      {std::make_pair("a.test", AttestedApiStatus::kProtectedAudience),
       std::make_pair("d.test", GetReportingDestinationAttestationStatus())});

  content::RenderFrameHost* fenced_frame_rfh =
      LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionForEventReporting();
  ASSERT_NE(fenced_frame_rfh, nullptr);

  // Set the automatic beacon.
  constexpr char kBeaconMessage[] = "this is the message";

  // Install the beacon observer to observe whether the beacon is queued to be
  // sent later.
  std::unique_ptr<content::test::FencedFrameReporterObserverForTesting>
      beacon_observer = content::test::InstallFencedFrameReporterObserver(
          fenced_frame_rfh,
          content::AutomaticBeaconEvent(
              blink::mojom::AutomaticBeaconType::kDeprecatedTopNavigation,
              kBeaconMessage));

  // Listen to the console error message from
  // `FencedFrameReporter::SendReportInternal()`.
  console_error_observer_->SetPattern(
      kFencedFrameReportingDestinationNotAttested);

  EXPECT_TRUE(ExecJs(
      fenced_frame_rfh,
      content::JsReplace(R"(
      window.fence.setReportEventDataForAutomaticBeacons({
        eventType: $1,
        eventData: $2,
        destination: ['buyer']
      });
    )",
                         blink::kDeprecatedFencedFrameTopNavigationBeaconType,
                         kBeaconMessage)));

  // Commit a top-level navigation.
  GURL navigation_url(https_server_.GetURL("a.test", "/title2.html"));
  EXPECT_TRUE(
      ExecJs(fenced_frame_rfh,
             content::JsReplace("window.open($1, '_blank');", navigation_url)));

  if (IsReportingDestinationEnrolled()) {
    // The automatic beacon destination is considered enrolled if attested for
    // Protected Audience.
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->content, kBeaconMessage);
  } else {
    // The console error is ignored if the reporting event is queued to be sent
    // later when fenced frame url mapping is ready.
    if (!beacon_observer->IsReportingEventQueued()) {
      // The console message should state different attestation requirement
      // based on the feature toggle.
      ASSERT_TRUE(console_error_observer_->Wait());
      EXPECT_EQ(console_error_observer_->messages().size(), 1u);
      EXPECT_TRUE(base::Contains(console_error_observer_->GetMessageAt(0u),
                                 "Protected Audience"));
    }

    // Verify the automatic beacon was not sent.
    fenced_frame_test_helper().SendBasicRequest(
        web_contents(), https_server_.GetURL("d.test", kReportingURL),
        "response");
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->content, "response");
  }
}

IN_PROC_BROWSER_TEST_P(PrivacySandboxSettingsEventReportingBrowserTest,
                       ReportEventDestinationEnrollment) {
  // In order to check events reported over the network, we register an HTTP
  // response interceptor for each reportEvent request we expect.
  net::test_server::ControllableHttpResponse response(&https_server_,
                                                      kReportingURL);

  ASSERT_TRUE(https_server_.Start());

  // Set reportEvent reporting destination to be attested according to the
  // test parameter.
  SetAttestations(
      {std::make_pair("a.test", AttestedApiStatus::kProtectedAudience),
       std::make_pair("d.test", GetReportingDestinationAttestationStatus())});

  content::RenderFrameHost* fenced_frame_rfh =
      LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionForEventReporting();
  ASSERT_NE(fenced_frame_rfh, nullptr);

  // Send the report to an enum destination.
  constexpr char kBeaconMessage[] = "this is the message";
  constexpr char kEventType[] = "click";

  // Install the beacon observer to observe whether the beacon is queued to be
  // sent later.
  std::unique_ptr<content::test::FencedFrameReporterObserverForTesting>
      beacon_observer = content::test::InstallFencedFrameReporterObserver(
          fenced_frame_rfh,
          content::DestinationEnumEvent(kEventType, kBeaconMessage));

  // Listen to the console error message from
  // `FencedFrameReporter::SendReportInternal()`.
  console_error_observer_->SetPattern(
      kFencedFrameReportingDestinationNotAttested);

  EXPECT_TRUE(
      ExecJs(fenced_frame_rfh, content::JsReplace(R"(
      window.fence.reportEvent({
        eventType: $1,
        eventData: $2,
        destination: ['buyer']
      });
    )",
                                                  kEventType, kBeaconMessage)));

  if (IsReportingDestinationEnrolled()) {
    // The reportEvent beacon destination is considered enrolled if attested for
    // Protected Audience.
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->content, kBeaconMessage);
  } else {
    // The console error is ignored if the reporting event is queued to be sent
    // later when fenced frame url mapping is ready.
    if (!beacon_observer->IsReportingEventQueued()) {
      // The console message should state different attestation requirement
      // based on the feature toggle.
      ASSERT_TRUE(console_error_observer_->Wait());
      EXPECT_EQ(console_error_observer_->messages().size(), 1u);
      EXPECT_TRUE(base::Contains(console_error_observer_->GetMessageAt(0u),
                                 "Protected Audience"));
    }

    // Verify the reportEvent beacon was not sent.
    fenced_frame_test_helper().SendBasicRequest(
        web_contents(), https_server_.GetURL("d.test", kReportingURL),
        "response");
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->content, "response");
  }
}

IN_PROC_BROWSER_TEST_P(PrivacySandboxSettingsEventReportingBrowserTest,
                       ReportEventCustomURLDestinationEnrollment) {
  // In order to check events reported over the network, we register an HTTP
  // response interceptor for each reportEvent request we expect.
  net::test_server::ControllableHttpResponse response(&https_server_,
                                                      kCustomReportingURL);

  ASSERT_TRUE(https_server_.Start());

  // Set custom url reporting destination to be attested according to the
  // test parameter.
  SetAttestations(
      {std::make_pair("a.test", AttestedApiStatus::kProtectedAudience),
       std::make_pair("d.test", GetReportingDestinationAttestationStatus())});

  GURL initial_url(https_server_.GetURL("a.test", "/empty.html"));
  GURL fenced_frame_url(
      https_server_.GetURL("a.test", "/fenced_frames/title1.html"));

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), initial_url));

  // Create the fenced frame.
  EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                     "var fenced_frame = document.createElement('fencedframe');"
                     "fenced_frame.id = 'fenced_frame';"
                     "document.body.appendChild(fenced_frame);"));
  content::RenderFrameHost* fenced_frame_rfh =
      fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
          web_contents()->GetPrimaryMainFrame());
  content::TestFrameNavigationObserver observer(fenced_frame_rfh);

  // Send the report to a custom URL destination.
  GURL destination_url = https_server_.GetURL("d.test", kCustomReportingURL);

  EXPECT_TRUE(
      ExecJs(web_contents()->GetPrimaryMainFrame(),
             content::JsReplace(kJoinAdInterestGroupScript, fenced_frame_url,
                                "/interest_group/bidding_logic.js", "testAd",
                                destination_url)));

  content::EvalJsResult auction_result =
      EvalJs(web_contents()->GetPrimaryMainFrame(),
             content::JsReplace(kRunAdAuctionAndNavigateFencedFrameScript,
                                fenced_frame_url,
                                "/interest_group/decision_logic.js", ""));

  if (IsReportingDestinationEnrolled()) {
    // The custom url destination is considered enrolled if attested for
    // Protected Audience.
    ASSERT_EQ(auction_result.ExtractString(), "success");

    observer.Wait();
    ASSERT_EQ(observer.last_committed_url(), fenced_frame_url);

    // Embedder-initiated fenced frame navigation uses a new browsing instance.
    // Fenced frame RenderFrameHost is a new one after navigation, so we need
    // to retrieve it.
    fenced_frame_rfh =
        fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
            web_contents()->GetPrimaryMainFrame());
    ASSERT_NE(fenced_frame_rfh, nullptr);

    // Send the beacon.
    EXPECT_TRUE(ExecJs(fenced_frame_rfh, content::JsReplace(R"(
      window.fence.reportEvent({destinationURL: $1});
    )",
                                                            destination_url)));

    // Verify the beacon was sent as a GET request.
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->method, net::test_server::METHOD_GET);
  } else {
    // Joining ad interest group an url that is not enrolled in
    // `allowedReportingOrigins` will fail silently. The auction later will not
    // return a winning ad.
    // TODO(xiaochenzh): The current behavior for `joinAdInterestGroup()` when
    // urls in `allowedReportingOrigins` are not attested is to fail silently.
    // Soon an error message will be added. This test should be updated to
    // listen to this error then.
    ASSERT_EQ(auction_result, "null auction result");

    // Verify the beacon was not sent.
    fenced_frame_test_helper().SendBasicRequest(
        web_contents(), https_server_.GetURL("d.test", kCustomReportingURL),
        "response");
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->content, "response");
  }
}

// For beacons from `reportWin()`, the reporting destination is considered
// enrolled if and only if it is attested for Protected Audience. The relaxed
// attestations requirement of either Protected Audience or Attribution
// Reporting for post-impression beacons from M120 should not apply to beacons
// from `reportWin()`.
IN_PROC_BROWSER_TEST_P(PrivacySandboxSettingsEventReportingBrowserTest,
                       ReportWinDestinationEnrollment) {
  // In order to check events reported over the network, we register an HTTP
  // response interceptor for each reporting beacon we expect.
  net::test_server::ControllableHttpResponse response(&https_server_,
                                                      kBidderReportURL);
  ASSERT_TRUE(https_server_.Start());

  // Set `reportWin()` reporting destination to be attested according to the
  // test parameter.
  SetAttestations(
      {std::make_pair("a.test", AttestedApiStatus::kProtectedAudience),
       std::make_pair("b.test", GetReportingDestinationAttestationStatus())});

  GURL initial_url(https_server_.GetURL("a.test", "/empty.html"));
  GURL fenced_frame_url(
      https_server_.GetURL("a.test", "/fenced_frames/title1.html"));

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), initial_url));

  // Create the fenced frame.
  EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                     "var fenced_frame = document.createElement('fencedframe');"
                     "fenced_frame.id = 'fenced_frame';"
                     "document.body.appendChild(fenced_frame);"));
  content::RenderFrameHost* fenced_frame_rfh =
      fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
          web_contents()->GetPrimaryMainFrame());
  content::TestFrameNavigationObserver observer(fenced_frame_rfh);

  // The `reportWin()` beacon will be attempted to send to this url.
  GURL bidder_report_to_url = https_server_.GetURL("b.test", kBidderReportURL);

  // Listen to the console error message from
  // `InterestGroupAuctionReporter::CheckReportUrl()`.
  console_error_observer_->SetPattern(
      kInterestGroupReportingDestinationNotAttested);

  // Run the ad auction with the bidding url `bidding_logic_report_to_name.js`.
  // This auction will attempt to send a `reportWin()` to the url in the
  // InterestGroup name.
  EXPECT_TRUE(ExecJs(
      web_contents()->GetPrimaryMainFrame(),
      content::JsReplace(kJoinAdInterestGroupScript, fenced_frame_url,
                         "/interest_group/bidding_logic_report_to_name.js",
                         bidder_report_to_url, fenced_frame_url)));

  content::EvalJsResult auction_result =
      EvalJs(web_contents()->GetPrimaryMainFrame(),
             content::JsReplace(kRunAdAuctionAndNavigateFencedFrameScript,
                                fenced_frame_url,
                                "/interest_group/decision_logic.js", ""));

  if (IsReportingDestinationEnrolled()) {
    // For beacons from `reportWin()`, the reporting destination is considered
    // enrolled if and only if it is attested for Protected Audience.
    ASSERT_EQ(auction_result.ExtractString(), "success");

    observer.Wait();
    ASSERT_EQ(observer.last_committed_url(), fenced_frame_url);

    // Verify the `reportWin()` beacon was sent.
    response.WaitForRequest();
    EXPECT_FALSE(response.http_request()->has_content);
    EXPECT_EQ(response.http_request()->method,
              net::test_server::HttpMethod::METHOD_GET);
  } else {
    // Verify the console messages states to require Protected Audience only.
    // Note that two console messages are sent due to debug and normal
    // reporting.
    ASSERT_TRUE(console_error_observer_->Wait());
    EXPECT_EQ(console_error_observer_->messages().size(), 2u);
    EXPECT_TRUE(base::Contains(console_error_observer_->GetMessageAt(0u),
                               "Protected Audience"));
    EXPECT_FALSE(base::Contains(console_error_observer_->GetMessageAt(0u),
                                "Attribution Reporting"));
    EXPECT_TRUE(base::Contains(console_error_observer_->GetMessageAt(1u),
                               "Protected Audience"));
    EXPECT_FALSE(base::Contains(console_error_observer_->GetMessageAt(1u),
                                "Attribution Reporting"));

    // Verify the `reportWin()` beacon was not sent.
    fenced_frame_test_helper().SendBasicRequest(
        web_contents(), bidder_report_to_url, "response");
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->content, "response");
  }
}

// For beacons from `reportResult()`, the reporting destination is considered
// enrolled if and only if it is attested for Protected Audience. The relaxed
// attestations requirement of either Protected Audience or Attribution
// Reporting for post-impression beacons from M120 should not apply to beacons
// from `reportResult()`.
IN_PROC_BROWSER_TEST_P(PrivacySandboxSettingsEventReportingBrowserTest,
                       ReportResultDestinationEnrollment) {
  // In order to check events reported over the network, we register an HTTP
  // response interceptor for each reporting beacon we expect.
  net::test_server::ControllableHttpResponse response(&https_server_,
                                                      kSellerReportURL);
  ASSERT_TRUE(https_server_.Start());

  // Set `reportResult()` reporting destination to be attested according to the
  // test parameter.
  SetAttestations(
      {std::make_pair("a.test", AttestedApiStatus::kProtectedAudience),
       std::make_pair("b.test", GetReportingDestinationAttestationStatus())});

  GURL initial_url(https_server_.GetURL("a.test", "/empty.html"));
  GURL fenced_frame_url(
      https_server_.GetURL("a.test", "/fenced_frames/title1.html"));

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), initial_url));

  // Create the fenced frame.
  EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                     "var fenced_frame = document.createElement('fencedframe');"
                     "fenced_frame.id = 'fenced_frame';"
                     "document.body.appendChild(fenced_frame);"));
  content::RenderFrameHost* fenced_frame_rfh =
      fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
          web_contents()->GetPrimaryMainFrame());
  content::TestFrameNavigationObserver observer(fenced_frame_rfh);

  // The `ReportResult()` beacon will be attempted to send to this url.
  GURL seller_report_to_url = https_server_.GetURL("b.test", kSellerReportURL);

  // Listen to the console error message from
  // `InterestGroupAuctionReporter::CheckReportUrl()`.
  console_error_observer_->SetPattern(
      kInterestGroupReportingDestinationNotAttested);

  // Run the ad auction with the decision url
  // `decision_logic_report_to_seller_signals.js`. This auction will attempt to
  // send a `ReportResult()` beacon to the url in the sellerSignals.
  EXPECT_TRUE(
      ExecJs(web_contents()->GetPrimaryMainFrame(),
             content::JsReplace(kJoinAdInterestGroupScript, fenced_frame_url,
                                "/interest_group/bidding_logic.js", "testAd",
                                fenced_frame_url)));

  content::EvalJsResult auction_result =
      EvalJs(web_contents()->GetPrimaryMainFrame(),
             content::JsReplace(
                 kRunAdAuctionAndNavigateFencedFrameScript, fenced_frame_url,
                 "/interest_group/decision_logic_report_to_seller_signals.js",
                 seller_report_to_url));

  if (IsReportingDestinationEnrolled()) {
    // For beacons from `reportResult()`, the reporting destination is
    // considered enrolled if and only if it is attested for Protected Audience.
    ASSERT_EQ(auction_result.ExtractString(), "success");

    observer.Wait();
    ASSERT_EQ(observer.last_committed_url(), fenced_frame_url);

    // Verify the `reportResult()` beacon was sent.
    response.WaitForRequest();
    EXPECT_FALSE(response.http_request()->has_content);
    EXPECT_EQ(response.http_request()->method,
              net::test_server::HttpMethod::METHOD_GET);
  } else {
    // Verify the console message states to require Protected Audience only.
    // Note that two console messages are sent due to debug and normal
    // reporting.
    ASSERT_TRUE(console_error_observer_->Wait());
    EXPECT_EQ(console_error_observer_->messages().size(), 2u);
    EXPECT_TRUE(base::Contains(console_error_observer_->GetMessageAt(0u),
                               "Protected Audience"));
    EXPECT_FALSE(base::Contains(console_error_observer_->GetMessageAt(0u),
                                "Attribution Reporting"));
    EXPECT_TRUE(base::Contains(console_error_observer_->GetMessageAt(1u),
                               "Protected Audience"));
    EXPECT_FALSE(base::Contains(console_error_observer_->GetMessageAt(1u),
                                "Attribution Reporting"));

    // Verify the `reportResult()` beacon was not sent.
    fenced_frame_test_helper().SendBasicRequest(
        web_contents(), seller_report_to_url, "response");
    response.WaitForRequest();
    EXPECT_EQ(response.http_request()->content, "response");
  }
}

INSTANTIATE_TEST_SUITE_P(
    PrivacySandboxSettingsEventReportingBrowserTest,
    PrivacySandboxSettingsEventReportingBrowserTest,
    testing::Values(AttestedApiStatus::kProtectedAudience,
                    AttestedApiStatus::kAttributionReporting,
                    AttestedApiStatus::kNone),
    describe_params);

class PrivacySandboxSettingsAttestProtectedAudienceBrowserTest
    : public PrivacySandboxSettingsAttestationsBrowserTestBase {
 public:
  PrivacySandboxSettingsAttestProtectedAudienceBrowserTest() {
    feature_list_.InitWithFeatures(
        /*enabled_features=*/
        {network::features::kInterestGroupStorage,
         blink::features::kAdInterestGroupAPI, blink::features::kFledge,
         blink::features::kFledgeBiddingAndAuctionServer,
         blink::features::kFencedFrames,
         blink::features::kFencedFramesAPIChanges,
         privacy_sandbox::kOverridePrivacySandboxSettingsLocalTesting},
        /*disabled_features=*/{});
  }

  void FinishSetUp() override {
    https_server_.RegisterRequestHandler(base::BindRepeating(
        &PrivacySandboxSettingsAttestProtectedAudienceBrowserTest::
            HandleWellKnownRequest,
        base::Unretained(this)));
    content::SetupCrossSiteRedirector(&https_server_);
    ASSERT_TRUE(https_server_.Start());
  }

  std::unique_ptr<net::test_server::HttpResponse> HandleWellKnownRequest(
      const net::test_server::HttpRequest& request) {
    if (!base::StartsWith(request.relative_url,
                          "/.well-known/interest-group/permissions/?origin=")) {
      return nullptr;
    }

    // .well-known requests should advertise they accept JSON responses.
    const auto accept_header =
        request.headers.find(net::HttpRequestHeaders::kAccept);
    CHECK(accept_header != request.headers.end());
    EXPECT_EQ(accept_header->second, "application/json");

    auto response = std::make_unique<net::test_server::BasicHttpResponse>();
    response->set_content_type("application/json");
    response->set_content(R"({"joinAdInterestGroup" : true})");
    response->AddCustomHeader("Access-Control-Allow-Origin", "*");
    return response;
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

class
    PrivacySandboxSettingsAttestPrivateAggregationInProtectedAudienceBrowserTest
    : public PrivacySandboxSettingsAttestProtectedAudienceBrowserTest {
 public:
  PrivacySandboxSettingsAttestPrivateAggregationInProtectedAudienceBrowserTest() {
    feature_list_.InitWithFeatures(
        /*enabled_features=*/
        {blink::features::kPrivateAggregationApi},
        /*disabled_features=*/{});
  }

  size_t GetTotalSampleCount(std::string_view histogram_name) {
    auto buckets = histogram_tester_.GetAllSamples(histogram_name);
    size_t count = 0;
    for (const auto& bucket : buckets) {
      count += bucket.count;
    }
    return count;
  }

  void WaitForHistogram(const std::string& histogram_name,
                        size_t expected_sample_count) {
    // Continue if histogram was already recorded and has at least the expected
    // number of samples.
    if (base::StatisticsRecorder::FindHistogram(histogram_name) &&
        GetTotalSampleCount(histogram_name) >= expected_sample_count) {
      return;
    }

    // Else, wait until the histogram is recorded with enough samples.
    base::RunLoop run_loop;
    auto histogram_observer = std::make_unique<
        base::StatisticsRecorder::ScopedHistogramSampleObserver>(
        histogram_name,
        base::BindLambdaForTesting([&](std::string_view histogram_name,
                                       uint64_t name_hash,
                                       base::HistogramBase::Sample32 sample) {
          if (GetTotalSampleCount(histogram_name) >= expected_sample_count) {
            run_loop.Quit();
          }
        }));
    run_loop.Run();
  }

 protected:
  base::HistogramTester histogram_tester_;

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(
    PrivacySandboxSettingsAttestPrivateAggregationInProtectedAudienceBrowserTest,
    SameOrigin_Enrolled_Success) {
  SetAttestations({std::make_pair(
      "a.test", AttestedApiStatus::kProtectedAudienceAndPrivateAggregation)});

  content::RenderFrameHost* fenced_frame_rfh =
      LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionWithPrivateAggregation(
          /*primary_main_frame_hostname=*/"a.test",
          /*fenced_frame_hostname=*/"a.test");
  ASSERT_NE(fenced_frame_rfh, nullptr);

  WaitForHistogram(kPrivateAggregationHostPipeResultHistogram, 2);
  histogram_tester_.ExpectUniqueSample(
      kPrivateAggregationHostPipeResultHistogram,
      content::GetPrivateAggregationHostPipeReportSuccessValue(), 2);
}

IN_PROC_BROWSER_TEST_F(
    PrivacySandboxSettingsAttestPrivateAggregationInProtectedAudienceBrowserTest,
    SameOrigin_NotEnrolled_Failure) {
  SetAttestations(
      {std::make_pair("a.test", AttestedApiStatus::kProtectedAudience)});

  content::RenderFrameHost* fenced_frame_rfh =
      LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionWithPrivateAggregation(
          /*primary_main_frame_hostname=*/"a.test",
          /*fenced_frame_hostname=*/"a.test");
  ASSERT_NE(fenced_frame_rfh, nullptr);

  WaitForHistogram(kPrivateAggregationHostPipeResultHistogram, 2);
  histogram_tester_.ExpectUniqueSample(
      kPrivateAggregationHostPipeResultHistogram,
      content::GetPrivateAggregationHostPipeApiDisabledValue(), 2);
}

// Verifies that joining interest groups and running auctions in the Protected
// Audience API are subject to attestation checks.
//
// navigtor.joinAdInterestGroup() doesn't have a separate attestation from
// navigator.runAdAuction() -- they both check the same kProtectedAudience
// attestation.
IN_PROC_BROWSER_TEST_F(PrivacySandboxSettingsAttestProtectedAudienceBrowserTest,
                       Join_RunAdAuction_Enrollment) {

  struct TestCase {
    AttestedApiStatus join_origin_attestation;
    AttestedApiStatus run_origin_attestation;
    bool expect_auction_succeeds;
  } kTestCases[] = {
      {/*join_origin_attestation=*/AttestedApiStatus::kProtectedAudience,
       /*run_origin_attestation=*/AttestedApiStatus::kProtectedAudience,
       /*expect_auction_succeeds=*/true},
      {/*join_origin_attestation=*/AttestedApiStatus::kSharedStorage,
       AttestedApiStatus::kProtectedAudience,
       /*expect_auction_succeeds=*/false},
      {/*join_origin_attestation=*/AttestedApiStatus::kProtectedAudience,
       /*run_origin_attestation=*/AttestedApiStatus::kSharedStorage,
       /*expect_auction_succeeds=*/false},
      {/*join_origin_attestation=*/AttestedApiStatus::kSharedStorage,
       /*run_origin_attestation=*/AttestedApiStatus::kSharedStorage,
       /*expect_auction_succeeds=*/false},
  };
  for (const auto test_case : kTestCases) {
    SCOPED_TRACE(::testing::Message()
                 << "Join origin attestation "
                 << static_cast<int>(test_case.join_origin_attestation)
                 << " run origin attestation "
                 << static_cast<int>(test_case.run_origin_attestation));
    SetAttestations(
        {std::make_pair("a.test", test_case.join_origin_attestation),
         std::make_pair("b.test", test_case.run_origin_attestation)});

    const GURL join_page = https_server_.GetURL("a.test", "/echo");
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), join_page));

    EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                       content::JsReplace(R"(
      (async() => {
        const FLEDGE_BIDDING_URL = "/interest_group/bidding_logic.js";

        const page_origin = new URL($1).origin;
        const bidding_url = new URL(FLEDGE_BIDDING_URL, page_origin);
        const interest_group = {
          name: 'testAd1',
          owner: page_origin,
          biddingLogicUrl: bidding_url,
          ads: [{renderURL: $1, bid: 1}],
        };

        // Pick an arbitrarily high duration to guarantee that we never leave
        // the ad interest group while the test runs.
        await navigator.joinAdInterestGroup(
            interest_group, /*durationSeconds=*/3000000);
      })())",
                                          join_page)));

    const GURL auction_page = https_server_.GetURL("b.test", "/echo");
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), auction_page));

    content::EvalJsResult result =
        EvalJs(web_contents()->GetPrimaryMainFrame(),
               content::JsReplace(R"(
      (async() => {
          const FLEDGE_DECISION_URL = "/interest_group/decision_logic.js";

          const page_origin = new URL($1).origin;
          const join_origin = new URL($2).origin;
          const auction_config = {
            seller: page_origin,
            interestGroupBuyers: [join_origin],
            decisionLogicURL: new URL(FLEDGE_DECISION_URL, page_origin),
          };

          return await navigator.runAdAuction(auction_config);
      })())",
                                  auction_page, join_page));
    if (test_case.expect_auction_succeeds) {
      EXPECT_NE(nullptr, result);
    } else {
      EXPECT_EQ(nullptr, result);
    }
  }
}

IN_PROC_BROWSER_TEST_F(
    PrivacySandboxSettingsAttestPrivateAggregationInProtectedAudienceBrowserTest,
    CrossOrigin_Enrolled_Success) {
  SetAttestations(
      {std::make_pair(
           "a.test",
           AttestedApiStatus::kProtectedAudienceAndPrivateAggregation),
       std::make_pair(
           "b.test",
           AttestedApiStatus::kProtectedAudienceAndPrivateAggregation)});

  content::RenderFrameHost* fenced_frame_rfh =
      LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionWithPrivateAggregation(
          /*primary_main_frame_hostname=*/"a.test",
          /*fenced_frame_hostname=*/"b.test");
  ASSERT_NE(fenced_frame_rfh, nullptr);

  WaitForHistogram(kPrivateAggregationHostPipeResultHistogram, 2);
  histogram_tester_.ExpectUniqueSample(
      kPrivateAggregationHostPipeResultHistogram,
      content::GetPrivateAggregationHostPipeReportSuccessValue(), 2);
}

IN_PROC_BROWSER_TEST_F(
    PrivacySandboxSettingsAttestPrivateAggregationInProtectedAudienceBrowserTest,
    CrossOrigin_NotEnrolled_Failure) {
  SetAttestations(
      {std::make_pair(
           "a.test",
           AttestedApiStatus::kProtectedAudienceAndPrivateAggregation),
       std::make_pair("b.test", AttestedApiStatus::kProtectedAudience)});

  content::RenderFrameHost* fenced_frame_rfh =
      LoadPageThenLoadAndNavigateFencedFrameViaAdAuctionWithPrivateAggregation(
          /*primary_main_frame_hostname=*/"a.test",
          /*fenced_frame_hostname=*/"b.test");
  ASSERT_NE(fenced_frame_rfh, nullptr);

  WaitForHistogram(kPrivateAggregationHostPipeResultHistogram, 2);
  histogram_tester_.ExpectUniqueSample(
      kPrivateAggregationHostPipeResultHistogram,
      content::GetPrivateAggregationHostPipeApiDisabledValue(), 2);
}