File: site_protection_metrics_observer_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: 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 (575 lines) | stat: -rw-r--r-- 24,149 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
// 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 "chrome/browser/site_protection/site_protection_metrics_observer.h"

#include "base/metrics/statistics_recorder.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "chrome/browser/engagement/site_engagement_service_factory.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/safe_browsing/test_safe_browsing_service.h"
#include "chrome/browser/site_protection/site_familiarity_heuristic_name.h"
#include "chrome/browser/ui/safety_hub/mock_safe_browsing_database_manager.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_browser_process.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_types.h"
#include "components/site_engagement/content/site_engagement_helper.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/web_contents_tester.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/test/base/scoped_testing_local_state.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

namespace site_protection {
namespace {

// MockSafeBrowsingDatabaseManager which enables adding URL to high confidence
// allowlist.
class TestSafeBrowsingDatabaseManager : public MockSafeBrowsingDatabaseManager {
 public:
  TestSafeBrowsingDatabaseManager() = default;

  void SetUrlOnHighConfidenceAllowlist(const GURL& url) {
    url_on_high_confidence_allowlist_ = url;
  }

  void CheckUrlForHighConfidenceAllowlist(
      const GURL& url,
      CheckUrlForHighConfidenceAllowlistCallback callback) override {
    std::move(callback).Run(
        /*url_on_high_confidence_allowlist=*/(
            url == url_on_high_confidence_allowlist_),
        /*logging_details=*/std::nullopt);
  }

 protected:
  ~TestSafeBrowsingDatabaseManager() override = default;

 private:
  GURL url_on_high_confidence_allowlist_;
};

}  // anonymous namespace

// Test for SiteProtectionMetricsObserver.
class SiteProtectionMetricsObserverTest
    : public ChromeRenderViewHostTestHarness {
 public:
  SiteProtectionMetricsObserverTest() = default;
  ~SiteProtectionMetricsObserverTest() override = default;

  SiteProtectionMetricsObserverTest(const SiteProtectionMetricsObserverTest&) =
      delete;
  SiteProtectionMetricsObserverTest& operator=(
      const SiteProtectionMetricsObserverTest&) = delete;

  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();

    browser_process_ = TestingBrowserProcess::GetGlobal();

    SetUpForNewWebContents();

    safe_browsing_database_manager_ =
        base::MakeRefCounted<TestSafeBrowsingDatabaseManager>();
    safe_browsing_factory_ =
        std::make_unique<safe_browsing::TestSafeBrowsingServiceFactory>();
    safe_browsing_factory_->SetTestDatabaseManager(
        safe_browsing_database_manager_.get());

    browser_process_->SetSafeBrowsingService(
        safe_browsing_factory_->CreateSafeBrowsingService());
    browser_process_->safe_browsing_service()->Initialize();
  }

  void TearDown() override {
    browser_process_->safe_browsing_service()->ShutDown();
    browser_process_->SetSafeBrowsingService(nullptr);

    ChromeRenderViewHostTestHarness::TearDown();
  }

  TestingProfile::TestingFactories GetTestingFactories() const override {
    return {TestingProfile::TestingFactory{
        HistoryServiceFactory::GetInstance(),
        HistoryServiceFactory::GetDefaultFactory()}};
  }

  void SetIncognito() {
    Profile* const otr_profile =
        profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true);
    EXPECT_TRUE(otr_profile->IsIncognitoProfile());
    scoped_refptr<content::SiteInstance> site_instance =
        content::SiteInstance::Create(otr_profile);
    SetContents(content::WebContentsTester::CreateTestWebContents(
        otr_profile, std::move(site_instance)));

    SetUpForNewWebContents();
  }

  void SetUpForNewWebContents() {
    // Create services which observe page navigation.
    site_engagement::SiteEngagementService::Helper::CreateForWebContents(
        web_contents());
    SiteProtectionMetricsObserver::CreateForWebContents(web_contents());
  }

  history::HistoryService* GetRegularProfileHistoryService() {
    return HistoryServiceFactory::GetForProfile(
        profile(), ServiceAccessType::IMPLICIT_ACCESS);
  }

  void AddPageVisitedYesterdayToRegularProfile(const GURL& url) {
    GetRegularProfileHistoryService()->AddPage(
        url, (base::Time::Now() - base::Hours(25)), history::SOURCE_BROWSED);
  }

  void NavigateAndWaitForHistogram(const GURL& url,
                                   const std::string& histogram_name) {
    base::RunLoop run_loop;
    base::StatisticsRecorder::ScopedHistogramSampleObserver observer(
        histogram_name,
        base::BindLambdaForTesting(
            [&](std::string_view histogram_name, uint64_t name_hash,
                base::HistogramBase::Sample32 sample) { run_loop.Quit(); }));
    NavigateAndCommit(url);
    run_loop.Run();
  }

  void NavigateAndCheckRecordedHeuristicHistograms(
      const GURL& url,
      const std::vector<SiteFamiliarityHeuristicName>& expected_heuristics) {
    const char kFamiliarityHistogramName[] =
        "SafeBrowsing.SiteProtection.FamiliarityHeuristic";

    base::HistogramTester histogram_tester;
    NavigateAndWaitForHistogram(url, kFamiliarityHistogramName);

    histogram_tester.ExpectTotalCount(kFamiliarityHistogramName,
                                      expected_heuristics.size());
    for (SiteFamiliarityHeuristicName expected_heuristic :
         expected_heuristics) {
      histogram_tester.ExpectBucketCount(kFamiliarityHistogramName,
                                         expected_heuristic, 1);
    }
  }

  void NavigateAndCheckCandidate1HeuristicHistogram(const GURL& url,
                                                    bool expected_value) {
    const char kCandidate1HeuristicHistogramName[] =
        "SafeBrowsing.SiteProtection.FamiliarityHeuristic."
        "Engagement15OrVisitedBeforeTodayOrHighConfidence";
    base::HistogramTester histogram_tester;
    NavigateAndWaitForHistogram(url, kCandidate1HeuristicHistogramName);
    histogram_tester.ExpectUniqueSample(kCandidate1HeuristicHistogramName,
                                        expected_value, 1);
  }

  int64_t GetUkmFamiliarityHeuristicValue(ukm::TestUkmRecorder& ukm_recorder,
                                          const std::string& metric_name) {
    std::vector<int64_t> values = ukm_recorder.GetMetricsEntryValues(
        "SiteFamiliarityHeuristicResult", metric_name);
    return values.size() == 1u ? values[0] : -1;
  }

  int64_t GetUkmHistoryFamiliarityHeuristicValue(
      ukm::TestUkmRecorder& ukm_recorder) {
    return GetUkmFamiliarityHeuristicValue(ukm_recorder,
                                           "SiteFamiliarityHistoryHeuristic");
  }

  void NavigateAndCheckRecordedHeuristicUkm(const GURL& url,
                                            const std::string& metric_name,
                                            int64_t expected_value) {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    base::RunLoop run_loop;
    ukm_recorder.SetOnAddEntryCallback(
        ukm::builders::SiteFamiliarityHeuristicResult::kEntryName,
        run_loop.QuitClosure());
    NavigateAndCommit(url);
    run_loop.Run();
    EXPECT_EQ(expected_value,
              GetUkmFamiliarityHeuristicValue(ukm_recorder, metric_name));
  }

 protected:
  raw_ptr<TestingBrowserProcess> browser_process_;

#if BUILDFLAG(IS_CHROMEOS)
  // Local state is needed to construct ProxyConfigService, which is a
  // dependency of PingManager on ChromeOS.
  ScopedTestingLocalState scoped_testing_local_state_{
      TestingBrowserProcess::GetGlobal()};
#endif  // BUILDFLAG(IS_CHROMEOS)

  scoped_refptr<TestSafeBrowsingDatabaseManager>
      safe_browsing_database_manager_;
  std::unique_ptr<safe_browsing::TestSafeBrowsingServiceFactory>
      safe_browsing_factory_;
};

// Test that SiteProtectionMetricsObserver logs the correct histogram and UKM if
// history doesn't have any history entries older than 24 hours ago.
TEST_F(SiteProtectionMetricsObserverTest, NoHistoryOlderThanADayAgo) {
  GURL kUrlVisited8HoursAgo("https://bar.com");
  GURL kUrlVisitedToday("https://baz.com");

  ukm::TestAutoSetUkmRecorder ukm_recorder;
  GetRegularProfileHistoryService()->AddPage(
      kUrlVisited8HoursAgo, (base::Time::Now() - base::Hours(8)),
      history::SOURCE_BROWSED);

  NavigateAndCheckRecordedHeuristicHistograms(
      kUrlVisitedToday,
      {SiteFamiliarityHeuristicName::kNoVisitsToAnySiteMoreThanADayAgo});
  EXPECT_EQ(static_cast<int>(SiteFamiliarityHistoryHeuristicName::
                                 kNoVisitsToAnySiteMoreThanADayAgo),
            GetUkmHistoryFamiliarityHeuristicValue(ukm_recorder));
}

// Test the histograms and UKM which are logged by SiteProtectionMetricsObserver
// based on how long ago the current page URL was previously visited.
TEST_F(SiteProtectionMetricsObserverTest, VisitInHistoryMoreThanADayAgo) {
  GURL kUrlVisitedYesterday("https://foo.com");
  GURL kUrlVisited8HoursAgo("https://bar.com");
  GURL kUrlVisited1HourAgo("https://baz.com");

  GetRegularProfileHistoryService()->AddPage(
      kUrlVisitedYesterday, (base::Time::Now() - base::Hours(25)),
      history::SOURCE_BROWSED);
  GetRegularProfileHistoryService()->AddPage(
      kUrlVisited8HoursAgo, (base::Time::Now() - base::Hours(8)),
      history::SOURCE_BROWSED);
  GetRegularProfileHistoryService()->AddPage(
      kUrlVisited1HourAgo, base::Time::Now(), history::SOURCE_BROWSED);

  {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    NavigateAndCheckRecordedHeuristicHistograms(
        kUrlVisitedYesterday,
        {SiteFamiliarityHeuristicName::kVisitedMoreThanFourHoursAgo,
         SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo});
    EXPECT_EQ(static_cast<int>(
                  SiteFamiliarityHistoryHeuristicName::kVisitedMoreThanADayAgo),
              GetUkmHistoryFamiliarityHeuristicValue(ukm_recorder));
  }

  {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    NavigateAndCheckRecordedHeuristicHistograms(
        kUrlVisited8HoursAgo,
        {SiteFamiliarityHeuristicName::kVisitedMoreThanFourHoursAgo});
    EXPECT_EQ(
        static_cast<int>(
            SiteFamiliarityHistoryHeuristicName::kVisitedMoreThanFourHoursAgo),
        GetUkmHistoryFamiliarityHeuristicValue(ukm_recorder));
  }

  {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    NavigateAndCheckRecordedHeuristicHistograms(
        kUrlVisited1HourAgo, {SiteFamiliarityHeuristicName::kNoHeuristicMatch});
    EXPECT_EQ(static_cast<int>(
                  SiteFamiliarityHistoryHeuristicName::kNoHeuristicMatch),
              GetUkmHistoryFamiliarityHeuristicValue(ukm_recorder));
  }
}

// Test the histograms which are logged by SiteProtectionMetricsObserver for
// different levels of site engagement.
TEST_F(SiteProtectionMetricsObserverTest, SiteEngagementScore) {
  AddPageVisitedYesterdayToRegularProfile(GURL("https://bar.com"));

  GURL kUrl("https://foo.com");
  site_engagement::SiteEngagementService* site_engagement_service =
      site_engagement::SiteEngagementServiceFactory::GetForProfile(profile());

  site_engagement_service->ResetBaseScoreForURL(kUrl, 1);
  NavigateAndCheckRecordedHeuristicHistograms(
      kUrl, {SiteFamiliarityHeuristicName::kSiteEngagementScoreExists});

  site_engagement_service->ResetBaseScoreForURL(kUrl, 10);
  NavigateAndCheckRecordedHeuristicHistograms(
      kUrl, {SiteFamiliarityHeuristicName::kSiteEngagementScoreExists,
             SiteFamiliarityHeuristicName::kSiteEngagementScoreGte10});

  site_engagement_service->ResetBaseScoreForURL(kUrl, 25);
  NavigateAndCheckRecordedHeuristicHistograms(
      kUrl, {SiteFamiliarityHeuristicName::kSiteEngagementScoreExists,
             SiteFamiliarityHeuristicName::kSiteEngagementScoreGte10,
             SiteFamiliarityHeuristicName::kSiteEngagementScoreGte25});

  site_engagement_service->ResetBaseScoreForURL(kUrl, 50);
  NavigateAndCheckRecordedHeuristicHistograms(
      kUrl, {
                SiteFamiliarityHeuristicName::kSiteEngagementScoreExists,
                SiteFamiliarityHeuristicName::kSiteEngagementScoreGte10,
                SiteFamiliarityHeuristicName::kSiteEngagementScoreGte25,
                SiteFamiliarityHeuristicName::kSiteEngagementScoreGte50,
            });
}

// That that SiteProtectionMetricsObserver ignores engagement due to the
// in-progress navigation.
TEST_F(SiteProtectionMetricsObserverTest, IgnoreCurrentNavigationEngagement) {
  AddPageVisitedYesterdayToRegularProfile(GURL("https://bar.com"));

  GURL kUrl("https://foo.com");
  base::HistogramTester histogram_tester;

  base::RunLoop run_loop;
  base::StatisticsRecorder::ScopedHistogramSampleObserver observer(
      "SafeBrowsing.SiteProtection.FamiliarityHeuristic",
      base::BindLambdaForTesting(
          [&](std::string_view histogram_name, uint64_t name_hash,
              base::HistogramBase::Sample32 sample) { run_loop.Quit(); }));

  NavigateAndCommit(kUrl, ui::PAGE_TRANSITION_TYPED);
  run_loop.Run();

  histogram_tester.ExpectUniqueSample(
      "SafeBrowsing.SiteProtection.FamiliarityHeuristic",
      SiteFamiliarityHeuristicName::kNoHeuristicMatch, 1);

  site_engagement::SiteEngagementService* site_engagement_service =
      site_engagement::SiteEngagementServiceFactory::GetForProfile(profile());
  EXPECT_LT(0, site_engagement_service->GetScore(kUrl));
}

// Test that SiteProtectionMetricsObserver logs the site engagement to UKM.
TEST_F(SiteProtectionMetricsObserverTest, SiteEngagementScoreUkm) {
  GURL kUrl("https://foo.com");
  const int kSiteEngagement = 15;
  // Site engagement should be rounded down to multiple of 10 in UKM.
  const int kExpectedUkmSiteEngagement = 10;

  site_engagement::SiteEngagementService* site_engagement_service =
      site_engagement::SiteEngagementServiceFactory::GetForProfile(profile());
  site_engagement_service->ResetBaseScoreForURL(kUrl, kSiteEngagement);
  GetRegularProfileHistoryService()->AddPage(
      kUrl, (base::Time::Now() - base::Hours(1)), history::SOURCE_BROWSED);

  NavigateAndCheckRecordedHeuristicUkm(kUrl, "SiteEngagementScore",
                                       kExpectedUkmSiteEngagement);
}

// Test that SiteProtectionMetricsObserver logs the correct histograms and UKM
// if the site is on the safe browsing global allowlist.
TEST_F(SiteProtectionMetricsObserverTest, GlobalAllowlistMatch) {
  AddPageVisitedYesterdayToRegularProfile(GURL("https://baz.com"));

  GURL kUrlOnHighConfidenceAllowlist("https://foo.com");
  GURL kRegularUrl("https://bar.com");
  safe_browsing_database_manager_->SetUrlOnHighConfidenceAllowlist(
      kUrlOnHighConfidenceAllowlist);

  {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    NavigateAndCheckRecordedHeuristicHistograms(
        kUrlOnHighConfidenceAllowlist,
        {SiteFamiliarityHeuristicName::kGlobalAllowlistMatch});
    EXPECT_EQ(true, GetUkmFamiliarityHeuristicValue(
                        ukm_recorder, "OnHighConfidenceAllowlist"));
  }

  {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    NavigateAndCheckRecordedHeuristicHistograms(
        kRegularUrl, {SiteFamiliarityHeuristicName::kNoHeuristicMatch});
    EXPECT_EQ(false, GetUkmFamiliarityHeuristicValue(
                         ukm_recorder, "OnHighConfidenceAllowlist"));
  }
}

// Test that SiteProtectionMetricsObserver logs the correct histograms and UKM
// if the SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo heuristic
// applies for the current visit to the site but the heuristic did not apply
// to the previous visit to the site.
TEST_F(SiteProtectionMetricsObserverTest, SiteFamiliarWasPreviouslyUnfamiliar) {
  GURL kPageUrl("https://bar.com");
  GURL kOtherUrl("https://baz.com");

  base::Time now = base::Time::Now();
  base::Time kPageVisitTime1 = now - base::Hours(25);
  base::Time kPageVisitTime2 = kPageVisitTime1 - base::Hours(25);
  base::Time kOtherVisitTime = kPageVisitTime2 - base::Hours(25);

  GetRegularProfileHistoryService()->AddPage(kPageUrl, kPageVisitTime1,
                                             history::SOURCE_BROWSED);
  GetRegularProfileHistoryService()->AddPage(kOtherUrl, kOtherVisitTime,
                                             history::SOURCE_BROWSED);
  {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    NavigateAndCheckRecordedHeuristicHistograms(
        kPageUrl,
        {SiteFamiliarityHeuristicName::kVisitedMoreThanFourHoursAgo,
         SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo,
         SiteFamiliarityHeuristicName::kFamiliarLikelyPreviouslyUnfamiliar});
    EXPECT_EQ(static_cast<int>(SiteFamiliarityHistoryHeuristicName::
                                   kVisitedMoreThanADayAgoPreviouslyUnfamiliar),
              GetUkmHistoryFamiliarityHeuristicValue(ukm_recorder));
  }

  GetRegularProfileHistoryService()->AddPage(kPageUrl, kPageVisitTime2,
                                             history::SOURCE_BROWSED);

  {
    ukm::TestAutoSetUkmRecorder ukm_recorder;
    NavigateAndCheckRecordedHeuristicHistograms(
        kPageUrl, {SiteFamiliarityHeuristicName::kVisitedMoreThanFourHoursAgo,
                   SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo});
    EXPECT_EQ(static_cast<int>(
                  SiteFamiliarityHistoryHeuristicName::kVisitedMoreThanADayAgo),
              GetUkmHistoryFamiliarityHeuristicValue(ukm_recorder));
  }
}

// Test that SiteProtectionMetricsObserver logs the correct histograms
// if:
// - SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo heuristic
//   applies for the current visit.
// AND
// -  SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo heuristic
//   does not apply to the previous visit.
// AND
// - SiteFamiliarityHeuristicName::kNoVisitsToAnySiteMoreThanADayAgo
//   applies to the previous visit.
TEST_F(SiteProtectionMetricsObserverTest,
       SiteFamiliarWasPreviouslyUnfamiliarDueToNoOldHistory) {
  GURL kPageUrl("https://bar.com");
  GURL kOtherUrl("https://baz.com");

  base::Time now = base::Time::Now();
  base::Time kPageVisitTime = now - base::Hours(25);
  base::Time kOtherVisitTime1 = kPageVisitTime - base::Hours(1);
  base::Time kOtherVisitTime2 = kOtherVisitTime1 - base::Hours(100);

  GetRegularProfileHistoryService()->AddPage(kPageUrl, kPageVisitTime,
                                             history::SOURCE_BROWSED);
  GetRegularProfileHistoryService()->AddPage(kOtherUrl, kOtherVisitTime1,
                                             history::SOURCE_BROWSED);

  NavigateAndCheckRecordedHeuristicHistograms(
      kPageUrl, {SiteFamiliarityHeuristicName::kVisitedMoreThanFourHoursAgo,
                 SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo});

  GetRegularProfileHistoryService()->AddPage(kOtherUrl, kOtherVisitTime2,
                                             history::SOURCE_BROWSED);
  NavigateAndCheckRecordedHeuristicHistograms(
      kPageUrl,
      {SiteFamiliarityHeuristicName::kVisitedMoreThanFourHoursAgo,
       SiteFamiliarityHeuristicName::kVisitedMoreThanADayAgo,
       SiteFamiliarityHeuristicName::kFamiliarLikelyPreviouslyUnfamiliar});
}

// Test that SiteProtectionMetricsObserver logs whether any heuristics matched
// to UKM.
TEST_F(SiteProtectionMetricsObserverTest, AnyHeuristicsMatchUkm) {
  GURL kUrlVisitedYesterday("https://foo.com");
  GURL kUrlVisitedNever("https://bar.com");

  AddPageVisitedYesterdayToRegularProfile(kUrlVisitedYesterday);

  NavigateAndCheckRecordedHeuristicUkm(kUrlVisitedYesterday,
                                       "AnyHeuristicsMatch", true);
  NavigateAndCheckRecordedHeuristicUkm(kUrlVisitedNever, "AnyHeuristicsMatch",
                                       false);
}

// Test that the SiteProtectionMetricsObserver does not log any metrics for
// file:// URLs.
TEST_F(SiteProtectionMetricsObserverTest, FileUrlNoMetricsLogged) {
  GURL kFileUrlVisitedNever("file:///usr/");
  GURL kUrlVisitedNever("https://bar.com");

  SiteProtectionMetricsObserver* site_protection_observer =
      SiteProtectionMetricsObserver::FromWebContents(web_contents());

  base::HistogramTester histogram_tester;

  // Check that there are no pending asynchronous tasks which would perhaps log
  // UMA when run.
  NavigateAndCommit(kFileUrlVisitedNever);
  EXPECT_FALSE(site_protection_observer->HasPendingTasksForTesting());

  // Check that there are pending asynchronous tasks which would log UMA when
  // run.
  NavigateAndCommit(kUrlVisitedNever);
  EXPECT_TRUE(site_protection_observer->HasPendingTasksForTesting());

  histogram_tester.ExpectTotalCount(
      "SafeBrowsing.SiteProtection.FamiliarityHeuristic", 0u);
}

// Test that SiteProtectionMetricsObserver logs to
// SafeBrowsing.SiteProtection.FamiliarityHeuristic.OffTheRecord when in
// incognito.
TEST_F(SiteProtectionMetricsObserverTest, Incognito) {
  const char kRegularProfileHistogramName[] =
      "SafeBrowsing.SiteProtection.FamiliarityHeuristic";
  const char kOffTheRecordHistogramName[] =
      "SafeBrowsing.SiteProtection.FamiliarityHeuristic.OffTheRecord";
  GURL kUrlVisitedNever("https://bar.com");

  SetIncognito();

  base::HistogramTester histogram_tester;
  NavigateAndWaitForHistogram(kUrlVisitedNever, kOffTheRecordHistogramName);
  histogram_tester.ExpectUniqueSample(
      kOffTheRecordHistogramName,
      SiteFamiliarityHeuristicName::kNoVisitsToAnySiteMoreThanADayAgo, 1);
  histogram_tester.ExpectTotalCount(kRegularProfileHistogramName, 0u);
}

// Test that
// SafeBrowsing.SiteProtection.FamiliarityHeuristic
//     .Engagement15OrVisitedBeforeTodayOrHighConfidence
// is properly recorded.
TEST_F(SiteProtectionMetricsObserverTest, MatchesHeuristicCandidate) {
  history::HistoryService* history_service = GetRegularProfileHistoryService();
  site_engagement::SiteEngagementService* site_engagement_service =
      site_engagement::SiteEngagementServiceFactory::GetForProfile(profile());
  const base::Time kTimeNow = base::Time::Now();
  const base::Time kTimeHourAgo = kTimeNow - base::Hours(1);
  const base::Time kTimeYesterday = kTimeNow - base::Days(1);

  GURL kUrlVisitedTodayEngagement5("https://bar.com");
  history_service->AddPage(kUrlVisitedTodayEngagement5, kTimeHourAgo,
                           history::SOURCE_BROWSED);
  site_engagement_service->ResetBaseScoreForURL(kUrlVisitedTodayEngagement5, 5);
  NavigateAndCheckCandidate1HeuristicHistogram(kUrlVisitedTodayEngagement5,
                                               /*expected_value=*/false);

  GURL kUrlVisitedTodayEngagement15("https://baz.com");
  history_service->AddPage(kUrlVisitedTodayEngagement15, kTimeHourAgo,
                           history::SOURCE_BROWSED);
  site_engagement_service->ResetBaseScoreForURL(kUrlVisitedTodayEngagement15,
                                                15);
  NavigateAndCheckCandidate1HeuristicHistogram(kUrlVisitedTodayEngagement15,
                                               /*expected_value=*/true);

  GURL kUrlVisitedYesterday("https://foo.com");
  history_service->AddPage(kUrlVisitedYesterday, kTimeYesterday,
                           history::SOURCE_BROWSED);
  NavigateAndCheckCandidate1HeuristicHistogram(kUrlVisitedYesterday,
                                               /*expected_value=*/true);

  GURL kUrlVisitedNeverHighConfidenceAllowlist("https://hi.com");
  safe_browsing_database_manager_->SetUrlOnHighConfidenceAllowlist(
      kUrlVisitedNeverHighConfidenceAllowlist);
  NavigateAndCheckCandidate1HeuristicHistogram(
      kUrlVisitedNeverHighConfidenceAllowlist,
      /*expected_value=*/true);
}

}  // namespace site_protection