File: async_check_tracker_unittest.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 (592 lines) | stat: -rw-r--r-- 25,031 bytes parent folder | download | duplicates (6)
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
// Copyright 2023 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/safe_browsing/content/browser/async_check_tracker.h"

#include "base/functional/callback_helpers.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/safe_browsing/content/browser/base_ui_manager.h"
#include "components/safe_browsing/content/browser/url_checker_holder.h"
#include "components/safe_browsing/core/browser/db/v4_protocol_manager_util.h"
#include "components/safe_browsing/core/browser/safe_browsing_url_checker_impl.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/security_interstitials/core/unsafe_resource.h"
#include "components/security_interstitials/core/unsafe_resource_locator.h"
#include "content/public/test/mock_navigation_handle.h"
#include "content/public/test/test_renderer_host.h"

using security_interstitials::UnsafeResourceLocator;

namespace safe_browsing {

namespace {

using security_interstitials::UnsafeResource;

class MockUIManager : public BaseUIManager {
 public:
  MockUIManager() : BaseUIManager() {}

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

  void DisplayBlockingPage(const UnsafeResource& resource) override {
    display_blocking_page_called_times_++;
    displayed_resource_ = resource;
  }

  int DisplayBlockingPageCalledTimes() {
    return display_blocking_page_called_times_;
  }

  UnsafeResource GetDisplayedResource() { return displayed_resource_; }

 protected:
  ~MockUIManager() override = default;

 private:
  int display_blocking_page_called_times_ = 0;
  UnsafeResource displayed_resource_;
};

constexpr int kLocalNavigationTimestampsSizeThreshold = 5;

}  // namespace

class AsyncCheckTrackerTest : public content::RenderViewHostTestHarness {
 protected:
  AsyncCheckTrackerTest()
      : RenderViewHostTestHarness(
            content::BrowserTaskEnvironment::REAL_IO_THREAD,
            base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
    std::vector<base::test::FeatureRef> enabled = {};
#if BUILDFLAG(IS_ANDROID)
    enabled.push_back(kSafeBrowsingSyncCheckerCheckAllowlist);
#endif
    feature_list_.InitWithFeatures(enabled, {});
  }

  void SetUp() override {
    content::RenderViewHostTestHarness::SetUp();

    url_ = GURL("https://example.com/");
    EXPECT_CALL(mock_web_contents_getter_, Run())
        .WillRepeatedly(testing::Return(nullptr));
    ui_manager_ = base::MakeRefCounted<MockUIManager>();
    tracker_ = AsyncCheckTracker::GetOrCreateForWebContents(
        web_contents(), ui_manager_.get(),
        /*should_sync_checker_check_allowlist=*/false);
  }

  void TearDown() override {
    tracker_ = nullptr;
    content::RenderViewHostTestHarness::TearDown();
  }

  void CallDidFinishNavigation(content::MockNavigationHandle& handle,
                               bool has_committed) {
    handle.set_has_committed(has_committed);
    tracker_->DidFinishNavigation(&handle);
    task_environment()->RunUntilIdle();
  }

  void CallPendingCheckerCompleted(int64_t navigation_id,
                                   bool proceed,
                                   bool has_post_commit_interstitial_skipped,
                                   bool all_checks_completed) {
    if (!proceed) {
      // This mocks how BaseUIManager caches unsafe resource if
      // load_post_commit_error_page is false.
      UnsafeResource resource;
      resource.url = url_;
      resource.threat_type = SBThreatType::SB_THREAT_TYPE_URL_PHISHING;
      resource.navigation_id = navigation_id;
      ui_manager_->AddUnsafeResource(url_, resource);
    }
    UrlCheckerHolder::OnCompleteCheckResult result(
        proceed, /*showed_interstitial=*/true,
        has_post_commit_interstitial_skipped,
        SafeBrowsingUrlCheckerImpl::PerformedCheck::kUrlRealTimeCheck,
        all_checks_completed);
    tracker_->PendingCheckerCompleted(navigation_id, result);
    task_environment()->RunUntilIdle();
  }

  void CallTransferUrlChecker(int64_t navigation_id) {
    auto checker = std::make_unique<UrlCheckerHolder>(
        /*delegate_getter=*/base::NullCallback(), content::FrameTreeNodeId(),
        navigation_id, mock_web_contents_getter_.Get(),
        /*complete_callback=*/base::NullCallback(),
        /*url_real_time_lookup_enabled=*/false,
        /*can_check_db=*/true,
        /*can_check_high_confidence_allowlist=*/true,
        /*url_lookup_service_metric_suffix=*/"",
        /*url_lookup_service=*/nullptr,
        /*hash_realtime_service=*/nullptr,
        /*hash_realtime_selection=*/
        hash_realtime_utils::HashRealTimeSelection::kNone,
        /*is_async_check=*/true, /*check_allowlist_before_hash_database=*/false,
        SessionID::InvalidValue(), /*referring_app_info=*/std::nullopt);
    checker->AddUrlInRedirectChainForTesting(url_);
    tracker_->TransferUrlChecker(std::move(checker));
  }

  base::test::ScopedFeatureList feature_list_;
  GURL url_;
  base::MockCallback<base::RepeatingCallback<content::WebContents*()>>
      mock_web_contents_getter_;
  scoped_refptr<MockUIManager> ui_manager_;
  raw_ptr<AsyncCheckTracker> tracker_;
};

TEST_F(AsyncCheckTrackerTest,
       DisplayBlockingPageNotCalled_PendingCheckNotFound) {
  content::MockNavigationHandle handle(url_, main_rfh());
  // This can happen when the complete callback is scheduled before the checker
  // is scheduled to be deleted on the UI thread. Mock this scenario by not
  // calling CallTransferUrlChecker.
  CallPendingCheckerCompleted(handle.GetNavigationId(), /*proceed=*/false,
                              /*has_post_commit_interstitial_skipped=*/true,
                              /*all_checks_completed=*/true);
  CallDidFinishNavigation(handle, /*has_committed=*/true);
  EXPECT_EQ(ui_manager_->DisplayBlockingPageCalledTimes(), 0);
}

TEST_F(AsyncCheckTrackerTest,
       DisplayBlockingPageNotCalled_PendingCheckNotCompleted) {
  content::MockNavigationHandle handle(url_, main_rfh());
  CallTransferUrlChecker(handle.GetNavigationId());
  CallDidFinishNavigation(handle, /*has_committed=*/true);
  EXPECT_EQ(ui_manager_->DisplayBlockingPageCalledTimes(), 0);
}

TEST_F(AsyncCheckTrackerTest,
       DisplayBlockingPageNotCalled_PendingCheckProceed) {
  base::HistogramTester histograms;
  content::MockNavigationHandle handle(url_, main_rfh());
  CallTransferUrlChecker(handle.GetNavigationId());
  CallPendingCheckerCompleted(handle.GetNavigationId(), /*proceed=*/true,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/true);
  CallDidFinishNavigation(handle, /*has_committed=*/true);
  EXPECT_EQ(ui_manager_->DisplayBlockingPageCalledTimes(), 0);

  histograms.ExpectTotalCount(
      "SafeBrowsing.AsyncCheck.HasPostCommitInterstitialSkipped",
      /*expected_count=*/0);
}

TEST_F(AsyncCheckTrackerTest,
       DisplayBlockingPageNotCalled_PostCommitInterstitialNotSkipped) {
  base::HistogramTester histograms;
  content::MockNavigationHandle handle(url_, main_rfh());
  CallTransferUrlChecker(handle.GetNavigationId());
  CallPendingCheckerCompleted(handle.GetNavigationId(), /*proceed=*/false,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/true);
  CallDidFinishNavigation(handle, /*has_committed=*/true);
  EXPECT_EQ(ui_manager_->DisplayBlockingPageCalledTimes(), 0);

  histograms.ExpectUniqueSample(
      "SafeBrowsing.AsyncCheck.HasPostCommitInterstitialSkipped",
      /*sample=*/false,
      /*expected_bucket_count=*/1);
}

TEST_F(AsyncCheckTrackerTest,
       DisplayBlockingPageNotCalled_NavigationNotCommitted) {
  content::MockNavigationHandle handle(url_, main_rfh());
  CallTransferUrlChecker(handle.GetNavigationId());
  CallPendingCheckerCompleted(handle.GetNavigationId(), /*proceed=*/false,
                              /*has_post_commit_interstitial_skipped=*/true,
                              /*all_checks_completed=*/true);
  CallDidFinishNavigation(handle, /*has_committed=*/false);
  EXPECT_EQ(ui_manager_->DisplayBlockingPageCalledTimes(), 0);
}

TEST_F(AsyncCheckTrackerTest, DisplayBlockingPageCalled) {
  base::HistogramTester histograms;
  content::MockNavigationHandle handle(url_, main_rfh());
  CallTransferUrlChecker(handle.GetNavigationId());
  CallPendingCheckerCompleted(handle.GetNavigationId(), /*proceed=*/false,
                              /*has_post_commit_interstitial_skipped=*/true,
                              /*all_checks_completed=*/true);
  CallDidFinishNavigation(handle, /*has_committed=*/true);
  EXPECT_EQ(ui_manager_->DisplayBlockingPageCalledTimes(), 1);
  UnsafeResource resource = ui_manager_->GetDisplayedResource();
  EXPECT_EQ(resource.threat_type, SBThreatType::SB_THREAT_TYPE_URL_PHISHING);
  EXPECT_EQ(resource.url, url_);
  EXPECT_EQ(resource.rfh_locator.render_process_id,
            main_rfh()->GetGlobalId().child_id);
  EXPECT_EQ(resource.rfh_locator.render_frame_token,
            main_rfh()->GetFrameToken().value());

  histograms.ExpectUniqueSample(
      "SafeBrowsing.AsyncCheck.HasPostCommitInterstitialSkipped",
      /*sample=*/true,
      /*expected_bucket_count=*/1);
}

TEST_F(AsyncCheckTrackerTest,
       DisplayBlockingPageCalled_DidFinishNavigationCalledFirst) {
  content::MockNavigationHandle handle(url_, main_rfh());
  CallTransferUrlChecker(handle.GetNavigationId());
  CallDidFinishNavigation(handle, /*has_committed=*/true);
  // Usually has_post_commit_interstitial_skipped is false if
  // DidFinishNavigation is already called. It can be true if
  // DidFinishNavigation happens to be called between when
  // PendingCheckerCompleted is scheduled and when it is run.
  CallPendingCheckerCompleted(handle.GetNavigationId(), /*proceed=*/false,
                              /*has_post_commit_interstitial_skipped=*/true,
                              /*all_checks_completed=*/true);
  EXPECT_EQ(ui_manager_->DisplayBlockingPageCalledTimes(), 1);
  UnsafeResource resource = ui_manager_->GetDisplayedResource();
  EXPECT_EQ(resource.threat_type, SBThreatType::SB_THREAT_TYPE_URL_PHISHING);
  EXPECT_EQ(resource.url, url_);
  EXPECT_EQ(resource.rfh_locator.render_process_id,
            main_rfh()->GetGlobalId().child_id);
  EXPECT_EQ(resource.rfh_locator.render_frame_token,
            main_rfh()->GetFrameToken().value());
}

TEST_F(AsyncCheckTrackerTest, IsMainPageLoadPending) {
  base::HistogramTester histograms;
  content::MockNavigationHandle handle(web_contents());
  auto rfh_locator = UnsafeResourceLocator::CreateForFrameTreeNodeId(
      main_rfh()->GetFrameTreeNodeId().value());

  AsyncCheckTracker* tracker =
      AsyncCheckTracker::FromWebContents(web_contents());
  EXPECT_TRUE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, handle.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));

  tracker->DidFinishNavigation(&handle);
  // The navigation is not committed.
  EXPECT_TRUE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, handle.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
  histograms.ExpectUniqueSample(
      "SafeBrowsing.AsyncCheck.CommittedNavigationIdsSize",
      /*sample=*/0,
      /*expected_count=*/1);

  handle.set_has_committed(true);
  tracker->DidFinishNavigation(&handle);
  EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, handle.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
  histograms.ExpectBucketCount(
      "SafeBrowsing.AsyncCheck.CommittedNavigationIdsSize",
      /*sample=*/1,
      /*expected_count=*/1);
}

TEST_F(AsyncCheckTrackerTest, IsMainPageLoadPending_NoNavigationId) {
  content::MockNavigationHandle handle(web_contents());
  auto rfh_locator = UnsafeResourceLocator::CreateForFrameTreeNodeId(
      main_rfh()->GetFrameTreeNodeId().value());
  EXPECT_TRUE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, /*navigation_id=*/std::nullopt,
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));

  // If there is no navigation id associated with the resource, whether the
  // main page load is pending is determined by
  // UnsafeResource::IsMainPageLoadPendingWithSyncCheck.
  EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator,
      /*navigation_id=*/std::nullopt,
      SBThreatType::SB_THREAT_TYPE_URL_CLIENT_SIDE_PHISHING));
}

TEST_F(AsyncCheckTrackerTest,
       IsMainPageLoadPending_DeleteExpiredNavigationTimestamps) {
  tracker_->SetNavigationTimestampsSizeThresholdForTesting(
      kLocalNavigationTimestampsSizeThreshold);
  auto rfh_locator = UnsafeResourceLocator::CreateForFrameTreeNodeId(
      main_rfh()->GetFrameTreeNodeId().value());

  std::vector<int64_t> old_navigation_ids;
  for (int i = 0; i < kLocalNavigationTimestampsSizeThreshold; i++) {
    content::MockNavigationHandle handle(url_, main_rfh());
    old_navigation_ids.push_back(handle.GetNavigationId());
    CallDidFinishNavigation(handle, /*has_committed=*/true);
  }
  for (int64_t id : old_navigation_ids) {
    EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
        rfh_locator, id, SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
  }

  task_environment()->FastForwardBy(base::Seconds(180));
  content::MockNavigationHandle recent_handle1(url_, main_rfh());
  CallDidFinishNavigation(recent_handle1, /*has_committed=*/true);
  for (int64_t id : old_navigation_ids) {
    EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
        rfh_locator, id, SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
  }

  task_environment()->FastForwardBy(base::Seconds(1));
  content::MockNavigationHandle recent_handle2(url_, main_rfh());
  CallDidFinishNavigation(recent_handle2, /*has_committed=*/true);
  // The old navigation timestamps have been cleaned up, so the function returns
  // true.
  for (int64_t id : old_navigation_ids) {
    EXPECT_TRUE(AsyncCheckTracker::IsMainPageLoadPending(
        rfh_locator, id, SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
  }

  // The recent timestamps should not be cleaned up.
  EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, recent_handle1.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
  EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, recent_handle2.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
}

TEST_F(
    AsyncCheckTrackerTest,
    IsMainPageLoadPending_DeleteExpiredNavigationTimestamps_NotReachingThreshold) {
  tracker_->SetNavigationTimestampsSizeThresholdForTesting(
      kLocalNavigationTimestampsSizeThreshold);
  auto rfh_locator = UnsafeResourceLocator::CreateForFrameTreeNodeId(
      main_rfh()->GetFrameTreeNodeId().value());

  content::MockNavigationHandle handle(url_, main_rfh());
  CallDidFinishNavigation(handle, /*has_committed=*/true);
  EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, handle.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));

  task_environment()->FastForwardBy(base::Seconds(181));
  content::MockNavigationHandle recent_handle(url_, main_rfh());
  CallDidFinishNavigation(recent_handle, /*has_committed=*/true);
  // The timestamp has expired but not cleaned up, because the size of the
  // timestamps has not reached the threshold.
  EXPECT_FALSE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, handle.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));

  for (int i = 0; i < kLocalNavigationTimestampsSizeThreshold - 1; i++) {
    content::MockNavigationHandle new_handle(url_, main_rfh());
    CallDidFinishNavigation(new_handle, /*has_committed=*/true);
  }
  // The size of the timestamps has reached the threshold, so the old timestamp
  // is cleaned up.
  EXPECT_TRUE(AsyncCheckTracker::IsMainPageLoadPending(
      rfh_locator, handle.GetNavigationId(),
      SBThreatType::SB_THREAT_TYPE_URL_PHISHING));
}

TEST_F(AsyncCheckTrackerTest, IsPlatformEligibleForSyncCheckerCheckAllowlist) {
#if BUILDFLAG(IS_ANDROID)
  EXPECT_TRUE(
      AsyncCheckTracker::IsPlatformEligibleForSyncCheckerCheckAllowlist());
#else
  EXPECT_FALSE(
      AsyncCheckTracker::IsPlatformEligibleForSyncCheckerCheckAllowlist());
#endif
}

TEST_F(AsyncCheckTrackerTest, GetShouldSyncCheckerCheckAllowlist) {
  std::unique_ptr<content::WebContents> web_contents = CreateTestWebContents();
  auto* tracker = AsyncCheckTracker::GetOrCreateForWebContents(
      web_contents.get(), ui_manager_.get(),
      /*should_sync_checker_check_allowlist=*/true);
  EXPECT_TRUE(tracker->should_sync_checker_check_allowlist());
}

TEST_F(AsyncCheckTrackerTest, GetBlockedPageCommittedTimestamp) {
  content::MockNavigationHandle handle(web_contents());
  UnsafeResource resource;
  resource.threat_type = SBThreatType::SB_THREAT_TYPE_URL_PHISHING;
  resource.rfh_locator = UnsafeResourceLocator::CreateForFrameTreeNodeId(
      main_rfh()->GetFrameTreeNodeId().value());
  resource.navigation_id = handle.GetNavigationId();

  AsyncCheckTracker* tracker =
      AsyncCheckTracker::FromWebContents(web_contents());
  EXPECT_FALSE(AsyncCheckTracker::GetBlockedPageCommittedTimestamp(resource)
                   .has_value());

  tracker->DidFinishNavigation(&handle);
  // The navigation is not committed.
  EXPECT_FALSE(AsyncCheckTracker::GetBlockedPageCommittedTimestamp(resource)
                   .has_value());

  handle.set_has_committed(true);
  tracker->DidFinishNavigation(&handle);
  EXPECT_TRUE(AsyncCheckTracker::GetBlockedPageCommittedTimestamp(resource)
                  .has_value());
}

TEST_F(AsyncCheckTrackerTest,
       PendingCheckersManagement_TransferWithSameNavigationId) {
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 0u);
  CallTransferUrlChecker(/*navigation_id=*/1);
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 1u);
  CallTransferUrlChecker(/*navigation_id=*/2);
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 2u);
  // Transfer a checker with the same navigation id. This scenario can be
  // triggered by HTTP client hints.
  CallTransferUrlChecker(/*navigation_id=*/2);
  // The previous checker should be deleted. The deletion should happen on the
  // UI thread.
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 2u);
}

TEST_F(AsyncCheckTrackerTest,
       PendingCheckersManagement_DeleteOldCheckersAfterDidFinishNavigation) {
  base::HistogramTester histograms;
  content::MockNavigationHandle handle_1(url_, main_rfh());
  content::MockNavigationHandle handle_2(url_, main_rfh());
  content::MockNavigationHandle handle_3(url_, main_rfh());
  CallTransferUrlChecker(handle_1.GetNavigationId());
  histograms.ExpectUniqueSample("SafeBrowsing.AsyncCheck.PendingCheckersSize",
                                /*sample=*/1,
                                /*expected_count=*/1);
  CallTransferUrlChecker(handle_2.GetNavigationId());
  histograms.ExpectBucketCount("SafeBrowsing.AsyncCheck.PendingCheckersSize",
                               /*sample=*/2,
                               /*expected_count=*/1);
  CallTransferUrlChecker(handle_3.GetNavigationId());
  histograms.ExpectBucketCount("SafeBrowsing.AsyncCheck.PendingCheckersSize",
                               /*sample=*/3,
                               /*expected_count=*/1);
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 3u);

  // Only the third navigation is committed successfully.
  CallDidFinishNavigation(handle_1, /*has_committed=*/false);
  CallDidFinishNavigation(handle_2, /*has_committed=*/false);
  CallDidFinishNavigation(handle_3, /*has_committed=*/true);
  // Only keep the checker for the committed navigation.
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 1u);

  CallPendingCheckerCompleted(handle_3.GetNavigationId(), /*proceed=*/false,
                              /*has_post_commit_interstitial_skipped=*/true,
                              /*all_checks_completed=*/true);
  // The remaining checker is deleted because proceed is false.
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 0u);
}

TEST_F(AsyncCheckTrackerTest,
       PendingCheckersManagement_CheckerNotDeletedIfAllChecksCompletedFalse) {
  CallTransferUrlChecker(/*navigation_id=*/1);
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 1u);

  CallPendingCheckerCompleted(/*navigation_id=*/1, /*proceed=*/true,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/false);
  // If all_checks_completed is false, the checker should be kept alive to
  // receive upcoming result from the checker. This scenario can happen if there
  // are server redirects.
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 1u);

  CallPendingCheckerCompleted(/*navigation_id=*/1, /*proceed=*/true,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/true);
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 0u);
}

TEST_F(AsyncCheckTrackerTest,
       PendingCheckersManagement_DestructWithPendingCheckers) {
  CallTransferUrlChecker(/*navigation_id=*/1);
  CallTransferUrlChecker(/*navigation_id=*/2);
  EXPECT_EQ(tracker_->PendingCheckersSizeForTesting(), 2u);

  tracker_ = nullptr;
  DeleteContents();
  // Tracker is deleted together with the WebContents. pending checkers that the
  // tracker currently owns should also be deleted on the UI thread.
}

class AsyncCheckTrackerTestObserver : public AsyncCheckTracker::Observer {
 public:
  void OnAsyncSafeBrowsingCheckCompleted() override {
    async_check_completed_times_++;
  }
  void OnAsyncSafeBrowsingCheckTrackerDestructed() override {
    tracker_destructed_times_++;
  }
  int AsyncCheckCompletedTimes() { return async_check_completed_times_; }
  int TrackerDestructedTimes() { return tracker_destructed_times_; }

 private:
  int async_check_completed_times_ = 0;
  int tracker_destructed_times_ = 0;
};

class AsyncCheckTrackerObserverTest : public AsyncCheckTrackerTest {
 protected:
  AsyncCheckTrackerTestObserver observer_;
};

TEST_F(AsyncCheckTrackerObserverTest, OnAsyncSafeBrowsingCheckCompleted) {
  tracker_->AddObserver(&observer_);

  CallTransferUrlChecker(/*navigation_id=*/1);
  CallPendingCheckerCompleted(/*navigation_id=*/1, /*proceed=*/true,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/false);
  // Observer not notified, because all_checks_completed is false.
  EXPECT_EQ(observer_.AsyncCheckCompletedTimes(), 0);

  CallPendingCheckerCompleted(/*navigation_id=*/1, /*proceed=*/true,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/true);
  EXPECT_EQ(observer_.AsyncCheckCompletedTimes(), 1);
  CallTransferUrlChecker(/*navigation_id=*/2);
  CallPendingCheckerCompleted(/*navigation_id=*/2, /*proceed=*/true,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/true);
  EXPECT_EQ(observer_.AsyncCheckCompletedTimes(), 2);

  tracker_->RemoveObserver(&observer_);

  CallTransferUrlChecker(/*navigation_id=*/3);
  CallPendingCheckerCompleted(/*navigation_id=*/3, /*proceed=*/true,
                              /*has_post_commit_interstitial_skipped=*/false,
                              /*all_checks_completed=*/true);
  // Observer not notified, because it has removed itself.
  EXPECT_EQ(observer_.AsyncCheckCompletedTimes(), 2);
}

TEST_F(AsyncCheckTrackerObserverTest, AsyncCheckTrackerDeletedWhileObserving) {
  std::unique_ptr<content::WebContents> web_contents = CreateTestWebContents();
  auto* tracker = AsyncCheckTracker::GetOrCreateForWebContents(
      web_contents.get(), ui_manager_.get(),
      /*should_sync_checker_check_allowlist=*/false);
  tracker->AddObserver(&observer_);
  EXPECT_TRUE(observer_.IsInObserverList());

  web_contents.reset();
  // Ensure that the observer is auto removed after the tracker is deleted.
  EXPECT_FALSE(observer_.IsInObserverList());
  EXPECT_EQ(observer_.TrackerDestructedTimes(), 1);
}

#if BUILDFLAG(IS_ANDROID)
class AsyncCheckTrackerSyncCheckerCheckAllowlistDisabledTest
    : public AsyncCheckTrackerTest {
 protected:
  AsyncCheckTrackerSyncCheckerCheckAllowlistDisabledTest()
      : AsyncCheckTrackerTest() {
    feature_list_.InitAndDisableFeature(kSafeBrowsingSyncCheckerCheckAllowlist);
  }

  base::test::ScopedFeatureList feature_list_;
};

TEST_F(AsyncCheckTrackerSyncCheckerCheckAllowlistDisabledTest,
       IsPlatformEligibleForSyncCheckerCheckAllowlist) {
  EXPECT_FALSE(
      AsyncCheckTracker::IsPlatformEligibleForSyncCheckerCheckAllowlist());
}

#endif

}  // namespace safe_browsing