File: verdict_cache_manager.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 (1267 lines) | stat: -rw-r--r-- 48,263 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
// Copyright 2019 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/core/browser/verdict_cache_manager.h"

#include <optional>
#include <string_view>

#include "base/base64.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/history/core/browser/history_service_observer.h"
#include "components/safe_browsing/core/browser/db/v4_protocol_manager_util.h"
#include "components/safe_browsing/core/common/hashprefix_realtime/hash_realtime_utils.h"
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "components/safe_browsing/core/common/safebrowsing_constants.h"
#include "components/safe_browsing/core/common/safebrowsing_switches.h"

namespace safe_browsing {

namespace {

// Keys for storing password protection verdict into a base::Value::Dict.
const char kCacheCreationTime[] = "cache_creation_time";
const char kVerdictProto[] = "verdict_proto";
const char kRealTimeThreatInfoProto[] = "rt_threat_info_proto";
const char kPasswordOnFocusCacheKey[] = "password_on_focus_cache_key";
const char kRealTimeUrlCacheKey[] = "real_time_url_cache_key";
const char kCsdTypeCacheKey[] = "client_side_detection_type_cache_key";
const char kLlamaForcedTriggerInfoKey[] = "llama_forced_trigger_info_key";

// The maximum number of entries to be removed in a single cleanup. Removing too
// many entries all at once could cause jank.
const int kMaxRemovedEntriesCount = 1000;

// The interval between the construction and the first cleanup is performed.
const int kCleanUpIntervalInitSecond = 120;

// The interval between every cleanup task.
const int kCleanUpIntervalSecond = 1800;

// The longest duration that a cache can be stored. If a cache is stored
// longer than the upper bound, it will be evicted.
const int kCacheDurationUpperBoundSecond = 7 * 24 * 60 * 60;  // 7 days

// The length of a randomly generated page load token.
const int kPageLoadTokenBytes = 32;

// The expiration time of a page load token.
const int kPageLoadTokenExpireMinute = 10;

// A helper class to include all match params. It is used as a centralized
// place to determine if the current cache entry should be considered as a
// match.
struct MatchParams {
  MatchParams() = default;
  bool ShouldMatch() {
    return !is_only_exact_match_allowed || (is_exact_host && is_exact_path);
  }
  // Indicates whether the current cache entry and the url have the same host.
  bool is_exact_host = false;
  // Indicates whether the current cache entry and the url have the same path.
  bool is_exact_path = false;
  // Indicates whether the current cache entry is only applicable for exact
  // match.
  bool is_only_exact_match_allowed = true;
};

// Given a URL of either http or https scheme, return its http://hostname.
// e.g., "https://www.foo.com:80/bar/test.cgi" -> "http://www.foo.com".
GURL GetHostNameWithHTTPScheme(const GURL& url) {
  DCHECK(url.SchemeIsHTTPOrHTTPS());
  std::string result(url::kHttpScheme);
  result.append(url::kStandardSchemeSeparator).append(url.host());
  return GURL(result);
}
// e.g, ("www.foo.com", "/bar/test.cgi") -> "http://www.foo.com/bar/test/cgi"
GURL GetUrlWithHostAndPath(const std::string& host, const std::string& path) {
  std::string result(url::kHttpScheme);
  result.append(url::kStandardSchemeSeparator).append(host).append(path);
  return GURL(result);
}

// e.g, "www.foo.com/bar/test/cgi" -> "http://www.foo.com"
GURL GetHostNameFromCacheExpression(const std::string& cache_expression) {
  std::string cache_expression_url(url::kHttpScheme);
  cache_expression_url.append(url::kStandardSchemeSeparator)
      .append(cache_expression);
  return GetHostNameWithHTTPScheme(GURL(cache_expression_url));
}

// Convert a Proto object into a base::Value::Dict.
template <class T>
base::Value::Dict CreateDictionaryFromVerdict(const T& verdict,
                                              const base::Time& receive_time,
                                              const char* proto_name) {
  DCHECK(proto_name == kVerdictProto || proto_name == kRealTimeThreatInfoProto);
  base::Value::Dict result;
  result.Set(kCacheCreationTime,
             static_cast<int>(receive_time.InSecondsFSinceUnixEpoch()));
  std::string serialized_proto(verdict.SerializeAsString());
  // Performs a base64 encoding on the serialized proto.
  serialized_proto = base::Base64Encode(serialized_proto);
  result.Set(proto_name, serialized_proto);
  return result;
}

template <class T>
base::Value::Dict CreateDictionaryFromVerdict(
    const T& verdict,
    const base::Time& receive_time,
    const char* proto_name,
    const safe_browsing::ClientSideDetectionType csd_type,
    const safe_browsing::LlamaForcedTriggerInfo llama_forced_trigger_info) {
  base::Value::Dict result =
      CreateDictionaryFromVerdict(verdict, receive_time, proto_name);
  result.Set(kCsdTypeCacheKey, static_cast<int>(csd_type));
  std::string serialized_proto(llama_forced_trigger_info.SerializeAsString());
  // Performs a base64 encoding on the serialized proto.
  serialized_proto = base::Base64Encode(serialized_proto);
  if (!serialized_proto.empty()) {
    result.Set(kLlamaForcedTriggerInfoKey, serialized_proto);
  }

  return result;
}

// Generate path variants of the given URL.
void GeneratePathVariantsWithoutQuery(const GURL& url,
                                      std::vector<std::string>* paths) {
  std::string canonical_path;
  V4ProtocolManagerUtil::CanonicalizeUrl(
      url, /*canonicalized_hostname=*/nullptr, &canonical_path,
      /*canonicalized_query=*/nullptr);
  V4ProtocolManagerUtil::GeneratePathVariantsToCheck(canonical_path,
                                                     std::string(), paths);
}

template <class T>
bool ParseVerdictEntry(base::Value* verdict_entry,
                       int* out_verdict_received_time,
                       T* out_verdict,
                       const char* proto_name) {
  DCHECK(proto_name == kVerdictProto || proto_name == kRealTimeThreatInfoProto);

  if (!verdict_entry || !verdict_entry->is_dict() || !out_verdict) {
    return false;
  }

  const base::Value::Dict& dict = verdict_entry->GetDict();
  std::optional<int> cache_creation_time = dict.FindInt(kCacheCreationTime);

  if (!cache_creation_time) {
    return false;
  }
  *out_verdict_received_time = cache_creation_time.value();

  const std::string* verdict_proto = dict.FindString(proto_name);
  if (!verdict_proto) {
    return false;
  }

  std::string serialized_proto;
  return base::Base64Decode(*verdict_proto, &serialized_proto) &&
         out_verdict->ParseFromString(serialized_proto);
}

// Return the path of the cache expression. e.g.:
// "www.google.com"     -> ""
// "www.google.com/abc" -> "/abc"
// "foo.com/foo/bar/"  -> "/foo/bar/"
std::string GetCacheExpressionPath(const std::string& cache_expression) {
  DCHECK(!cache_expression.empty());
  size_t first_slash_pos = cache_expression.find_first_of("/");
  if (first_slash_pos == std::string::npos) {
    return "";
  }
  return cache_expression.substr(first_slash_pos);
}

// Returns the number of path segments in |cache_expression_path|.
// For example, return 0 for "/", since there is no path after the leading
// slash; return 3 for "/abc/def/gh.html".
size_t GetPathDepth(const std::string& cache_expression_path) {
  return base::SplitString(std::string_view(cache_expression_path), "/",
                           base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)
      .size();
}

size_t GetHostDepth(const std::string& hostname) {
  return base::SplitString(std::string_view(hostname), ".",
                           base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)
      .size();
}

bool PathVariantsMatchCacheExpression(
    const std::vector<std::string>& generated_paths,
    const std::string& cache_expression_path) {
  return base::Contains(generated_paths, cache_expression_path);
}

bool IsCacheExpired(int cache_creation_time, int cache_duration) {
  // Note that we assume client's clock is accurate or almost accurate.
  return base::Time::Now().InSecondsFSinceUnixEpoch() >
         static_cast<double>(cache_creation_time + cache_duration);
}

bool IsCacheOlderThanUpperBound(int cache_creation_time) {
  return base::Time::Now().InSecondsFSinceUnixEpoch() >
         static_cast<double>(cache_creation_time +
                             kCacheDurationUpperBoundSecond);
}

template <class T>
VerdictCacheManager::DictionaryCounts ComputeCountsAndMaybeRemoveExpiredEntries(
    base::Value::Dict& verdict_dictionary,
    const char* proto_name,
    bool remove_entries) {
  DCHECK(proto_name == kVerdictProto || proto_name == kRealTimeThreatInfoProto);
  std::vector<std::string> expired_keys;
  VerdictCacheManager::DictionaryCounts counts;
  counts.num_entries = verdict_dictionary.size();
  if (!remove_entries) {
    // Return early if we are just interested in the entry count, not in
    // removing expired entries.
    return counts;
  }

  for (auto item : verdict_dictionary) {
    int verdict_received_time;
    T verdict;
    if (!ParseVerdictEntry<T>(&item.second, &verdict_received_time, &verdict,
                              proto_name) ||
        IsCacheExpired(verdict_received_time, verdict.cache_duration_sec()) ||
        IsCacheOlderThanUpperBound(verdict_received_time)) {
      expired_keys.push_back(item.first);
    }
  }

  for (const std::string& key : expired_keys) {
    verdict_dictionary.Remove(key);
  }

  counts.num_removed_expired_entries = expired_keys.size();
  return counts;
}

std::string GetKeyOfTypeFromTriggerType(
    LoginReputationClientRequest::TriggerType trigger_type,
    ReusedPasswordAccountType password_type) {
  return trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE
             ? kPasswordOnFocusCacheKey
             : base::NumberToString(
                   static_cast<std::underlying_type_t<
                       ReusedPasswordAccountType::AccountType>>(
                       password_type.account_type()));
}

// If the verdict doesn't have |cache_expression_match_type| field, always
// interpret it as exact match only.
template <typename T>
bool IsOnlyExactMatchAllowed(T verdict) {
  NOTREACHED();
}
template <>
bool IsOnlyExactMatchAllowed<RTLookupResponse::ThreatInfo>(
    RTLookupResponse::ThreatInfo verdict) {
  return verdict.cache_expression_match_type() ==
         RTLookupResponse::ThreatInfo::EXACT_MATCH;
}
// Always do fuzzy matching for password protection verdicts.
template <>
bool IsOnlyExactMatchAllowed<LoginReputationClientResponse>(
    LoginReputationClientResponse verdict) {
  return false;
}

template <typename T>
std::string GetCacheExpression(T verdict) {
  NOTREACHED();
}

template <>
std::string GetCacheExpression<RTLookupResponse::ThreatInfo>(
    RTLookupResponse::ThreatInfo verdict) {
  return verdict.cache_expression_using_match_type();
}

template <>
std::string GetCacheExpression<LoginReputationClientResponse>(
    LoginReputationClientResponse verdict) {
  return verdict.cache_expression();
}

template <class T>
std::optional<base::Value> GetMostMatchingCachedVerdictEntryWithPathMatching(
    const GURL& url,
    const std::string& type_key,
    scoped_refptr<HostContentSettingsMap> content_settings,
    const ContentSettingsType contents_setting_type,
    const char* proto_name,
    MatchParams match_params) {
  DCHECK(proto_name == kVerdictProto || proto_name == kRealTimeThreatInfoProto);

  std::optional<base::Value> result;

  GURL hostname = GetHostNameWithHTTPScheme(url);
  base::Value cache_dictionary_value = content_settings->GetWebsiteSetting(
      hostname, GURL(), contents_setting_type, nullptr);

  if (!cache_dictionary_value.is_dict()) {
    return std::nullopt;
  }

  base::Value::Dict* verdict_dictionary =
      cache_dictionary_value.GetDict().FindDict(type_key);

  if (!verdict_dictionary) {
    return std::nullopt;
  }

  std::vector<std::string> paths;
  GeneratePathVariantsWithoutQuery(url, &paths);

  std::string root_path;
  V4ProtocolManagerUtil::CanonicalizeUrl(
      url, /*canonicalized_hostname*/ nullptr, &root_path,
      /*canonicalized_query*/ nullptr);

  int max_path_depth = -1;
  for (const auto [key, value] : *verdict_dictionary) {
    int verdict_received_time;
    T verdict;
    // Ignore any entry that we cannot parse. These invalid entries will be
    // cleaned up during shutdown.
    if (!ParseVerdictEntry<T>(&value, &verdict_received_time, &verdict,
                              proto_name)) {
      continue;
    }
    // Since verdict content settings are keyed by origin, we only need to
    // compare the path part of the cache_expression and the given url.
    std::string cache_expression_path =
        GetCacheExpressionPath(GetCacheExpression(verdict));

    match_params.is_only_exact_match_allowed = IsOnlyExactMatchAllowed(verdict);
    match_params.is_exact_path = (root_path == cache_expression_path);
    // Finds the most specific match.
    int path_depth = static_cast<int>(GetPathDepth(cache_expression_path));
    if (path_depth > max_path_depth &&
        PathVariantsMatchCacheExpression(paths, cache_expression_path) &&
        match_params.ShouldMatch() &&
        !IsCacheExpired(verdict_received_time, verdict.cache_duration_sec())) {
      max_path_depth = path_depth;
      result = std::move(value);
    }
  }

  return result;
}

template <class T>
std::optional<base::Value>
GetMostMatchingCachedVerdictEntryWithHostAndPathMatching(
    const GURL& url,
    const std::string& type_key,
    scoped_refptr<HostContentSettingsMap> content_settings,
    const ContentSettingsType contents_setting_type,
    const char* proto_name) {
  DCHECK(proto_name == kVerdictProto || proto_name == kRealTimeThreatInfoProto);
  std::optional<base::Value> most_matching_verdict;
  MatchParams match_params;

  std::string root_host, root_path;
  V4ProtocolManagerUtil::CanonicalizeUrl(url, &root_host, &root_path,
                                         /*canonicalized_query*/ nullptr);
  std::vector<std::string> host_variants;
  V4ProtocolManagerUtil::GenerateHostVariantsToCheck(root_host, &host_variants);
  int max_path_depth = -1;
  for (const auto& host : host_variants) {
    int depth = static_cast<int>(GetHostDepth(host));
    GURL url_to_check = GetUrlWithHostAndPath(host, root_path);
    match_params.is_exact_host = (root_host == host);
    std::optional<base::Value> verdict =
        GetMostMatchingCachedVerdictEntryWithPathMatching<T>(
            url_to_check, type_key, content_settings, contents_setting_type,
            proto_name, match_params);
    if (depth > max_path_depth && verdict && verdict->is_dict()) {
      max_path_depth = depth;
      most_matching_verdict = std::move(verdict);
    }
  }

  return most_matching_verdict;
}

template <class T>
typename T::VerdictType GetVerdictTypeFromMostMatchedCachedVerdict(
    const char* proto_name,
    std::optional<base::Value> verdict_entry,
    T* out_response) {
  DCHECK(proto_name == kVerdictProto || proto_name == kRealTimeThreatInfoProto);

  if (!verdict_entry || !verdict_entry->is_dict()) {
    return T::VERDICT_TYPE_UNSPECIFIED;
  }

  const std::string* verdict_proto_value =
      verdict_entry->GetDict().FindString(proto_name);
  if (verdict_proto_value) {
    std::string serialized_proto = *verdict_proto_value;

    if (base::Base64Decode(serialized_proto, &serialized_proto) &&
        out_response->ParseFromString(serialized_proto)) {
      return out_response->verdict_type();
    } else {
      return T::VERDICT_TYPE_UNSPECIFIED;
    }
  } else {
    return T::VERDICT_TYPE_UNSPECIFIED;
  }
}

bool HasPageLoadTokenExpired(int64_t token_time_msec) {
  return base::Time::Now() -
             base::Time::FromMillisecondsSinceUnixEpoch(token_time_msec) >
         base::Minutes(kPageLoadTokenExpireMinute);
}

}  // namespace

VerdictCacheManager::VerdictCacheManager(
    history::HistoryService* history_service,
    scoped_refptr<HostContentSettingsMap> content_settings,
    PrefService* pref_service,
    std::unique_ptr<SafeBrowsingSyncObserver> sync_observer)
    : stored_verdict_count_password_on_focus_(std::nullopt),
      stored_verdict_count_password_entry_(std::nullopt),
      has_stored_verdicts_real_time_url_check_(false),
      corrupt_real_time_cache_dictionary_override_(false),
      content_settings_(content_settings),
      sync_observer_(std::move(sync_observer)) {
  if (history_service) {
    history_service_observation_.Observe(history_service);
  }
  if (!content_settings->IsOffTheRecord()) {
    ScheduleNextCleanUpAfterInterval(base::Seconds(kCleanUpIntervalInitSecond));
  }
  // pref_service can be null in tests.
  if (pref_service) {
    pref_change_registrar_.Init(pref_service);
    pref_change_registrar_.Add(
        prefs::kSafeBrowsingEnhanced,
        base::BindRepeating(&VerdictCacheManager::CleanUpAllPageLoadTokens,
                            weak_factory_.GetWeakPtr(),
                            ClearReason::kSafeBrowsingStateChanged));
    pref_change_registrar_.Add(
        prefs::kSafeBrowsingEnabled,
        base::BindRepeating(&VerdictCacheManager::CleanUpAllPageLoadTokens,
                            weak_factory_.GetWeakPtr(),
                            ClearReason::kSafeBrowsingStateChanged));
  }
  // sync_observer_ can be null in some embedders that don't support sync.
  if (sync_observer_) {
    sync_observer_->ObserveHistorySyncStateChanged(base::BindRepeating(
        &VerdictCacheManager::CleanUpAllPageLoadTokens,
        weak_factory_.GetWeakPtr(), ClearReason::kSyncStateChanged));
  }
  CacheArtificialUnsafeRealTimeUrlVerdictFromSwitch();
  CacheArtificialUnsafePhishGuardVerdictFromSwitch();
  CacheArtificialUnsafeHashRealTimeLookupVerdictFromSwitch();
  CacheArtificialEnterpriseBlockedVerdictFromSwitch();
  CacheArtificialEnterpriseWarnedVerdictFromSwitch();
}

void VerdictCacheManager::Shutdown() {
  CleanUpExpiredVerdicts();
  history_service_observation_.Reset();
  pref_change_registrar_.RemoveAll();
  sync_observer_.reset();

  // Clear references to other KeyedServices.
  content_settings_ = nullptr;

  is_shut_down_ = true;
  weak_factory_.InvalidateWeakPtrs();
}

VerdictCacheManager::~VerdictCacheManager() = default;

void VerdictCacheManager::CachePhishGuardVerdict(
    LoginReputationClientRequest::TriggerType trigger_type,
    ReusedPasswordAccountType password_type,
    const LoginReputationClientResponse& verdict,
    const base::Time& receive_time) {
  if (is_shut_down_) {
    return;
  }
  DCHECK(content_settings_);
  DCHECK(trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE ||
         trigger_type == LoginReputationClientRequest::PASSWORD_REUSE_EVENT);

  GURL hostname = GetHostNameFromCacheExpression(GetCacheExpression(verdict));

  base::Value cache_dictionary_value = content_settings_->GetWebsiteSetting(
      hostname, GURL(), ContentSettingsType::PASSWORD_PROTECTION, nullptr);

  base::Value::Dict cache_dictionary =
      cache_dictionary_value.is_dict()
          ? std::move(cache_dictionary_value.GetDict())
          : base::Value::Dict();

  base::Value::Dict verdict_entry(
      CreateDictionaryFromVerdict<LoginReputationClientResponse>(
          verdict, receive_time, kVerdictProto));

  std::string type_key =
      GetKeyOfTypeFromTriggerType(trigger_type, password_type);
  base::Value::Dict* verdict_dictionary = cache_dictionary.FindDict(type_key);
  if (!verdict_dictionary) {
    verdict_dictionary =
        cache_dictionary.Set(type_key, base::Value::Dict())->GetIfDict();
  }

  // Increases stored verdict count if we haven't seen this cache expression
  // before.
  if (!verdict_dictionary->contains(GetCacheExpression(verdict))) {
    std::optional<size_t>* stored_verdict_count =
        trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE
            ? &stored_verdict_count_password_on_focus_
            : &stored_verdict_count_password_entry_;
    *stored_verdict_count = GetStoredPhishGuardVerdictCount(trigger_type) + 1;
  }

  // If same cache_expression is already in this verdict_dictionary, we simply
  // override it.
  verdict_dictionary->Set(GetCacheExpression(verdict),
                          std::move(verdict_entry));
  content_settings_->SetWebsiteSettingDefaultScope(
      hostname, GURL(), ContentSettingsType::PASSWORD_PROTECTION,
      base::Value(std::move(cache_dictionary)));
}

LoginReputationClientResponse::VerdictType
VerdictCacheManager::GetCachedPhishGuardVerdict(
    const GURL& url,
    LoginReputationClientRequest::TriggerType trigger_type,
    ReusedPasswordAccountType password_type,
    LoginReputationClientResponse* out_response) {
  DCHECK(trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE ||
         trigger_type == LoginReputationClientRequest::PASSWORD_REUSE_EVENT);
  if (is_shut_down_) {
    return LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED;
  }

  std::string type_key =
      GetKeyOfTypeFromTriggerType(trigger_type, password_type);
  std::optional<base::Value> most_matching_verdict =
      GetMostMatchingCachedVerdictEntryWithHostAndPathMatching<
          LoginReputationClientResponse>(
          url, type_key, content_settings_,
          ContentSettingsType::PASSWORD_PROTECTION, kVerdictProto);

  return GetVerdictTypeFromMostMatchedCachedVerdict<
      LoginReputationClientResponse>(
      kVerdictProto, std::move(most_matching_verdict), out_response);
}

size_t VerdictCacheManager::GetStoredPhishGuardVerdictCount(
    LoginReputationClientRequest::TriggerType trigger_type) {
  if (is_shut_down_) {
    return 0;
  }
  DCHECK(content_settings_);
  DCHECK(trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE ||
         trigger_type == LoginReputationClientRequest::PASSWORD_REUSE_EVENT);
  std::optional<size_t>* stored_verdict_count =
      trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE
          ? &stored_verdict_count_password_on_focus_
          : &stored_verdict_count_password_entry_;
  // If we have already computed this, return its value.
  if (stored_verdict_count->has_value()) {
    return stored_verdict_count->value();
  }

  stored_verdict_count_password_on_focus_ = 0;
  stored_verdict_count_password_entry_ = 0;
  for (const ContentSettingPatternSource& source :
       content_settings_->GetSettingsForOneType(
           ContentSettingsType::PASSWORD_PROTECTION)) {
    for (auto item : source.setting_value.GetDict()) {
      if (item.first == std::string_view(kPasswordOnFocusCacheKey)) {
        stored_verdict_count_password_on_focus_.value() +=
            item.second.GetDict().size();
      } else {
        stored_verdict_count_password_entry_.value() +=
            item.second.GetDict().size();
      }
    }
  }
  return stored_verdict_count->value();
}

void VerdictCacheManager::CacheRealTimeUrlVerdict(
    const RTLookupResponse& verdict,
    const base::Time& receive_time) {
  if (is_shut_down_) {
    return;
  }
  std::vector<std::string> visited_cache_expressions;
  safe_browsing::ClientSideDetectionType csd_type =
      verdict.client_side_detection_type();
  safe_browsing::LlamaForcedTriggerInfo llama_forced_trigger_info =
      verdict.llama_forced_trigger_info();

  for (const auto& threat_info : verdict.threat_info()) {
    // If |cache_expression_match_type| is unspecified, ignore this entry.
    if (threat_info.cache_expression_match_type() ==
        RTLookupResponse::ThreatInfo::MATCH_TYPE_UNSPECIFIED) {
      continue;
    }
    std::string cache_expression = GetCacheExpression(threat_info);
    // For the same cache_expression, threat_info is in decreasing order of
    // severity. To avoid lower severity threat being overridden by higher one,
    // only store threat info that is first seen for a cache expression.
    if (base::Contains(visited_cache_expressions, cache_expression)) {
      continue;
    }

    GURL hostname = GetHostNameFromCacheExpression(cache_expression);
    base::Value cache_dictionary_value = content_settings_->GetWebsiteSetting(
        hostname, GURL(), ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA,
        nullptr);

    base::Value::Dict cache_dictionary =
        cache_dictionary_value.is_dict()
            ? std::move(cache_dictionary_value.GetDict())
            : base::Value::Dict();

    base::Value::Dict* verdict_dictionary =
        cache_dictionary.FindDict(kRealTimeUrlCacheKey);
    if (!verdict_dictionary) {
      verdict_dictionary =
          cache_dictionary.Set(kRealTimeUrlCacheKey, base::Value::Dict())
              ->GetIfDict();
    }

    base::Value::Dict threat_info_entry =
        CreateDictionaryFromVerdict<RTLookupResponse::ThreatInfo>(
            threat_info, receive_time, kRealTimeThreatInfoProto, csd_type,
            llama_forced_trigger_info);
    has_stored_verdicts_real_time_url_check_ = true;

    verdict_dictionary->Set(cache_expression, std::move(threat_info_entry));
    visited_cache_expressions.push_back(cache_expression);

    content_settings_->SetWebsiteSettingDefaultScope(
        hostname, GURL(), ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA,
        base::Value(std::move(cache_dictionary)));
  }
}

RTLookupResponse::ThreatInfo::VerdictType
VerdictCacheManager::GetCachedRealTimeUrlVerdict(
    const GURL& url,
    RTLookupResponse::ThreatInfo* out_threat_info) {
  if (is_shut_down_) {
    return RTLookupResponse::ThreatInfo::VERDICT_TYPE_UNSPECIFIED;
  }

  std::optional<base::Value> most_matching_verdict =
      GetMostMatchingCachedVerdictEntryWithHostAndPathMatching<
          RTLookupResponse::ThreatInfo>(
          url, kRealTimeUrlCacheKey, content_settings_,
          ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA,
          kRealTimeThreatInfoProto);

  return GetVerdictTypeFromMostMatchedCachedVerdict<
      RTLookupResponse::ThreatInfo>(kRealTimeThreatInfoProto,
                                    std::move(most_matching_verdict),
                                    out_threat_info);
}

safe_browsing::ClientSideDetectionType
VerdictCacheManager::GetCachedRealTimeUrlClientSideDetectionType(
    const GURL& url) {
  if (is_shut_down_) {
    return safe_browsing::ClientSideDetectionType::
        CLIENT_SIDE_DETECTION_TYPE_UNSPECIFIED;
  }
  std::optional<base::Value> most_matching_verdict =
      GetMostMatchingCachedVerdictEntryWithHostAndPathMatching<
          RTLookupResponse::ThreatInfo>(
          url, kRealTimeUrlCacheKey, content_settings_,
          ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA,
          kRealTimeThreatInfoProto);

  if (!most_matching_verdict || !most_matching_verdict->is_dict()) {
    return safe_browsing::ClientSideDetectionType::
        CLIENT_SIDE_DETECTION_TYPE_UNSPECIFIED;
  }

  const std::optional<int> cache_client_side_detection_type =
      most_matching_verdict->GetDict().FindInt(kCsdTypeCacheKey);
  if (cache_client_side_detection_type) {
    return static_cast<safe_browsing::ClientSideDetectionType>(
        cache_client_side_detection_type.value());
  } else {
    return safe_browsing::ClientSideDetectionType::
        CLIENT_SIDE_DETECTION_TYPE_UNSPECIFIED;
  }
}

bool VerdictCacheManager::GetCachedRealTimeLlamaForcedTriggerInfo(
    const GURL& url,
    safe_browsing::LlamaForcedTriggerInfo* out_llama_forced_trigger_info) {
  if (is_shut_down_) {
    return false;
  }

  std::optional<base::Value> most_matching_verdict =
      GetMostMatchingCachedVerdictEntryWithHostAndPathMatching<
          RTLookupResponse::ThreatInfo>(
          url, kRealTimeUrlCacheKey, content_settings_,
          ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA,
          kRealTimeThreatInfoProto);

  if (!most_matching_verdict || !most_matching_verdict->is_dict()) {
    return false;
  }

  const std::string* cache_llama_forced_trigger_info =
      most_matching_verdict->GetDict().FindString(kLlamaForcedTriggerInfoKey);

  if (cache_llama_forced_trigger_info) {
    std::string serialized_llama_forced_trigger_info =
        *cache_llama_forced_trigger_info;

    if (base::Base64Decode(serialized_llama_forced_trigger_info,
                           &serialized_llama_forced_trigger_info)) {
      return out_llama_forced_trigger_info->ParseFromString(
          serialized_llama_forced_trigger_info);
    }
  }

  return false;
}

ChromeUserPopulation::PageLoadToken VerdictCacheManager::CreatePageLoadToken(
    const GURL& url) {
  std::string hostname = url.host();
  ChromeUserPopulation::PageLoadToken token;
  token.set_token_source(
      ChromeUserPopulation::PageLoadToken::CLIENT_GENERATION);
  token.set_token_time_msec(base::Time::Now().InMillisecondsSinceUnixEpoch());
  token.set_token_value(base::RandBytesAsString(kPageLoadTokenBytes));

  page_load_token_map_[hostname] = token;

  return token;
}

ChromeUserPopulation::PageLoadToken VerdictCacheManager::GetPageLoadToken(
    const GURL& url) {
  std::string hostname = url.host();
  if (!base::Contains(page_load_token_map_, hostname)) {
    return ChromeUserPopulation::PageLoadToken();
  }

  ChromeUserPopulation::PageLoadToken token = page_load_token_map_[hostname];
  bool has_expired = HasPageLoadTokenExpired(token.token_time_msec());
  base::UmaHistogramLongTimes(
      "SafeBrowsing.PageLoadToken.Duration",
      base::Time::Now() -
          base::Time::FromMillisecondsSinceUnixEpoch(token.token_time_msec()));
  base::UmaHistogramBoolean("SafeBrowsing.PageLoadToken.HasExpired",
                            has_expired);
  return has_expired ? ChromeUserPopulation::PageLoadToken() : token;
}

void VerdictCacheManager::CacheHashPrefixRealTimeLookupResults(
    const std::vector<std::string>& requested_hash_prefixes,
    const std::vector<V5::FullHash>& response_full_hashes,
    const V5::Duration& cache_duration) {
  hash_realtime_cache_->CacheSearchHashesResponse(
      requested_hash_prefixes, response_full_hashes, cache_duration);
}

std::unordered_map<std::string, std::vector<V5::FullHash>>
VerdictCacheManager::GetCachedHashPrefixRealTimeLookupResults(
    const std::set<std::string>& hash_prefixes) {
  return hash_realtime_cache_->SearchCache(hash_prefixes);
}

void VerdictCacheManager::ScheduleNextCleanUpAfterInterval(
    base::TimeDelta interval) {
  cleanup_timer_.Stop();
  cleanup_timer_.Start(FROM_HERE, interval, this,
                       &VerdictCacheManager::CleanUpExpiredVerdicts);
}

void VerdictCacheManager::CleanUpExpiredVerdicts() {
  if (is_shut_down_) {
    return;
  }
  DCHECK(content_settings_);
  SCOPED_UMA_HISTOGRAM_TIMER("SafeBrowsing.RT.CacheManager.CleanUpTime");
  CleanUpExpiredPhishGuardVerdicts();
  CleanUpExpiredRealTimeUrlCheckVerdicts();
  CleanUpExpiredPageLoadTokens();
  CleanUpExpiredHashPrefixRealTimeLookupResults();
  ScheduleNextCleanUpAfterInterval(base::Seconds(kCleanUpIntervalSecond));
}

void VerdictCacheManager::CleanUpExpiredPhishGuardVerdicts() {
  if (GetStoredPhishGuardVerdictCount(
          LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE) <= 0 &&
      GetStoredPhishGuardVerdictCount(
          LoginReputationClientRequest::PASSWORD_REUSE_EVENT) <= 0) {
    return;
  }

  int removed_count = 0;
  for (ContentSettingPatternSource& source :
       content_settings_->GetSettingsForOneType(
           ContentSettingsType::PASSWORD_PROTECTION)) {
    // Find all verdicts associated with this origin.
    base::Value::Dict cache_dictionary =
        std::move(source.setting_value.GetDict());

    bool has_expired_password_on_focus_entry = RemoveExpiredPhishGuardVerdicts(
        LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE, cache_dictionary);
    bool has_expired_password_reuse_entry = RemoveExpiredPhishGuardVerdicts(
        LoginReputationClientRequest::PASSWORD_REUSE_EVENT, cache_dictionary);

    if (!cache_dictionary.empty() && !has_expired_password_on_focus_entry &&
        !has_expired_password_reuse_entry) {
      continue;
    }

    // Set the website setting of this origin with the updated
    // |cache_dictionary|.
    content_settings_->SetWebsiteSettingCustomScope(
        source.primary_pattern, source.secondary_pattern,
        ContentSettingsType::PASSWORD_PROTECTION,
        cache_dictionary.empty() ? base::Value()
                                 : base::Value(std::move(cache_dictionary)));

    if ((++removed_count) == GetMaxRemovedEntriesCount()) {
      return;
    }
  }
}

int VerdictCacheManager::GetMaxRemovedEntriesCount() {
  if (max_removed_entries_count_override_.has_value()) {
    return max_removed_entries_count_override_.value();
  }
  return kMaxRemovedEntriesCount;
}

void VerdictCacheManager::CleanUpExpiredRealTimeUrlCheckVerdicts() {
  DictionaryCounts overall_counts;
  int removed_count = 0;
  if (has_stored_verdicts_real_time_url_check_) {
    for (ContentSettingPatternSource& source :
         content_settings_->GetSettingsForOneType(
             ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA)) {
      bool is_removing_allowed = removed_count < GetMaxRemovedEntriesCount();
      // Find all verdicts associated with this origin.
      base::Value::Dict cache_dictionary;
      if (source.setting_value.is_dict() &&
          !corrupt_real_time_cache_dictionary_override_) {
        cache_dictionary = std::move(source.setting_value.GetDict());
        DictionaryCounts counts =
            ComputeCountsAndMaybeRemoveExpiredRealTimeUrlCheckVerdicts(
                cache_dictionary,
                /*remove_expired_verdicts=*/is_removing_allowed);
        overall_counts.num_entries += counts.num_entries;
        overall_counts.num_removed_expired_entries +=
            counts.num_removed_expired_entries;

        if (!cache_dictionary.empty() &&
            counts.num_removed_expired_entries == 0U) {
          continue;
        }
      }

      // Don't continue removing entries if we're past the threshold, but
      // continue counting the entries for the histogram log when the loop
      // completes.
      if (!is_removing_allowed) {
        continue;
      }
      ++removed_count;

      // Set the website setting of this origin with the updated
      // |cache_dictionary|.
      content_settings_->SetWebsiteSettingCustomScope(
          source.primary_pattern, source.secondary_pattern,
          ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA,
          cache_dictionary.empty() ? base::Value()
                                   : base::Value(std::move(cache_dictionary)));
    }
  }
  has_stored_verdicts_real_time_url_check_ =
      overall_counts.num_entries > overall_counts.num_removed_expired_entries;
  base::UmaHistogramCounts10000(
      "SafeBrowsing.RT.CacheManager.RealTimeVerdictCount2",
      overall_counts.num_entries);
  base::UmaHistogramBoolean(
      "SafeBrowsing.RT.CacheManager.CleanupReachedThreshold",
      removed_count >= GetMaxRemovedEntriesCount());
}

void VerdictCacheManager::CleanUpExpiredPageLoadTokens() {
  base::EraseIf(page_load_token_map_, [&](const auto& hostname_token_pair) {
    ChromeUserPopulation::PageLoadToken token = hostname_token_pair.second;
    return HasPageLoadTokenExpired(token.token_time_msec());
  });
  base::UmaHistogramCounts10000("SafeBrowsing.PageLoadToken.TokenCount",
                                page_load_token_map_.size());
}

void VerdictCacheManager::CleanUpAllPageLoadTokens(ClearReason reason) {
  base::UmaHistogramEnumeration("SafeBrowsing.PageLoadToken.ClearReason",
                                reason);
  page_load_token_map_.clear();
}

void VerdictCacheManager::CleanUpExpiredHashPrefixRealTimeLookupResults() {
  hash_realtime_cache_->ClearExpiredResults();
}

// Overridden from history::HistoryServiceObserver.
void VerdictCacheManager::OnHistoryDeletions(
    history::HistoryService* history_service,
    const history::DeletionInfo& deletion_info) {
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindRepeating(
                     &VerdictCacheManager::RemoveContentSettingsOnURLsDeleted,
                     GetWeakPtr(), deletion_info.IsAllHistory(),
                     deletion_info.deleted_rows()));
}

// Overridden from history::HistoryServiceObserver.
void VerdictCacheManager::HistoryServiceBeingDeleted(
    history::HistoryService* history_service) {
  DCHECK(history_service_observation_.IsObservingSource(history_service));
  history_service_observation_.Reset();
}

void VerdictCacheManager::OnCookiesDeleted() {
  CleanUpAllPageLoadTokens(ClearReason::kCookiesDeleted);
}

bool VerdictCacheManager::RemoveExpiredPhishGuardVerdicts(
    LoginReputationClientRequest::TriggerType trigger_type,
    base::Value::Dict& cache_dictionary) {
  DCHECK(trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE ||
         trigger_type == LoginReputationClientRequest::PASSWORD_REUSE_EVENT);
  if (cache_dictionary.empty()) {
    return false;
  }

  size_t verdicts_removed = 0;
  std::vector<std::string> empty_keys;
  for (auto [key, value] : cache_dictionary) {
    if (trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE &&
        key == std::string(kPasswordOnFocusCacheKey)) {
      DictionaryCounts counts = ComputeCountsAndMaybeRemoveExpiredEntries<
          LoginReputationClientResponse>(value.GetDict(), kVerdictProto,
                                         /*remove_entries=*/true);
      verdicts_removed += counts.num_removed_expired_entries;
      if (stored_verdict_count_password_on_focus_.has_value()) {
        stored_verdict_count_password_on_focus_.value() -=
            counts.num_removed_expired_entries;
      }
    } else {
      DictionaryCounts counts = ComputeCountsAndMaybeRemoveExpiredEntries<
          LoginReputationClientResponse>(value.GetDict(), kVerdictProto,
                                         /*remove_entries=*/true);
      verdicts_removed += counts.num_removed_expired_entries;
      if (stored_verdict_count_password_entry_.has_value()) {
        stored_verdict_count_password_entry_.value() -=
            counts.num_removed_expired_entries;
      }
    }

    if (value.GetDict().size() == 0U) {
      empty_keys.push_back(key);
    }
  }
  for (const auto& key : empty_keys) {
    cache_dictionary.Remove(key);
  }

  return verdicts_removed > 0U;
}

VerdictCacheManager::DictionaryCounts
VerdictCacheManager::ComputeCountsAndMaybeRemoveExpiredRealTimeUrlCheckVerdicts(
    base::Value::Dict& cache_dictionary,
    bool remove_expired_verdicts) {
  std::vector<std::string> empty_keys;
  DictionaryCounts overall_counts;
  for (auto [key, value] : cache_dictionary) {
    bool is_key_unneeded = true;
    if (value.is_dict()) {
      DictionaryCounts counts = ComputeCountsAndMaybeRemoveExpiredEntries<
          RTLookupResponse::ThreatInfo>(
          value.GetDict(), kRealTimeThreatInfoProto,
          /*remove_entries=*/remove_expired_verdicts);
      overall_counts.num_removed_expired_entries +=
          counts.num_removed_expired_entries;
      overall_counts.num_entries += counts.num_entries;
      is_key_unneeded = value.GetDict().size() == 0U;
    }
    if (remove_expired_verdicts && is_key_unneeded) {
      empty_keys.push_back(key);
    }
  }
  for (const auto& key : empty_keys) {
    cache_dictionary.Remove(key);
  }

  return overall_counts;
}

void VerdictCacheManager::RemoveContentSettingsOnURLsDeleted(
    bool all_history,
    const history::URLRows& deleted_rows) {
  if (is_shut_down_) {
    return;
  }
  DCHECK(content_settings_);

  if (all_history) {
    content_settings_->ClearSettingsForOneType(
        ContentSettingsType::PASSWORD_PROTECTION);
    stored_verdict_count_password_on_focus_ = 0;
    stored_verdict_count_password_entry_ = 0;
    has_stored_verdicts_real_time_url_check_ = false;
    content_settings_->ClearSettingsForOneType(
        ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA);
    return;
  }

  // For now, if a URL is deleted from history, we simply remove all the
  // cached verdicts of the same origin. This is a pretty aggressive deletion.
  // We might revisit this logic later to decide if we want to only delete the
  // cached verdict whose cache expression matches this URL.
  for (const history::URLRow& row : deleted_rows) {
    if (!row.url().SchemeIsHTTPOrHTTPS()) {
      continue;
    }

    GURL url_key = GetHostNameWithHTTPScheme(row.url());
    stored_verdict_count_password_on_focus_ =
        GetStoredPhishGuardVerdictCount(
            LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE) -
        GetPhishGuardVerdictCountForURL(
            url_key, LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE);
    stored_verdict_count_password_entry_ =
        GetStoredPhishGuardVerdictCount(
            LoginReputationClientRequest::PASSWORD_REUSE_EVENT) -
        GetPhishGuardVerdictCountForURL(
            url_key, LoginReputationClientRequest::PASSWORD_REUSE_EVENT);
    content_settings_->SetWebsiteSettingDefaultScope(
        url_key, GURL(), ContentSettingsType::PASSWORD_PROTECTION,
        base::Value());
    content_settings_->SetWebsiteSettingDefaultScope(
        url_key, GURL(), ContentSettingsType::SAFE_BROWSING_URL_CHECK_DATA,
        base::Value());
  }
}

size_t VerdictCacheManager::GetPhishGuardVerdictCountForURL(
    const GURL& url,
    LoginReputationClientRequest::TriggerType trigger_type) {
  DCHECK(trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE ||
         trigger_type == LoginReputationClientRequest::PASSWORD_REUSE_EVENT);
  base::Value cache_dictionary_value = content_settings_->GetWebsiteSetting(
      url, GURL(), ContentSettingsType::PASSWORD_PROTECTION, nullptr);

  if (!cache_dictionary_value.is_dict()) {
    return 0;
  }

  int verdict_cnt = 0;
  if (trigger_type == LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE) {
    base::Value::Dict* password_on_focus_dict =
        cache_dictionary_value.GetDict().FindDict(kPasswordOnFocusCacheKey);
    verdict_cnt += password_on_focus_dict ? password_on_focus_dict->size() : 0;
  } else {
    for (auto [key, value] : cache_dictionary_value.GetDict()) {
      if (key == kPasswordOnFocusCacheKey) {
        continue;
      }
      verdict_cnt += value.GetDict().size();
    }
  }
  return verdict_cnt;
}

void VerdictCacheManager::CacheArtificialUnsafeRealTimeUrlVerdictFromSwitch() {
  std::string phishing_url_string =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kArtificialCachedUrlRealTimeVerdictFlag);
  CacheArtificialRealTimeUrlVerdict(
      phishing_url_string, RTLookupResponse::ThreatInfo::DANGEROUS,
      RTLookupResponse::ThreatInfo::SOCIAL_ENGINEERING);
}

void VerdictCacheManager::CacheArtificialRealTimeUrlVerdict(
    const std::string& url_string,
    RTLookupResponse::ThreatInfo::VerdictType verdict_type,
    std::optional<RTLookupResponse::ThreatInfo::ThreatType> threat_type) {
  if (url_string.empty()) {
    return;
  }

  GURL artificial_url(url_string);
  if (!artificial_url.is_valid()) {
    return;
  }

  has_artificial_cached_url_ = true;

  RTLookupResponse response;
  RTLookupResponse::ThreatInfo* threat_info = response.add_threat_info();
  threat_info->set_verdict_type(verdict_type);
  if (threat_type.has_value()) {
    threat_info->set_threat_type(threat_type.value());
  }
  threat_info->set_cache_duration_sec(3000);
  threat_info->set_cache_expression_using_match_type(
      artificial_url.GetContent());
  threat_info->set_cache_expression_match_type(
      RTLookupResponse::ThreatInfo::EXACT_MATCH);
  RemoveContentSettingsOnURLsDeleted(/*all_history=*/false,
                                     {history::URLRow(artificial_url)});
  CacheRealTimeUrlVerdict(response, base::Time::Now());
}

void VerdictCacheManager::CacheArtificialUnsafePhishGuardVerdictFromSwitch() {
  std::string phishing_url_string =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kArtificialCachedPhishGuardVerdictFlag);
  if (phishing_url_string.empty()) {
    return;
  }

  GURL artificial_unsafe_url(phishing_url_string);
  if (!artificial_unsafe_url.is_valid()) {
    return;
  }

  has_artificial_cached_url_ = true;

  ReusedPasswordAccountType reused_password_account_type;
  reused_password_account_type.set_account_type(
      ReusedPasswordAccountType::SAVED_PASSWORD);

  LoginReputationClientResponse verdict;
  verdict.set_verdict_type(LoginReputationClientResponse::PHISHING);
  verdict.set_cache_expression(artificial_unsafe_url.GetContent());
  verdict.set_cache_duration_sec(3000);
  CachePhishGuardVerdict(LoginReputationClientRequest::PASSWORD_REUSE_EVENT,
                         reused_password_account_type, verdict,
                         base::Time::Now());
}

void VerdictCacheManager::CacheArtificialHashRealTimeLookupVerdict(
    const std::string& url_spec,
    bool is_unsafe) {
  if (url_spec.empty()) {
    return;
  }

  GURL artificial_unsafe_url(url_spec);
  if (!artificial_unsafe_url.is_valid()) {
    return;
  }

  has_artificial_cached_url_ = true;

  std::vector<FullHashStr> full_hashes;
  V4ProtocolManagerUtil::UrlToFullHashes(artificial_unsafe_url, &full_hashes);
  std::vector<std::string> hash_prefixes;
  for (const auto& full_hash : full_hashes) {
    auto hash_prefix = hash_realtime_utils::GetHashPrefix(full_hash);
    hash_prefixes.emplace_back(hash_prefix);
  }
  FullHashStr sample_full_hash = full_hashes[0];
  V5::FullHash full_hash_object;
  full_hash_object.set_full_hash(sample_full_hash);
  if (is_unsafe) {
    auto* details = full_hash_object.add_full_hash_details();
    details->set_threat_type(V5::ThreatType::SOCIAL_ENGINEERING);
  }
  V5::Duration cache_duration;
  cache_duration.set_seconds(3000);
  CacheHashPrefixRealTimeLookupResults(hash_prefixes, {full_hash_object},
                                       cache_duration);
}

void VerdictCacheManager::
    CacheArtificialUnsafeHashRealTimeLookupVerdictFromSwitch() {
  std::string phishing_url_string =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kArtificialCachedHashPrefixRealTimeVerdictFlag);
  CacheArtificialHashRealTimeLookupVerdict(phishing_url_string,
                                           /*is_unsafe=*/true);
}

void VerdictCacheManager::CacheArtificialEnterpriseBlockedVerdictFromSwitch() {
  std::string blocked_url_string =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kArtificialCachedEnterpriseBlockedVerdictFlag);
  CacheArtificialRealTimeUrlVerdict(
      blocked_url_string, RTLookupResponse::ThreatInfo::DANGEROUS,
      RTLookupResponse::ThreatInfo::MANAGED_POLICY);
}

void VerdictCacheManager::CacheArtificialEnterpriseWarnedVerdictFromSwitch() {
  std::string flagged_url_string =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kArtificialCachedEnterpriseWarnedVerdictFlag);
  CacheArtificialRealTimeUrlVerdict(
      flagged_url_string, RTLookupResponse::ThreatInfo::WARN,
      RTLookupResponse::ThreatInfo::MANAGED_POLICY);
}

void VerdictCacheManager::StopCleanUpTimerForTesting() {
  if (cleanup_timer_.IsRunning()) {
    cleanup_timer_.Stop();
  }
}

void VerdictCacheManager::SetPageLoadTokenForTesting(
    const GURL& url,
    ChromeUserPopulation::PageLoadToken token) {
  std::string hostname = url.host();
  page_load_token_map_[hostname] = token;
}

// static
bool VerdictCacheManager::has_artificial_cached_url_ = false;
bool VerdictCacheManager::has_artificial_cached_url() {
  return has_artificial_cached_url_;
}
void VerdictCacheManager::ResetHasArtificialCachedUrlForTesting() {
  has_artificial_cached_url_ = false;
}

}  // namespace safe_browsing