File: privacy_budget_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (862 lines) | stat: -rw-r--r-- 34,154 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
// 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 <array>
#include <cstdint>
#include <iosfwd>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <utility>
#include <vector>

#include "base/barrier_closure.h"
#include "base/containers/flat_set.h"
#include "base/feature_list.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "chrome/browser/privacy_budget/identifiability_study_state.h"
#include "chrome/browser/privacy_budget/privacy_budget_browsertest_util.h"
#include "chrome/browser/privacy_budget/privacy_budget_prefs.h"
#include "chrome/common/privacy_budget/privacy_budget_features.h"
#include "chrome/common/privacy_budget/scoped_privacy_budget_config.h"
#include "chrome/common/privacy_budget/types.h"
#include "chrome/test/base/platform_browser_test.h"
#include "components/prefs/pref_service.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/ukm/ukm_recorder_observer.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "mojo/public/cpp/bindings/struct_ptr.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/metrics/public/mojom/ukm_interface.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_token.h"
#include "third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom-shared.h"
#include "url/gurl.h"

class Profile;

namespace ukm {
class UkmService;
}  // namespace ukm

namespace {

using testing::_;
using testing::AllOf;
using testing::Contains;
using testing::Each;
using testing::Field;
using testing::IsSupersetOf;
using testing::Key;
using testing::Pair;
using testing::UnorderedElementsAreArray;

MATCHER_P(Type, type, "") {
  return blink::IdentifiableSurface::FromMetricHash(arg).GetType() == type;
}

constexpr uint64_t HashFeature(const blink::mojom::WebFeature& feature) {
  return blink::IdentifiableSurface::FromTypeAndToken(
             blink::IdentifiableSurface::Type::kWebFeature, feature)
      .ToUkmMetricHash();
}

class EnableRandomSampling {
 public:
  EnableRandomSampling()
      : privacy_budget_config_(
            test::ScopedPrivacyBudgetConfig::Presets::kEnableRandomSampling) {}

 private:
  test::ScopedPrivacyBudgetConfig privacy_budget_config_;
};

class PrivacyBudgetBrowserTestEnableRandomSampling
    : private EnableRandomSampling,
      public PlatformBrowserTest {};

class PrivacyBudgetBrowserTestWithTestRecorder
    : private EnableRandomSampling,
      public PrivacyBudgetBrowserTestBaseWithTestRecorder {};

}  // namespace

IN_PROC_BROWSER_TEST_F(PrivacyBudgetBrowserTestEnableRandomSampling,
                       BrowserSideSettingsIsActive) {
  ASSERT_TRUE(base::FeatureList::IsEnabled(features::kIdentifiabilityStudy));
  const auto* settings = blink::IdentifiabilityStudySettings::Get();
  EXPECT_TRUE(settings->IsActive());
}

IN_PROC_BROWSER_TEST_F(PrivacyBudgetBrowserTestWithTestRecorder, SamplingAPIs) {
  ASSERT_TRUE(embedded_test_server()->Start());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  // We expect 3 entries here generated by the two navigations from the test.
  // The first navigation adds a document created entry and a web feature entry,
  // while the second one generates only a document created entry.
  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   BarrierClosure(3u, run_loop.QuitClosure()));

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(
                          "/privacy_budget/samples_some_surfaces.html")));

  // The document calls a bunch of instrumented functions and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed.
  std::string scraped_apis;
  ASSERT_TRUE(messages.WaitForMessage(&scraped_apis));

  // The contents of the received message isn't used for anything other than
  // diagnostics.
  SCOPED_TRACE(scraped_apis);

  // Navigating away from the test page causes the document to be unloaded. That
  // will cause any buffered metrics to be flushed.
  content::NavigateToURLBlockUntilNavigationsComplete(web_contents(),
                                                      GURL("about:blank"), 1);

  // Wait for the metrics to come down the pipe.
  run_loop.Run();

  auto merged_entries = recorder().GetMergedEntriesByName(
      ukm::builders::Identifiability::kEntryName);

  // We expect two merged entries, corresponding to the two navigations.
  ASSERT_EQ(merged_entries.size(), 2u);

  // We collect all metrics together and check that there is one that contains
  // the web feature metrics.
  auto metrics = merged_entries.begin()->second->metrics;

  for (auto& it : merged_entries) {
    metrics.insert(it.second->metrics.begin(), it.second->metrics.end());
  }

  // All of the following features should be included in the list of returned
  // metrics here. The exact values depend on the test host.
  EXPECT_THAT(
      metrics,
      IsSupersetOf({
          Key(HashFeature(
              blink::mojom::WebFeature::kV8Screen_Height_AttributeGetter)),
          Key(HashFeature(
              blink::mojom::WebFeature::kV8Screen_Width_AttributeGetter)),
          Key(HashFeature(
              blink::mojom::WebFeature::kV8Screen_AvailLeft_AttributeGetter)),
          Key(HashFeature(
              blink::mojom::WebFeature::kV8Screen_AvailTop_AttributeGetter)),
          Key(HashFeature(
              blink::mojom::WebFeature::kV8Screen_AvailWidth_AttributeGetter)),
          Key(HashFeature(blink::mojom::WebFeature::kNavigatorDoNotTrack)),
      }));
}

IN_PROC_BROWSER_TEST_P(PrivacyBudgetBrowserTestWithTestRecorder,
                       RecordingFeaturesCalledInWorker) {
  ASSERT_TRUE(embedded_test_server()->Start());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  std::vector<uint64_t> expected_keys = {
      HashFeature(blink::mojom::WebFeature::kNavigatorUserAgent),
  };

  // We wait for the expected metrics to be reported. Since some of the
  // metrics are reported from the renderer process, this is the only reliable
  // way to be sure we waited long enough.
  auto quit_run_loop = [this, &expected_keys, &run_loop]() {
    if (GetReportedSurfaceKeys(expected_keys).size() == expected_keys.size())
      run_loop.Quit();
  };
  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   base::BindLambdaForTesting(quit_run_loop));

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(FilePathXYZ())));

  // The document calls a bunch of instrumented functions and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed.
  std::string done;
  ASSERT_TRUE(messages.WaitForMessage(&done));

  // Wait for the metrics to come down the pipe.
  run_loop.Run();

  // The previously registered callback will be invalid after the test class is
  // destructed.
  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   {});

  // Test succeeds if there is no timeout. However, let's recheck the metrics
  // here, so that if there is a timeout we get an output of which metrics are
  // missing.
  EXPECT_THAT(GetReportedSurfaceKeys(expected_keys), expected_keys);
}

INSTANTIATE_TEST_SUITE_P(
    PrivacyBudgetBrowserTestWithTestRecorderParameterized,
    PrivacyBudgetBrowserTestWithTestRecorder,
    ::testing::Values("/privacy_budget/calls_dedicated_worker.html",
// Shared workers are not supported on Android.
#if !BUILDFLAG(IS_ANDROID)
                      "/privacy_budget/calls_shared_worker.html",
#endif
                      "/privacy_budget/calls_service_worker.html"));

namespace {

using PrivacyBudgetBrowserTestForWorkersClientAdded =
    PrivacyBudgetBrowserTestWithTestRecorder;
}  // namespace

IN_PROC_BROWSER_TEST_P(PrivacyBudgetBrowserTestForWorkersClientAdded,
                       WorkersRecordWorkerClientAddedMetrics) {
  ASSERT_TRUE(embedded_test_server()->Start());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  std::vector<uint64_t> expected_keys = {
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kWorkerClientAdded_ClientSourceId)
          .ToUkmMetricHash(),
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kWorkerClientAdded_WorkerType)
          .ToUkmMetricHash(),
  };

  // We wait for the expected metrics to be reported. Since some of the
  // metrics are reported from the renderer process, this is the only reliable
  // way to be sure we waited long enough.
  auto quit_run_loop = [this, &expected_keys, &run_loop]() {
    if (GetReportedSurfaceKeys(expected_keys).size() == expected_keys.size())
      run_loop.Quit();
  };

  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   base::BindLambdaForTesting(quit_run_loop));

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(FilePathXYZ() + ".html")));

  // The document calls a bunch of instrumented functions and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed.
  std::string done;
  ASSERT_TRUE(messages.WaitForMessage(&done));

  // Wait for the metrics to come down the pipe.
  run_loop.Run();

  // The previously registered callback will be invalid after the test class is
  // destructed.
  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   {});

  // Test succeeds if there is no timeout. However, let's recheck the metrics
  // here, so that if there is a timeout we get an output of which metrics are
  // missing.
  EXPECT_THAT(GetReportedSurfaceKeys(expected_keys),
              UnorderedElementsAreArray(expected_keys));
}

IN_PROC_BROWSER_TEST_P(PrivacyBudgetBrowserTestForWorkersClientAdded,
                       ReportWorkerClientAddedMetricForEveryRegisteredClient) {
  ASSERT_TRUE(embedded_test_server()->Start());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  uint64_t expected_key =
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kWorkerClientAdded_ClientSourceId)
          .ToUkmMetricHash();

  // We wait for the expected metrics to be reported. Since some of the
  // metrics are reported from the renderer process, this is the only reliable
  // way to be sure we waited long enough.
  auto quit_run_loop = [this, &expected_key, &run_loop]() {
    if (GetSurfaceKeyCount(expected_key) == 2)
      run_loop.Quit();
  };

  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   base::BindLambdaForTesting(quit_run_loop));

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(
                          FilePathXYZ() + "_with_two_clients.html")));

  // The document calls a bunch of instrumented functions and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed.
  std::string done;
  ASSERT_TRUE(messages.WaitForMessage(&done));

  // Wait for the metrics to come down the pipe.
  run_loop.Run();

  // The previously registered callback will be invalid after the test class is
  // destructed.
  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   {});

  // Test succeeds if there is no timeout.
  // Both surfaces should come from the same source but have different client
  // ids.
  std::vector<raw_ptr<const ukm::mojom::UkmEntry, VectorExperimental>> entries =
      recorder().GetEntriesByName(ukm::builders::Identifiability::kEntryName);

  base::flat_set<uint64_t> source_ids;
  base::flat_set<uint64_t> client_source_ids;
  for (const ukm::mojom::UkmEntry* entry : entries) {
    for (const auto& metric : entry->metrics) {
      if (metric.first == expected_key) {
        source_ids.insert(entry->source_id);
        client_source_ids.insert(metric.second);
      }
    }
  }
  EXPECT_EQ(source_ids.size(), 1u);
  EXPECT_EQ(client_source_ids.size(), 2u);
}

INSTANTIATE_TEST_SUITE_P(
    PrivacyBudgetBrowserTestForWorkersClientAddedParameterized,
    PrivacyBudgetBrowserTestForWorkersClientAdded,
    ::testing::Values(
// Shared workers are not supported on Android.
#if !BUILDFLAG(IS_ANDROID)
        "/privacy_budget/calls_shared_worker",
#endif
        "/privacy_budget/calls_service_worker"));

IN_PROC_BROWSER_TEST_F(PrivacyBudgetBrowserTestWithTestRecorder,
                       EveryNavigationRecordsDocumentCreatedMetrics) {
  ASSERT_TRUE(embedded_test_server()->Start());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  // We expect 5 entries here generated by the two navigations from the test.
  // The first navigation adds 2 document created entries and 2 web feature
  // entries, while the second one generates only a document created entry.
  recorder().SetOnAddEntryCallback(ukm::builders::Identifiability::kEntryName,
                                   BarrierClosure(5u, run_loop.QuitClosure()));

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(
                          "/privacy_budget/samples_some_surfaces.html")));

  // The document calls a bunch of instrumented functions and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed.
  std::string screen_scrape;
  ASSERT_TRUE(messages.WaitForMessage(&screen_scrape));

  // The contents of the received message isn't used for anything other than
  // diagnostics.
  SCOPED_TRACE(screen_scrape);

  // Create an empty iframe in the page.
  EXPECT_TRUE(content::ExecJs(web_contents(),
                              "let f = document.createElement('iframe');"
                              "document.body.appendChild(f);"
                              "f.contentWindow.navigator.userAgent;"));

  // Navigating away from the test page causes the document to be unloaded. That
  // will cause any buffered metrics to be flushed.
  content::NavigateToURLBlockUntilNavigationsComplete(web_contents(),
                                                      GURL("about:blank"), 1);

  // Wait for the metrics to come down the pipe.
  run_loop.Run();

  auto merged_entries = recorder().GetMergedEntriesByName(
      ukm::builders::Identifiability::kEntryName);

  // We expect 3 merged entries, corresponding to the 3 documents.
  ASSERT_EQ(merged_entries.size(), 3u);

  constexpr uint64_t is_main_frame_hash =
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kDocumentCreated_IsMainFrame)
          .ToUkmMetricHash();
  constexpr uint64_t is_cross_origin_hash =
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kDocumentCreated_IsCrossOriginFrame)
          .ToUkmMetricHash();
  constexpr uint64_t is_cross_site_hash =
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kDocumentCreated_IsCrossSiteFrame)
          .ToUkmMetricHash();
  constexpr uint64_t navigation_source_id_hash =
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kDocumentCreated_NavigationSourceId)
          .ToUkmMetricHash();
  constexpr uint64_t user_agent_hash =
      HashFeature(blink::mojom::WebFeature::kNavigatorUserAgent);

  // Each entry in merged_entries corresponds to a committed document and they
  // all should contain the document created metrics.
  EXPECT_THAT(
      merged_entries,
      UnorderedElementsAre(
          Pair(_, Pointee(Field(&ukm::mojom::UkmEntry::metrics,
                                IsSupersetOf({Pair(is_main_frame_hash, 1),
                                              Pair(is_cross_origin_hash, 0),
                                              Pair(is_cross_site_hash, 0)})))),
          Pair(_,
               Pointee(Field(&ukm::mojom::UkmEntry::metrics,
                             AllOf(IsSupersetOf({Pair(is_main_frame_hash, 0),
                                                 Pair(is_cross_origin_hash, 0),
                                                 Pair(is_cross_site_hash, 0)}),
                                   // The child iframe should also report that
                                   // it queried the user agent.
                                   Contains(Key(user_agent_hash)))))),
          Pair(_,
               Pointee(Field(&ukm::mojom::UkmEntry::metrics,
                             IsSupersetOf({Pair(is_main_frame_hash, 1),
                                           Pair(is_cross_origin_hash, 0),
                                           Pair(is_cross_site_hash, 0)}))))));
  EXPECT_THAT(
      merged_entries,
      Each(Pair(_, Pointee(Field(&ukm::mojom::UkmEntry::metrics,
                                 Contains(Key(navigation_source_id_hash)))))));
}

IN_PROC_BROWSER_TEST_F(PrivacyBudgetBrowserTestWithTestRecorder,
                       CallsCanvasToBlob) {
  ASSERT_TRUE(embedded_test_server()->Start());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  // Add a callback checking when the canvas metric is reported.
  recorder().SetOnAddEntryCallback(
      ukm::builders::Identifiability::kEntryName,
      base::BindLambdaForTesting([this, &run_loop]() {
        // toBlob() is called on a context-less canvas, hence -1, which is the
        // value of blink::CanvasRenderingContext::CanvasRenderingAPI::kUnknown.
        constexpr uint64_t input_digest = -1;
        const uint64_t canvas_key =
            blink::IdentifiableSurface::FromTypeAndToken(
                blink::IdentifiableSurface::Type::kCanvasReadback, input_digest)
                .ToUkmMetricHash();

        for (const ukm::mojom::UkmEntry* entry : recorder().GetEntriesByName(
                 ukm::builders::Identifiability::kEntryName)) {
          for (const auto& [key, value] : entry->metrics) {
            if (key == canvas_key) {
              run_loop.Quit();
            }
          }
        }
      }));

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(
                          "/privacy_budget/calls_canvas_to_blob.html")));

  // The document calls an instrumented method and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed. However, we must also wait for the UKM metric to be
  // recorded, which happens on a TaskRunner.
  std::string blob_type;
  ASSERT_TRUE(messages.WaitForMessage(&blob_type));

  // Navigating away from the test page causes the document to be unloaded. That
  // will cause any buffered metrics to be flushed.
  content::NavigateToURLBlockUntilNavigationsComplete(web_contents(),
                                                      GURL("about:blank"), 1);

  // Wait for the metrics to come down the pipe.
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(PrivacyBudgetBrowserTestWithTestRecorder,
                       CanvasToBlobDifferentDocument) {
  ASSERT_TRUE(embedded_test_server()->Start());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  // Add a callback checking when the canvas metric is reported.
  recorder().SetOnAddEntryCallback(
      ukm::builders::Identifiability::kEntryName,
      base::BindLambdaForTesting([this, &run_loop]() {
        // Key of the entry metric to look for.
        constexpr uint64_t input_digest = UINT64_C(10266206452287635496);
        const uint64_t canvas_key =
            blink::IdentifiableSurface::FromTypeAndToken(
                blink::IdentifiableSurface::Type::kCanvasReadback,
                input_digest >> blink::IdentifiableSurface::kTypeBits)
                .ToUkmMetricHash();

        for (const ukm::mojom::UkmEntry* entry : recorder().GetEntriesByName(
                 ukm::builders::Identifiability::kEntryName)) {
          for (const auto& [key, value] : entry->metrics) {
            if (key == canvas_key) {
              run_loop.Quit();
            }
          }
        }
      }));

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(
                          "/privacy_budget/calls_canvas_to_blob_xdoc.html")));

  // The document calls an instrumented method and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed. However, we must also wait for the UKM metric to be
  // recorded, which happens on a TaskRunner.
  std::string message;
  ASSERT_TRUE(messages.WaitForMessage(&message));

  // Navigating away from the test page causes the document to be unloaded. That
  // will cause any buffered metrics to be flushed.
  content::NavigateToURLBlockUntilNavigationsComplete(web_contents(),
                                                      GURL("about:blank"), 1);

  // Wait for the metrics to come down the pipe.
  run_loop.Run();
}

namespace {

// Test class that allows to enable UKM recording.
class PrivacyBudgetBrowserTestWithUkmRecording
    : private EnableRandomSampling,
      public PrivacyBudgetBrowserTestBaseWithUkmRecording {};

}  // namespace

// When UKM resets the Client ID for some reason the study should reset its
// local state as well.
IN_PROC_BROWSER_TEST_F(PrivacyBudgetBrowserTestWithUkmRecording,
                       UkmClientIdChangesResetStudyState) {
  EXPECT_TRUE(blink::IdentifiabilityStudySettings::Get()->IsActive());
  ASSERT_TRUE(EnableUkmRecording());

  local_state()->SetString(prefs::kPrivacyBudgetSeenSurfaces, "1,2,3");

  ASSERT_TRUE(DisableUkmRecording());

  EXPECT_TRUE(
      local_state()->GetString(prefs::kPrivacyBudgetSeenSurfaces).empty())
      << "Active surface list still exists after resetting client ID";
}

IN_PROC_BROWSER_TEST_F(PrivacyBudgetBrowserTestWithUkmRecording,
                       IncludesMetadata) {
  ASSERT_TRUE(base::FeatureList::IsEnabled(features::kIdentifiabilityStudy));
  ASSERT_TRUE(EnableUkmRecording());

  constexpr blink::IdentifiableToken kDummyToken = 1;
  constexpr blink::IdentifiableSurface kDummySurface =
      blink::IdentifiableSurface::FromMetricHash(2125235);
  auto* ukm_recorder = ukm::UkmRecorder::Get();

  blink::IdentifiabilityMetricBuilder(ukm::UkmRecorder::GetNewSourceID())
      .Add(kDummySurface, kDummyToken)
      .Record(ukm_recorder);

  blink::IdentifiabilitySampleCollector::Get()->Flush(ukm_recorder);

  ukm::UkmTestHelper ukm_test_helper(ukm_service());
  ukm_test_helper.BuildAndStoreLog();
  std::unique_ptr<ukm::Report> ukm_report = ukm_test_helper.GetUkmReport();
  ASSERT_TRUE(ukm_test_helper.HasUnsentLogs());
  ASSERT_TRUE(ukm_report);
  ASSERT_NE(ukm_report->entries_size(), 0);

  std::map<uint64_t, int64_t> seen_metrics;
  for (const auto& entry : ukm_report->entries()) {
    ASSERT_TRUE(entry.has_event_hash());
    if (entry.event_hash() != ukm::builders::Identifiability::kEntryNameHash) {
      continue;
    }
    for (const auto& metric : entry.metrics()) {
      ASSERT_TRUE(metric.has_metric_hash());
      ASSERT_TRUE(metric.has_value());
      seen_metrics.insert({metric.metric_hash(), metric.value()});
    }
  }

  const std::pair<uint64_t, int64_t> kExpectedGenerationEntry{
      ukm::builders::Identifiability::kStudyGeneration_626NameHash,
      test::ScopedPrivacyBudgetConfig::kDefaultGeneration};
  EXPECT_THAT(seen_metrics, testing::Contains(kExpectedGenerationEntry));

  const std::pair<uint64_t, int64_t> kExpectedGeneratorEntry{
      ukm::builders::Identifiability::kGeneratorVersion_926NameHash,
      IdentifiabilityStudyState::kGeneratorVersion};
  EXPECT_THAT(seen_metrics, testing::Contains(kExpectedGeneratorEntry));
}

namespace {

class PrivacyBudgetGroupConfigBrowserTest : public PlatformBrowserTest {
 public:
  PrivacyBudgetGroupConfigBrowserTest() {
    test::ScopedPrivacyBudgetConfig::Parameters parameters;

    constexpr auto kSurfacesPerGroup = 40;
    constexpr auto kGroupCount = 200;

    auto counter = 0;
    for (auto i = 0; i < kGroupCount; ++i) {
      parameters.blocks.emplace_back();
      auto& group = parameters.blocks.back();
      group.reserve(kSurfacesPerGroup);
      for (auto j = 0; j < kSurfacesPerGroup; ++j) {
        group.push_back(blink::IdentifiableSurface::FromTypeAndToken(
            blink::IdentifiableSurface::Type::kNavigator_GetUserMedia,
            ++counter));
      }
    }

    scoped_config_.Apply(parameters);
  }

 private:
  test::ScopedPrivacyBudgetConfig scoped_config_;
};

}  // namespace

IN_PROC_BROWSER_TEST_F(PrivacyBudgetGroupConfigBrowserTest, LoadsAGroup) {
  EXPECT_TRUE(base::FeatureList::IsEnabled(features::kIdentifiabilityStudy));

  const auto* settings = blink::IdentifiabilityStudySettings::Get();
  ASSERT_TRUE(settings->IsActive());
}

namespace {

class PrivacyBudgetAssignedBlockSamplingConfigTest
    : public PlatformBrowserTest {
 public:
  PrivacyBudgetAssignedBlockSamplingConfigTest() {
    scoped_feature_list_.InitWithFeaturesAndParameters(
        {{features::kIdentifiabilityStudy,
          {{features::kIdentifiabilityStudyBlockedMetrics.name, "44033,44289"},
           {features::kIdentifiabilityStudyBlockedTypes.name, "11,25,28"},
           {features::kIdentifiabilityStudyBlockWeights.name,
            "5202,37515,34582"},
           {features::kIdentifiabilityStudyBlocks.name,
            // Define three blocks of surfaces.
            "9129224;865032;8710152;8678920;9305096,"
            "1722309467823238416;3972031034286914064,"
            "3873813933275956760;7532279523433960728;13014994009983628312,"},
           {features::kIdentifiabilityStudyGeneration.name, "7"}}}},
        /*disabled_features=*/{features::kIdentifiabilityStudyMetaExperiment});
  }

  static constexpr auto kBlockedSurface =
      blink::IdentifiableSurface::FromMetricHash(44033);

  // This surface is not mentioned above and is not blocked by default. It
  // should be considered allowed, but its metrics will not be recorded because
  // it is not one of the active surfaces.
  static constexpr auto kAllowedInactiveSurface =
      blink::IdentifiableSurface::FromMetricHash(44290);

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

}  // namespace

// This test checks that the Identifiability Study configuration is picked up
// correctly from the field trial parameters.
IN_PROC_BROWSER_TEST_F(PrivacyBudgetAssignedBlockSamplingConfigTest,
                       LoadsSettingsFromFieldTrialParameters) {
  ASSERT_TRUE(base::FeatureList::IsEnabled(features::kIdentifiabilityStudy));

  const auto* settings = blink::IdentifiabilityStudySettings::Get();
  EXPECT_TRUE(settings->IsActive());
  // Allowed by default.
  EXPECT_TRUE(settings->ShouldSampleType(
      blink::IdentifiableSurface::Type::kCanvasReadback));

  // Blocked surfaces.
  EXPECT_FALSE(settings->ShouldSampleSurface(kBlockedSurface));

  // Some random surface that shouldn't be blocked.
  EXPECT_TRUE(settings->ShouldSampleSurface(kAllowedInactiveSurface));

  // Blocked types
  EXPECT_FALSE(settings->ShouldSampleType(
      blink::IdentifiableSurface::Type::kHTMLMediaElement_CanPlayType));
  EXPECT_FALSE(settings->ShouldSampleType(
      blink::IdentifiableSurface::Type::kMediaCapabilities_DecodingInfo));
}

namespace {

class EnableMetaExperiment {
 public:
  EnableMetaExperiment() {
    scoped_feature_list_.InitWithFeaturesAndParameters(
        {{features::kIdentifiabilityStudyMetaExperiment,
          {{features::kIdentifiabilityStudyMetaExperimentActivationProbability
                .name,
            "1"}}}},
        {features::kIdentifiabilityStudy});
  }

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

class PrivacyBudgetMetaExperimentBrowserTestWithUkmRecording
    : private EnableMetaExperiment,
      public PrivacyBudgetBrowserTestBaseWithUkmRecording {};

class UkmRecorderAddEntryObserver : public ukm::UkmRecorderObserver {
 public:
  explicit UkmRecorderAddEntryObserver(
      base::RepeatingCallback<void(ukm::mojom::UkmEntryPtr entry)> callback)
      : callback_(std::move(callback)) {}
  void OnEntryAdded(ukm::mojom::UkmEntryPtr entry) override {
    callback_.Run(std::move(entry));
  }

 private:
  base::RepeatingCallback<void(ukm::mojom::UkmEntryPtr entry)> callback_;
};

}  // namespace

IN_PROC_BROWSER_TEST_F(PrivacyBudgetMetaExperimentBrowserTestWithUkmRecording,
                       ReportsEncounteredSurfacesAndDocumentCreatedMetrics) {
  ASSERT_TRUE(embedded_test_server()->Start());
  EXPECT_TRUE(blink::IdentifiabilityStudySettings::Get()->IsActive());
  ASSERT_TRUE(EnableUkmRecording());

  content::DOMMessageQueue messages(web_contents());
  base::RunLoop run_loop;

  constexpr uint64_t document_created_metric =
      blink::IdentifiableSurface::FromTypeAndToken(
          blink::IdentifiableSurface::Type::kReservedInternal,
          blink::IdentifiableSurface::ReservedSurfaceMetrics::
              kDocumentCreated_NavigationSourceId)
          .ToUkmMetricHash();

  const std::array<uint64_t, 6> expected_webfeature_metrics = {
      HashFeature(blink::mojom::WebFeature::kV8Screen_Height_AttributeGetter),
      HashFeature(blink::mojom::WebFeature::kV8Screen_Width_AttributeGetter),
      HashFeature(
          blink::mojom::WebFeature::kV8Screen_AvailLeft_AttributeGetter),
      HashFeature(blink::mojom::WebFeature::kV8Screen_AvailTop_AttributeGetter),
      HashFeature(
          blink::mojom::WebFeature::kV8Screen_AvailWidth_AttributeGetter),
      HashFeature(blink::mojom::WebFeature::kNavigatorDoNotTrack)};

  // Add a callback checking when the metrics are reported.
  base::flat_set<uint64_t> expected_metrics_set(
      expected_webfeature_metrics.begin(), expected_webfeature_metrics.end());
  expected_metrics_set.insert(document_created_metric);
  UkmRecorderAddEntryObserver ukm_observer(base::BindLambdaForTesting(
      [&run_loop, &expected_metrics_set](ukm::mojom::UkmEntryPtr entry) {
        for (const auto& [key, value] : entry->metrics) {
          expected_metrics_set.erase(key);
        }
        if (expected_metrics_set.empty()) {
          run_loop.Quit();
        }
      }));
  ukm_service()->AddUkmRecorderObserver(
      {ukm::builders::Identifiability::kEntryNameHash}, &ukm_observer);

  ASSERT_TRUE(content::NavigateToURL(
      web_contents(), embedded_test_server()->GetURL(
                          "/privacy_budget/samples_some_surfaces.html")));

  // The document calls a bunch of instrumented functions and sends a message
  // back to the test. Receipt of the message indicates that the script
  // successfully completed.
  std::string scraped_apis;
  ASSERT_TRUE(messages.WaitForMessage(&scraped_apis));

  // The contents of the received message isn't used for anything other than
  // diagnostics.
  SCOPED_TRACE(scraped_apis);

  // Navigating away from the test page causes the document to be unloaded. That
  // will cause any buffered metrics to be flushed.
  content::NavigateToURLBlockUntilNavigationsComplete(web_contents(),
                                                      GURL("about:blank"), 1);

  // Wait for the metrics to come down the pipe.
  run_loop.Run();

  ukm::UkmTestHelper ukm_test_helper(ukm_service());
  ukm_test_helper.BuildAndStoreLog();
  std::unique_ptr<ukm::Report> ukm_report = ukm_test_helper.GetUkmReport();
  ASSERT_TRUE(ukm_test_helper.HasUnsentLogs());
  ASSERT_TRUE(ukm_report);
  ASSERT_NE(ukm_report->entries_size(), 0);

  std::map<uint64_t, int64_t> seen_metrics;
  for (const auto& entry : ukm_report->entries()) {
    ASSERT_TRUE(entry.has_event_hash());
    if (entry.event_hash() != ukm::builders::Identifiability::kEntryNameHash) {
      continue;
    }
    for (const auto& metric : entry.metrics()) {
      ASSERT_TRUE(metric.has_metric_hash());
      ASSERT_TRUE(metric.has_value());
      seen_metrics.insert({metric.metric_hash(), metric.value()});
    }
  }

  for (uint64_t expected_metric : expected_webfeature_metrics) {
    EXPECT_THAT(
        seen_metrics,
        Contains(Pair(Type(blink::IdentifiableSurface::Type::kMeasuredSurface),
                      expected_metric)));
  }
  EXPECT_THAT(seen_metrics, Contains(Key(document_created_metric)));

  ukm_service()->RemoveUkmRecorderObserver(&ukm_observer);
}