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

#include "components/safe_browsing/content/browser/client_side_detection_service.h"

#include <algorithm>
#include <memory>

#include "base/callback_list.h"
#include "base/containers/contains.h"
#include "base/containers/queue.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/escape.h"
#include "base/strings/strcat.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/optimization_guide/core/delivery/optimization_guide_model_provider.h"
#include "components/optimization_guide/core/optimization_guide_util.h"
#include "components/optimization_guide/proto/common_types.pb.h"
#include "components/optimization_guide/proto/models.pb.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/content/browser/client_side_phishing_model.h"
#include "components/safe_browsing/content/browser/web_ui/safe_browsing_ui.h"
#include "components/safe_browsing/content/common/safe_browsing.mojom.h"
#include "components/safe_browsing/core/common/fbs/client_model_generated.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/safe_browsing/core/common/proto/client_model.pb.h"
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/safe_browsing/core/common/safebrowsing_constants.h"
#include "components/safe_browsing/core/common/utils.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "crypto/sha2.h"
#include "google_apis/google_api_keys.h"
#include "ipc/ipc_channel_proxy.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/ip_address.h"
#include "net/base/load_flags.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "url/gurl.h"

using content::BrowserThread;

namespace safe_browsing {

const int ClientSideDetectionService::kReportsIntervalDays = 1;
const int ClientSideDetectionService::kMaxReportsPerInterval = 3;
const int ClientSideDetectionService::kNegativeCacheIntervalDays = 1;
const int ClientSideDetectionService::kPositiveCacheIntervalMinutes = 30;

const char ClientSideDetectionService::kClientReportPhishingUrl[] =
    "https://sb-ssl.google.com/safebrowsing/clientreport/phishing";

struct ClientSideDetectionService::ClientPhishingReportInfo {
  std::unique_ptr<network::SimpleURLLoader> loader;
  ClientReportPhishingRequestCallback callback;
  GURL phishing_url;
};

void LogOnDeviceModelSessionCreationSuccess(bool success) {
  base::UmaHistogramBoolean(
      "SBClientPhishing.OnDeviceModelSessionCreationSuccess", success);
}

void LogOnDeviceModelExecutionSuccessAndTime(
    bool success,
    base::TimeTicks session_execution_start_time) {
  base::UmaHistogramBoolean("SBClientPhishing.OnDeviceModelExecutionSuccess",
                            success);
  base::UmaHistogramMediumTimes(
      "SBClientPhishing.OnDeviceModelExecutionDuration",
      base::TimeTicks::Now() - session_execution_start_time);
}

void LogOnDeviceModelExecutionParse(bool success) {
  base::UmaHistogramBoolean(
      "SBClientPhishing.OnDeviceModelResponseParseSuccess", success);
}

void LogOnDeviceModelSessionAliveOnNewRequest(bool is_alive) {
  base::UmaHistogramBoolean(
      "SBClientPhishing.OnDeviceModelSessionAliveOnNewRequest", is_alive);
}

void LogOnDeviceModelCallbackStateOnSuccessfulResponse(bool is_alive) {
  base::UmaHistogramBoolean(
      "SBClientPhishing.OnDeviceModelSuccessfulResponseCallbackAlive",
      is_alive);
}

ClientSideDetectionService::CacheState::CacheState(bool phish, base::Time time)
    : is_phishing(phish), timestamp(time) {}

ClientSideDetectionService::ClientSideDetectionService(
    std::unique_ptr<Delegate> delegate,
    optimization_guide::OptimizationGuideModelProvider* opt_guide)
    : delegate_(std::move(delegate)) {
  // delegate and prefs can be null in unit tests.
  if (!delegate_ || !delegate_->GetPrefs()) {
    return;
  }

  if (!base::FeatureList::IsEnabled(kClientSideDetectionKillswitch) &&
      opt_guide) {
    client_side_phishing_model_ =
        std::make_unique<ClientSidePhishingModel>(opt_guide);
  }

  url_loader_factory_ = delegate_->GetSafeBrowsingURLLoaderFactory();

  pref_change_registrar_.Init(delegate_->GetPrefs());
  pref_change_registrar_.Add(
      prefs::kSafeBrowsingEnabled,
      base::BindRepeating(&ClientSideDetectionService::OnPrefsUpdated,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      prefs::kSafeBrowsingEnhanced,
      base::BindRepeating(&ClientSideDetectionService::OnPrefsUpdated,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      prefs::kSafeBrowsingScoutReportingEnabled,
      base::BindRepeating(&ClientSideDetectionService::OnPrefsUpdated,
                          base::Unretained(this)));

  // Load the report times from preferences.
  LoadPhishingReportTimesFromPrefs();

  //  Do an initial check of the prefs.
  OnPrefsUpdated();
}

ClientSideDetectionService::~ClientSideDetectionService() {
  weak_factory_.InvalidateWeakPtrs();
}

void ClientSideDetectionService::Shutdown() {
  url_loader_factory_.reset();
  delegate_->StopListeningToOnDeviceModelUpdate();
  delegate_.reset();
  enabled_ = false;
  client_side_phishing_model_.reset();
  on_device_model_available_ = false;
  if (session_) {
    session_.reset();
  }
}

void ClientSideDetectionService::OnPrefsUpdated() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  bool enabled = IsSafeBrowsingEnabled(*delegate_->GetPrefs());
  bool extended_reporting =
      IsEnhancedProtectionEnabled(*delegate_->GetPrefs()) ||
      IsExtendedReportingEnabled(*delegate_->GetPrefs());
  if (enabled == enabled_ && extended_reporting_ == extended_reporting) {
    return;
  }

  enabled_ = enabled;
  extended_reporting_ = extended_reporting;
  if (enabled_ && client_side_phishing_model_) {
    update_model_subscription_ = client_side_phishing_model_->RegisterCallback(
        base::BindRepeating(&ClientSideDetectionService::SendModelToRenderers,
                            weak_factory_.GetWeakPtr()));
    if (IsEnhancedProtectionEnabled(*delegate_->GetPrefs())) {
      client_side_phishing_model_->SubscribeToImageEmbedderOptimizationGuide();
      if (base::FeatureList::IsEnabled(
              kClientSideDetectionBrandAndIntentForScamDetection) ||
          base::FeatureList::IsEnabled(
              kClientSideDetectionLlamaForcedTriggerInfoForScamDetection)) {
        delegate_->StartListeningToOnDeviceModelUpdate();
      }
    } else {
      UnsubscribeToModelSubscription();
    }
  } else {
    // Invoke pending callbacks with a false verdict.
    for (auto& client_phishing_report : client_phishing_reports_) {
      ClientPhishingReportInfo* info = client_phishing_report.second.get();
      if (!info->callback.is_null()) {
        std::move(info->callback)
            .Run(info->phishing_url, false, std::nullopt, std::nullopt);
      }
    }

    // Unsubscribe to any SafeBrowsing preference related subscriptions if the
    // SafeBrowsing enabled state is false entirely or
    // client_side_phishing_model_ is unavailable.
    UnsubscribeToModelSubscription();

    client_phishing_reports_.clear();
    cache_.clear();
  }

  SendModelToRenderers();  // always refresh the renderer state
}

void ClientSideDetectionService::UnsubscribeToModelSubscription() {
  delegate_->StopListeningToOnDeviceModelUpdate();
  on_device_model_available_ = false;
  // We will check for the model object below because we also call this function
  // when the model object is not available.
  if (client_side_phishing_model_) {
    client_side_phishing_model_->UnsubscribeToImageEmbedderOptimizationGuide();
  }
}

void ClientSideDetectionService::NotifyOnDeviceModelAvailable() {
  on_device_model_available_ = true;
}

bool ClientSideDetectionService::IsOnDeviceModelAvailable(
    bool log_failed_eligibility_reason) {
  if (log_failed_eligibility_reason && !on_device_model_available_ &&
      delegate_) {
    delegate_->LogOnDeviceModelEligibilityReason();
  }
  return on_device_model_available_;
}

void ClientSideDetectionService::SendClientReportPhishingRequest(
    std::unique_ptr<ClientPhishingRequest> verdict,
    ClientReportPhishingRequestCallback callback,
    const std::string& access_token) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &ClientSideDetectionService::StartClientReportPhishingRequest,
          weak_factory_.GetWeakPtr(), std::move(verdict), std::move(callback),
          access_token));
}

bool ClientSideDetectionService::IsPrivateIPAddress(
    const net::IPAddress& address) const {
  return !address.IsPubliclyRoutable();
}

bool ClientSideDetectionService::IsLocalResource(
    const net::IPAddress& address) const {
  return !address.IsValid();
}

void ClientSideDetectionService::OnURLLoaderComplete(
    network::SimpleURLLoader* url_loader,
    base::Time start_time,
    std::unique_ptr<std::string> response_body) {
  base::UmaHistogramTimes("SBClientPhishing.NetworkRequestDuration",
                          base::Time::Now() - start_time);

  std::string data;
  if (response_body) {
    data = std::move(*response_body.get());
  }
  std::optional<net::HttpStatusCode> response_code = std::nullopt;
  if (url_loader->ResponseInfo() && url_loader->ResponseInfo()->headers) {
    response_code = static_cast<net::HttpStatusCode>(
        url_loader->ResponseInfo()->headers->response_code());
  }
  RecordHttpResponseOrErrorCode(
      "SBClientPhishing.NetworkResult2", url_loader->NetError(),
      response_code.has_value() ? response_code.value() : 0);

  DCHECK(base::Contains(client_phishing_reports_, url_loader));
  HandlePhishingVerdict(url_loader, url_loader->GetFinalURL(),
                        url_loader->NetError(), response_code, data);
}

void ClientSideDetectionService::SendModelToRenderers() {
  // We will not send models to the renderer process if the feature is disabled.
  // This is because the feature can be disabled via Finch in a scenario where a
  // bad model is uploaded to the server.
  if (base::FeatureList::IsEnabled(kClientSideDetectionKillswitch)) {
    return;
  }
  for (content::RenderProcessHost::iterator it(
           content::RenderProcessHost::AllHostsIterator());
       !it.IsAtEnd(); it.Advance()) {
    if (delegate_->ShouldSendModelToBrowserContext(
            it.GetCurrentValue()->GetBrowserContext())) {
      auto* rph = it.GetCurrentValue();
      if (rph->IsReady()) {
        SetPhishingModel(rph, /*new_renderer_process_host=*/false);
      } else {
        if (rph->IsInitializedAndNotDead() &&
            !observed_render_process_hosts_.IsObservingSource(rph)) {
          observed_render_process_hosts_.AddObservation(rph);
        }
      }
    }
  }
  if (client_side_phishing_model_) {
    trigger_model_version_ =
        client_side_phishing_model_->GetTriggerModelVersion();
  }
}

void ClientSideDetectionService::StartClientReportPhishingRequest(
    std::unique_ptr<ClientPhishingRequest> request,
    ClientReportPhishingRequestCallback callback,
    const std::string& access_token) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!enabled_) {
    if (!callback.is_null()) {
      std::move(callback).Run(GURL(request->url()), false, std::nullopt,
                              std::nullopt);
    }
    return;
  }

  // Record that we made a request. Logged before the request is made
  // to ensure it gets recorded. If this returns false due to being at ping cap
  // or prefs are null, abandon the request.
  if (!AddPhishingReport(base::Time::Now())) {
    if (!callback.is_null()) {
      std::move(callback).Run(GURL(request->url()), false, std::nullopt,
                              std::nullopt);
    }
    return;
  }

  std::string request_data;
  request->SerializeToString(&request_data);

  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation(
          "safe_browsing_client_side_phishing_detector", R"(
          semantics {
            sender: "Safe Browsing Client-Side Phishing Detector"
            description:
              "If the client-side phishing detector determines that the "
              "current page contents are similar to phishing pages, it will "
              "send a request to Safe Browsing to ask for a final verdict. If "
              "Safe Browsing agrees the page is dangerous, Chrome will show a "
              "full-page interstitial warning."
            trigger:
              "Whenever the clinet-side detector machine learning model "
              "computes a phishy-ness score above a threshold, after page-load."
            data:
              "Top-level page URL without CGI parameters, boolean and double "
              "features extracted from DOM, such as the number of resources "
              "loaded in the page, if certain likely phishing and social "
              "engineering terms found on the page, etc."
            destination: GOOGLE_OWNED_SERVICE
          }
          policy {
            cookies_allowed: YES
            cookies_store: "Safe browsing cookie store"
            setting:
              "Users can enable or disable this feature by toggling 'Protect "
              "you and your device from dangerous sites' in Chrome settings "
              "under Privacy. This feature is enabled by default."
            chrome_policy {
              SafeBrowsingProtectionLevel {
                policy_options {mode: MANDATORY}
                SafeBrowsingProtectionLevel: 0
              }
            }
            chrome_policy {
              SafeBrowsingEnabled {
                policy_options {mode: MANDATORY}
                SafeBrowsingEnabled: false
              }
            }
            deprecated_policies: "SafeBrowsingEnabled"
          })");
  auto resource_request = std::make_unique<network::ResourceRequest>();
  if (!access_token.empty()) {
    LogAuthenticatedCookieResets(
        *resource_request,
        SafeBrowsingAuthenticatedEndpoint::kClientSideDetection);
    SetAccessToken(resource_request.get(), access_token);
  }

  resource_request->url = GetClientReportUrl(kClientReportPhishingUrl);
  resource_request->method = "POST";
  resource_request->load_flags = net::LOAD_DISABLE_CACHE;

  auto loader = network::SimpleURLLoader::Create(std::move(resource_request),
                                                 traffic_annotation);
  loader->AttachStringForUpload(request_data, "application/octet-stream");
  loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      url_loader_factory_.get(),
      base::BindOnce(&ClientSideDetectionService::OnURLLoaderComplete,
                     base::Unretained(this), loader.get(), base::Time::Now()));

  // Remember which callback and URL correspond to the current fetcher object.
  std::unique_ptr<ClientPhishingReportInfo> info(new ClientPhishingReportInfo);
  auto* loader_ptr = loader.get();
  info->loader = std::move(loader);
  info->callback = std::move(callback);
  info->phishing_url = GURL(request->url());
  client_phishing_reports_[loader_ptr] = std::move(info);

  // The following is to log this ClientPhishingRequest on any open
  // chrome://safe-browsing pages. If no such page is open, the request is
  // dropped and the |request| object deleted.
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(&WebUIInfoSingleton::AddToClientPhishingRequestsSent,
                     base::Unretained(WebUIInfoSingleton::GetInstance()),
                     std::move(request), access_token));
}

void ClientSideDetectionService::HandlePhishingVerdict(
    network::SimpleURLLoader* source,
    const GURL& url,
    int net_error,
    std::optional<net::HttpStatusCode> response_code,
    const std::string& data) {
  ClientPhishingResponse response;
  std::unique_ptr<ClientPhishingReportInfo> info =
      std::move(client_phishing_reports_[source]);
  client_phishing_reports_.erase(source);

  bool is_phishing = false;
  std::optional<IntelligentScanVerdict> intelligent_scan_verdict = std::nullopt;
  if (net_error == net::OK && response_code.has_value() &&
      net::HTTP_OK == response_code.value() && response.ParseFromString(data)) {
    // Cache response, possibly flushing an old one.
    cache_[info->phishing_url] =
        base::WrapUnique(new CacheState(response.phishy(), base::Time::Now()));
    is_phishing = response.phishy();
    if (response.has_intelligent_scan_verdict()) {
      intelligent_scan_verdict = response.intelligent_scan_verdict();
    }
  }

  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(&WebUIInfoSingleton::AddToClientPhishingResponsesReceived,
                     base::Unretained(WebUIInfoSingleton::GetInstance()),
                     std::make_unique<ClientPhishingResponse>(response)));

  if (!info->callback.is_null()) {
    if (response_code.has_value() && response_code.value() == 0) {
      response_code = std::nullopt;
    }

    std::move(info->callback)
        .Run(info->phishing_url, is_phishing, response_code,
             intelligent_scan_verdict);
  }
}

bool ClientSideDetectionService::GetValidCachedResult(const GURL& url,
                                                      bool* is_phishing) {
  UpdateCache();

  auto it = cache_.find(url);
  if (it == cache_.end()) {
    return false;
  }

  // We still need to check if the result is valid.
  const CacheState& cache_state = *it->second;
  if (cache_state.is_phishing
          ? cache_state.timestamp >
                base::Time::Now() - base::Minutes(kPositiveCacheIntervalMinutes)
          : cache_state.timestamp >
                base::Time::Now() - base::Days(kNegativeCacheIntervalDays)) {
    *is_phishing = cache_state.is_phishing;
    return true;
  }
  return false;
}

void ClientSideDetectionService::UpdateCache() {
  // Since we limit the number of requests but allow pass-through for cache
  // refreshes, we don't want to remove elements from the cache if they
  // could be used for this purpose even if we will not use the entry to
  // satisfy the request from the cache.
  base::TimeDelta positive_cache_interval =
      std::max(base::Minutes(kPositiveCacheIntervalMinutes),
               base::Days(kReportsIntervalDays));
  base::TimeDelta negative_cache_interval = std::max(
      base::Days(kNegativeCacheIntervalDays), base::Days(kReportsIntervalDays));

  // Remove elements from the cache that will no longer be used.
  for (auto it = cache_.begin(); it != cache_.end();) {
    const CacheState& cache_state = *it->second;
    if (cache_state.is_phishing
            ? cache_state.timestamp >
                  base::Time::Now() - positive_cache_interval
            : cache_state.timestamp >
                  base::Time::Now() - negative_cache_interval) {
      ++it;
    } else {
      cache_.erase(it++);
    }
  }
}

bool ClientSideDetectionService::AtPhishingReportLimit() {
  // Clear the expired timestamps
  const auto cutoff = base::Time::Now() - base::Days(kReportsIntervalDays);
  // Erase items older than cutoff because we will never care about them again.
  while (!phishing_report_times_.empty() &&
         phishing_report_times_.front() < cutoff) {
    phishing_report_times_.pop_front();
  }

  // `delegate_` and prefs can be null in unit tests.
  if (base::FeatureList::IsEnabled(kSafeBrowsingDailyPhishingReportsLimit) &&
      (delegate_ && delegate_->GetPrefs()) &&
      IsEnhancedProtectionEnabled(*delegate_->GetPrefs())) {
    return GetPhishingNumReports() >=
           kSafeBrowsingDailyPhishingReportsLimitESB.Get();
  }
  return GetPhishingNumReports() >= kMaxReportsPerInterval;
}

int ClientSideDetectionService::GetPhishingNumReports() {
  return phishing_report_times_.size();
}

bool ClientSideDetectionService::AddPhishingReport(base::Time timestamp) {
  // We should not be adding a report when we are at the limit when this
  // function calls, but in case it does, we want to track how far back the
  // last report was prior to the current report and exit the function early.
  // Each classification request is made on the tab level, which may not have
  // had |phishing_report_times_| updated because the service class, that's on
  // the profile level, was processing a different request. Therefore, we check
  // one last time before we log the request.
  if (AtPhishingReportLimit()) {
    base::UmaHistogramMediumTimes("SBClientPhishing.TimeSinceLastReportAtLimit",
                                  timestamp - phishing_report_times_.back());
    return false;
  }

  if (!delegate_ || !delegate_->GetPrefs()) {
    base::UmaHistogramBoolean("SBClientPhishing.AddPhishingReportSuccessful",
                              false);
    return false;
  }

  phishing_report_times_.push_back(timestamp);

  base::Value::List time_list;
  for (const base::Time& report_time : phishing_report_times_) {
    time_list.Append(base::Value(report_time.InSecondsFSinceUnixEpoch()));
  }
  delegate_->GetPrefs()->SetList(prefs::kSafeBrowsingCsdPingTimestamps,
                                 std::move(time_list));
  base::UmaHistogramBoolean("SBClientPhishing.AddPhishingReportSuccessful",
                            true);

  return true;
}

void ClientSideDetectionService::LoadPhishingReportTimesFromPrefs() {
  // delegate and prefs can be null in unit tests.
  if (!delegate_ || !delegate_->GetPrefs()) {
    return;
  }

  phishing_report_times_.clear();
  const auto cutoff = base::Time::Now() - base::Days(kReportsIntervalDays);
  for (const base::Value& timestamp :
       delegate_->GetPrefs()->GetList(prefs::kSafeBrowsingCsdPingTimestamps)) {
    auto time = base::Time::FromSecondsSinceUnixEpoch(timestamp.GetDouble());
    if (time >= cutoff) {
      phishing_report_times_.push_back(time);
    }
  }
}

// static
GURL ClientSideDetectionService::GetClientReportUrl(
    const std::string& report_url) {
  GURL url(report_url);
  std::string api_key = google_apis::GetAPIKey();
  if (!api_key.empty()) {
    url = url.Resolve("?key=" + base::EscapeQueryParamValue(api_key, true));
  }

  return url;
}

CSDModelType ClientSideDetectionService::GetModelType() {
  return client_side_phishing_model_
             ? client_side_phishing_model_->GetModelType()
             : CSDModelType::kNone;
}

base::ReadOnlySharedMemoryRegion
ClientSideDetectionService::GetModelSharedMemoryRegion() {
  return client_side_phishing_model_->GetModelSharedMemoryRegion();
}

const base::File& ClientSideDetectionService::GetVisualTfLiteModel() {
  return client_side_phishing_model_->GetVisualTfLiteModel();
}

const base::File& ClientSideDetectionService::GetImageEmbeddingModel() {
  // At launch, we will only deploy the Image Embedding Model through
  // OptimizationGuide
  return client_side_phishing_model_->GetImageEmbeddingModel();
}

bool ClientSideDetectionService::
    IsModelMetadataImageEmbeddingVersionMatching() {
  return client_side_phishing_model_ &&
         client_side_phishing_model_
             ->IsModelMetadataImageEmbeddingVersionMatching();
}

void ClientSideDetectionService::SetURLLoaderFactoryForTesting(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
  url_loader_factory_ = url_loader_factory;
}

void ClientSideDetectionService::OnRenderProcessHostCreated(
    content::RenderProcessHost* rph) {
  if (delegate_->ShouldSendModelToBrowserContext(rph->GetBrowserContext())) {
    // The |rph| is ready, so the model can immediately be send.
    if (rph->IsReady()) {
      SetPhishingModel(rph, /*new_renderer_process_host=*/true);
    } else if (!observed_render_process_hosts_.IsObservingSource(rph)) {
      // Postpone sending the model until the |rph| is ready.
      observed_render_process_hosts_.AddObservation(rph);
    }
  }
}

void ClientSideDetectionService::RenderProcessHostDestroyed(
    content::RenderProcessHost* rph) {
  if (observed_render_process_hosts_.IsObservingSource(rph)) {
    observed_render_process_hosts_.RemoveObservation(rph);
  }
}

void ClientSideDetectionService::RenderProcessReady(
    content::RenderProcessHost* rph) {
  SetPhishingModel(rph, /*new_renderer_process_host=*/true);
  if (observed_render_process_hosts_.IsObservingSource(rph)) {
    observed_render_process_hosts_.RemoveObservation(rph);
  }
}

void ClientSideDetectionService::SetPhishingModel(
    content::RenderProcessHost* rph,
    bool new_renderer_process_host) {
  // We want to check if the trigger model has been sent. If we have received a
  // callback after sending the trigger models before and the models are now
  // unavailable, that means the OptimizationGuide server sent us a null model
  // to signal that a bad model is in disk.
  if (!IsModelAvailable() && !sent_trigger_models_) {
    return;
  }
  if (!rph->GetChannel()) {
    return;
  }

  mojo::AssociatedRemote<mojom::PhishingModelSetter> model_setter;
  rph->GetChannel()->GetRemoteAssociatedInterface(&model_setter);
  if (!IsModelAvailable() && sent_trigger_models_) {
    model_setter->ClearScorer();
    return;
  }

  switch (GetModelType()) {
    case CSDModelType::kNone:
      return;
    case CSDModelType::kFlatbuffer:
      if (delegate_ && delegate_->GetPrefs() &&
          IsEnhancedProtectionEnabled(*delegate_->GetPrefs())) {
        // The check for image embedding model is important because the
        // OptimizationGuide server can send a null image embedding model to
        // signal there is a bad model in disk. If the image embedding model
        // isn't available because of this, the scorer will be created without
        // the image embedder model, temporarily halting the image embedding
        // process on the renderer.
        if (IsModelMetadataImageEmbeddingVersionMatching() &&
            HasImageEmbeddingModel()) {
          base::UmaHistogramBoolean(
              "SBClientPhishing.ImageEmbeddingModelVersionMatch", true);
          if (!new_renderer_process_host &&
              trigger_model_version_ ==
                  client_side_phishing_model_->GetTriggerModelVersion()) {
            // If the trigger model version remains the same in the same
            // renderer process host, we can just attach the complementary image
            // embedding model to the current scorer.
            model_setter->AttachImageEmbeddingModel(
                GetImageEmbeddingModel().Duplicate());
          } else {
            model_setter->SetImageEmbeddingAndPhishingFlatBufferModel(
                GetModelSharedMemoryRegion(),
                GetVisualTfLiteModel().Duplicate(),
                GetImageEmbeddingModel().Duplicate());
          }
        } else {
          base::UmaHistogramBoolean(
              "SBClientPhishing.ImageEmbeddingModelVersionMatch", false);
          model_setter->SetPhishingFlatBufferModel(
              GetModelSharedMemoryRegion(), GetVisualTfLiteModel().Duplicate());
        }
      } else {
        model_setter->SetPhishingFlatBufferModel(
            GetModelSharedMemoryRegion(), GetVisualTfLiteModel().Duplicate());
      }
      sent_trigger_models_ = true;
      return;
  }
}

const base::flat_map<std::string, TfLiteModelMetadata::Threshold>&
ClientSideDetectionService::GetVisualTfLiteModelThresholds() {
  return client_side_phishing_model_->GetVisualTfLiteModelThresholds();
}

void ClientSideDetectionService::ClassifyPhishingThroughThresholds(
    ClientPhishingRequest* verdict) {
  // This is added so that client_side_detection_host_unittest.cc can pass.
  // Outside of the test, this should never occur because the model should have
  // been available in order to receive the verdict in the first place.
  if (!IsModelAvailable()) {
    return;
  }

  const base::flat_map<std::string, TfLiteModelMetadata::Threshold>&
      label_to_thresholds_map = GetVisualTfLiteModelThresholds();

  if (static_cast<int>(verdict->tflite_model_scores().size()) >
      static_cast<int>(label_to_thresholds_map.size())) {
    // Model is misconfigured, so bail out.
    base::UmaHistogramEnumeration(
        "SBClientPhishing.ClassifyThresholdsResult",
        SBClientDetectionClassifyThresholdsResult::kModelSizeMismatch);
    VLOG(0) << "Model is misconfigured. Size is mismatched. Verdict scores "
               "size is "
            << static_cast<int>(verdict->tflite_model_scores().size())
            << " and model thresholds size is "
            << static_cast<int>(label_to_thresholds_map.size());
    verdict->set_is_phishing(false);
    verdict->set_is_tflite_match(false);
    return;
  }

  for (int i = 0; i < verdict->tflite_model_scores().size(); i++) {
    // Users can have older models that do not have the esb thresholds in their
    // fields, so ESB subscribed users will use the standard thresholds instead
    auto result = label_to_thresholds_map.find(
        verdict->tflite_model_scores().at(i).label());

    if (result == label_to_thresholds_map.end()) {
      // Model is misconfigured, so bail out.
      base::UmaHistogramEnumeration(
          "SBClientPhishing.ClassifyThresholdsResult",
          SBClientDetectionClassifyThresholdsResult::kModelLabelNotFound);
      VLOG(0) << "Model is misconfigured. Unable to match label string to "
                 "threshold map";
      verdict->set_is_phishing(false);
      verdict->set_is_tflite_match(false);
      return;
    }

    const TfLiteModelMetadata::Threshold& thresholds = result->second;

    if (delegate_ && delegate_->GetPrefs() &&
        IsEnhancedProtectionEnabled(*delegate_->GetPrefs())) {
      if (verdict->tflite_model_scores().at(i).value() >=
          thresholds.esb_threshold()) {
        verdict->set_is_phishing(true);
        verdict->set_is_tflite_match(true);
      }
    } else {
      if (verdict->tflite_model_scores().at(i).value() >=
          thresholds.threshold()) {
        verdict->set_is_phishing(true);
        verdict->set_is_tflite_match(true);
      }
    }
  }

  base::UmaHistogramEnumeration(
      "SBClientPhishing.ClassifyThresholdsResult",
      SBClientDetectionClassifyThresholdsResult::kSuccess);
}

base::WeakPtr<ClientSideDetectionService>
ClientSideDetectionService::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

bool ClientSideDetectionService::IsModelAvailable() {
  if (base::FeatureList::IsEnabled(kClientSideDetectionKillswitch)) {
    return false;
  }

  return client_side_phishing_model_ &&
         client_side_phishing_model_->IsEnabled();
}

int ClientSideDetectionService::GetTriggerModelVersion() {
  return trigger_model_version_;
}

bool ClientSideDetectionService::HasImageEmbeddingModel() {
  return client_side_phishing_model_ &&
         client_side_phishing_model_->HasImageEmbeddingModel();
}

bool ClientSideDetectionService::IsSubscribedToImageEmbeddingModelUpdates() {
  return client_side_phishing_model_ &&
         client_side_phishing_model_
             ->IsSubscribedToImageEmbeddingModelUpdates();
}

base::CallbackListSubscription
ClientSideDetectionService::RegisterCallbackForModelUpdates(
    base::RepeatingCallback<void()> callback) {
  return client_side_phishing_model_->RegisterCallback(callback);
}

void ClientSideDetectionService::ResetOnDeviceSession(bool inquiry_complete) {
  // Because of the use of DeleteSoon below, we can't guarantee that session_
  // is still available when the callback is invoked.
  if (session_) {
    // Reset session immediately so that future inference is not affected by the
    // old context.
    // TODO(crbug.com/380928557): Call session_.reset() directly once
    // crbug.com/384774788 is fixed.
    content::GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE,
                                                   std::move(session_));
    if (!inquiry_complete) {
      LogOnDeviceModelSessionAliveOnNewRequest(true);
    }
  }
}

void ClientSideDetectionService::InquireOnDeviceModel(
    std::string rendered_texts,
    base::OnceCallback<
        void(std::optional<optimization_guide::proto::ScamDetectionResponse>)>
        callback) {
  // We have checked the model availability prior to calling this function, but
  // we want to check one last time before creating a session.
  if (!IsOnDeviceModelAvailable(/*log_failed_eligibility_reason=*/false)) {
    std::move(callback).Run(std::nullopt);
    return;
  }

  // Close off the previous session if session's model execution from a previous
  // call into InquireOnDeviceModel is still happening.
  if (session_) {
    LogOnDeviceModelSessionAliveOnNewRequest(true);
    session_.reset();
  } else {
    LogOnDeviceModelSessionAliveOnNewRequest(false);
  }

  base::TimeTicks session_creation_start_time = base::TimeTicks::Now();

  session_ = delegate_->GetModelExecutorSession();

  if (!session_) {
    LogOnDeviceModelSessionCreationSuccess(false);
    std::move(callback).Run(std::nullopt);
    return;
  }

  base::UmaHistogramMediumTimes(
      "SBClientPhishing.OnDeviceModelSessionCreationTime",
      base::TimeTicks::Now() - session_creation_start_time);
  LogOnDeviceModelSessionCreationSuccess(true);

  ScamDetectionRequest request;
  request.set_rendered_text(rendered_texts);

  inquire_on_device_model_callback_ = std::move(callback);
  session_execution_start_time_ = base::TimeTicks::Now();
  session_->ExecuteModel(
      *std::make_unique<ScamDetectionRequest>(request),
      base::BindRepeating(&ClientSideDetectionService::ModelExecutionCallback,
                          weak_factory_.GetWeakPtr()));
}

void ClientSideDetectionService::ModelExecutionCallback(
    optimization_guide::OptimizationGuideModelStreamingExecutionResult result) {
  if (!result.response.has_value()) {
    LogOnDeviceModelExecutionSuccessAndTime(/*success=*/false,
                                            session_execution_start_time_);
    if (inquire_on_device_model_callback_) {
      std::move(inquire_on_device_model_callback_).Run(std::nullopt);
    }
    return;
  }

  // This is a non-error response, but it's not completed, yet so we wait till
  // it's complete. We will not respond to the callback yet because of this.
  if (!result.response->is_complete) {
    return;
  }

  LogOnDeviceModelExecutionSuccessAndTime(/*success=*/true,
                                          session_execution_start_time_);

  auto scam_detection_response = optimization_guide::ParsedAnyMetadata<
      optimization_guide::proto::ScamDetectionResponse>(
      result.response->response);

  if (!scam_detection_response) {
    LogOnDeviceModelExecutionParse(false);
    if (inquire_on_device_model_callback_) {
      std::move(inquire_on_device_model_callback_).Run(std::nullopt);
    }
    return;
  }

  LogOnDeviceModelExecutionParse(true);

  ResetOnDeviceSession(/*inquiry_complete=*/true);

  LogOnDeviceModelCallbackStateOnSuccessfulResponse(
      !!inquire_on_device_model_callback_);
  if (inquire_on_device_model_callback_) {
    std::move(inquire_on_device_model_callback_).Run(scam_detection_response);
  }
}

// IN-TEST
void ClientSideDetectionService::SetModelAndVisualTfLiteForTesting(
    const base::FilePath& model,
    const base::FilePath& visual_tf_lite) {
  client_side_phishing_model_->SetModelAndVisualTfLiteForTesting(  // IN-TEST
      model, visual_tf_lite);
}

// IN-TEST
void ClientSideDetectionService::SetOnDeviceAvailabilityForTesting(
    bool available) {
  on_device_model_available_ = available;
}

}  // namespace safe_browsing