File: content_settings_pref.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (656 lines) | stat: -rw-r--r-- 25,686 bytes parent folder | download | duplicates (4)
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
// Copyright 2015 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/content_settings/core/browser/content_settings_pref.h"

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "base/auto_reset.h"
#include "base/functional/bind.h"
#include "base/json/values_util.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/time/clock.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/content_settings/core/browser/content_settings_info.h"
#include "components/content_settings/core/browser/content_settings_registry.h"
#include "components/content_settings/core/browser/content_settings_rule.h"
#include "components/content_settings/core/browser/content_settings_utils.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_constraints.h"
#include "components/content_settings/core/common/content_settings_partition_key.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/content_settings/core/common/features.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "services/preferences/public/cpp/dictionary_value_update.h"
#include "services/preferences/public/cpp/scoped_pref_update.h"
#include "url/gurl.h"

namespace {

const char kExpirationKey[] = "expiration";
const char kLastUsedKey[] = "last_used";
const char kLastVisitKey[] = "last_visit";
const char kSessionModelKey[] = "model";
const char kSettingKey[] = "setting";
const char kLastModifiedKey[] = "last_modified";
const char kLifetimeKey[] = "lifetime";
const char kDecidedByRelatedWebsiteSets[] = "decided_by_related_website_sets";

const base::TimeDelta kLastUsedPermissionExpiration = base::Hours(24);

bool IsValueAllowedForType(const base::Value& value, ContentSettingsType type) {
  const content_settings::ContentSettingsInfo* info =
      content_settings::ContentSettingsRegistry::GetInstance()->Get(type);
  if (info) {
    if (!value.is_int())
      return false;
    if (value.GetInt() == CONTENT_SETTING_DEFAULT)
      return false;
    return info->IsSettingValid(IntToContentSetting(value.GetInt()));
  }

  // TODO(raymes): We should permit different types of base::Value for
  // website settings.
  return value.is_dict();
}

// Extract a timestamp from `dict[key]`.
// Will return base::Time() if no timestamp exists.
base::Time GetTimeFromDictKey(const base::Value::Dict& dict,
                              const std::string& key) {
  return base::ValueToTime(dict.Find(key)).value_or(base::Time());
}

// Extract a timestamp from `dict[key]`.
// Will return base::Time() if no timestamp exists.
base::TimeDelta GetTimeDeltaFromDictKey(const base::Value::Dict& dict,
                                        const std::string& key) {
  return base::ValueToTimeDelta(dict.Find(key)).value_or(base::TimeDelta());
}

// Extract a timestamp from `dictionary[kLastModifiedKey]`.
// Will return base::Time() if no timestamp exists.
base::Time GetLastModified(const base::Value::Dict& dictionary) {
  return GetTimeFromDictKey(dictionary, kLastModifiedKey);
}

// Extract a timestamp from `dictionary[kExpirationKey]`.
// Will return base::Time() if no timestamp exists.
base::Time GetExpiration(const base::Value::Dict& dictionary) {
  return GetTimeFromDictKey(dictionary, kExpirationKey);
}

// Extract a timestamp from `dictionary[kLastUsedKey]`.
// Will return base::Time() if no timestamp exists.
base::Time GetLastUsed(const base::Value::Dict& dictionary) {
  return GetTimeFromDictKey(dictionary, kLastUsedKey);
}

// Extract a timestamp from `dictionary[kLastVisit]`.
// Will return base::Time() if no timestamp exists.
base::Time GetLastVisit(const base::Value::Dict& dictionary) {
  return GetTimeFromDictKey(dictionary, kLastVisitKey);
}

// Extract a TimeDelta from `dictionary[kLifetimeKey]`.
// Will return base::TimeDelta() if no value exists for that key.
base::TimeDelta GetLifetime(const base::Value::Dict& dictionary) {
  return GetTimeDeltaFromDictKey(dictionary, kLifetimeKey);
}

// Extract a bool from `dictionary[kDecidedByRelatedWebsiteSets]`.
// Will return false if no value exists for that key.
bool GetDecidedByRelatedWebsiteSets(const base::Value::Dict& dictionary) {
  return dictionary.FindBool(kDecidedByRelatedWebsiteSets).value_or(false);
}

// Extract a SessionModel from |dictionary[kSessionModelKey]|. Will return
// SessionModel::DURABLE if no model exists.
content_settings::mojom::SessionModel GetSessionModel(
    const base::Value::Dict& dictionary) {
  int model_int = dictionary.FindInt(kSessionModelKey).value_or(0);
  if ((model_int >
       static_cast<int>(content_settings::mojom::SessionModel::kMaxValue)) ||
      (model_int < 0)) {
    model_int = 0;
  }

  content_settings::mojom::SessionModel session_model =
      static_cast<content_settings::mojom::SessionModel>(model_int);
  return session_model;
}

}  // namespace

namespace content_settings {

ContentSettingsPref::ContentSettingsPref(
    ContentSettingsType content_type,
    PrefService* prefs,
    PrefChangeRegistrar* registrar,
    const std::string& pref_name,
    const std::string& partitioned_pref_name,
    bool off_the_record,
    bool restore_session,
    NotifyObserversCallback notify_callback)
    : content_type_(content_type),
      prefs_(prefs),
      registrar_(registrar),
      pref_name_(pref_name),
      partitioned_pref_name_(partitioned_pref_name),
      off_the_record_(off_the_record),
      restore_session_(restore_session),
      updating_preferences_(false),
      notify_callback_(notify_callback),
      clock_(base::DefaultClock::GetInstance()) {
  DCHECK(prefs_);
  ReadContentSettingsFromPref();

  for (const auto& path : {pref_name_, partitioned_pref_name_}) {
    registrar_->Add(path,
                    base::BindRepeating(&ContentSettingsPref::OnPrefChanged,
                                        base::Unretained(this)));
  }
}

ContentSettingsPref::~ContentSettingsPref() = default;

std::unique_ptr<RuleIterator> ContentSettingsPref::GetRuleIterator(
    bool off_the_record,
    const PartitionKey& partition_key) const {
  if (off_the_record)
    return off_the_record_value_map_.GetRuleIterator(content_type_,
                                                     partition_key);
  return value_map_.GetRuleIterator(content_type_, partition_key);
}

std::unique_ptr<Rule> ContentSettingsPref::GetRule(
    const GURL& primary_url,
    const GURL& secondary_url,
    bool off_the_record,
    const PartitionKey& partition_key) const {
  if (off_the_record) {
    base::AutoLock auto_lock(off_the_record_value_map_.GetLock());
    return off_the_record_value_map_.GetRule(primary_url, secondary_url,
                                             content_type_, partition_key);
  }
  base::AutoLock auto_lock(value_map_.GetLock());
  return value_map_.GetRule(primary_url, secondary_url, content_type_,
                            partition_key);
}

void ContentSettingsPref::SetWebsiteSetting(
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern,
    base::Value value,
    RuleMetaData metadata,
    const PartitionKey& partition_key) {
  DCHECK(value.is_none() || IsValueAllowedForType(value, content_type_));
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(prefs_);
  DCHECK(primary_pattern != ContentSettingsPattern::Wildcard() ||
         secondary_pattern != ContentSettingsPattern::Wildcard());

  // Update in memory value map.
  auto* map_to_modify = &off_the_record_value_map_;
  if (!off_the_record_)
    map_to_modify = &value_map_;

  {
    base::AutoLock auto_lock(map_to_modify->GetLock());
    if (!value.is_none()) {
      if (!map_to_modify->SetValue(primary_pattern, secondary_pattern,
                                   content_type_, value.Clone(),
                                   metadata.Clone(), partition_key)) {
        return;
      }
    } else {
      if (!map_to_modify->DeleteValue(primary_pattern, secondary_pattern,
                                      content_type_, partition_key)) {
        return;
      }
    }
  }
  // Update the content settings preference.
  if (!off_the_record_ && !partition_key.in_memory()) {
    UpdatePref(primary_pattern, secondary_pattern, std::move(value),
               std::move(metadata), partition_key);
  }

  notify_callback_.Run(primary_pattern, secondary_pattern, content_type_,
                       &partition_key);
}

void ContentSettingsPref::ClearAllContentSettingsRules(
    const PartitionKey& partition_key) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(prefs_);

  auto* map_to_modify = &value_map_;
  if (off_the_record_) {
    map_to_modify = &off_the_record_value_map_;
  }

  {
    base::AutoLock auto_lock(map_to_modify->GetLock());
    map_to_modify->DeleteValues(content_type_, partition_key);
  }

  if (!off_the_record_ && !partition_key.in_memory()) {
    base::AutoReset<bool> auto_reset(&updating_preferences_, true);
    if (partition_key.is_default()) {
      prefs::ScopedDictionaryPrefUpdate update(prefs_, pref_name_);
      update->Clear();
    } else {
      prefs::ScopedDictionaryPrefUpdate update(prefs_, partitioned_pref_name_);
      update->RemoveWithoutPathExpansion(partition_key.Serialize(), nullptr);
    }
  }

  notify_callback_.Run(ContentSettingsPattern::Wildcard(),
                       ContentSettingsPattern::Wildcard(), content_type_,
                       &partition_key);
}

void ContentSettingsPref::OnShutdown() {
  prefs_ = nullptr;
  registrar_ = nullptr;
}

size_t ContentSettingsPref::GetNumExceptions() {
  base::AutoLock auto_lock(value_map_.GetLock());
  return value_map_.size();
}

bool ContentSettingsPref::TryLockForTesting() const {
  if (!value_map_.GetLock().Try()) {
    return false;
  }
  value_map_.GetLock().Release();
  return true;
}

void ContentSettingsPref::ReadContentSettingsFromPref() {
  // |ScopedDictionaryPrefUpdate| sends out notifications when destructed. This
  // construction order ensures |AutoLock| gets destroyed first and |lock_| is
  // not held when the notifications are sent. Also, |auto_reset| must be still
  // valid when the notifications are sent, so that |Observe| skips the
  // notification.
  base::AutoReset<bool> auto_reset(&updating_preferences_, true);
  base::AutoLock auto_lock(value_map_.GetLock());

  value_map_.clear();

  // Read for the default PartitionKey.
  {
    std::unique_ptr<prefs::ScopedDictionaryPrefUpdate> update;
    std::unique_ptr<prefs::DictionaryValueUpdate> mutable_partition;
    // Don't create `update` in off the record mode to avoid accidentally
    // modifying the pref.
    if (!off_the_record_) {
      update = std::make_unique<prefs::ScopedDictionaryPrefUpdate>(prefs_,
                                                                   pref_name_);
      mutable_partition = update->Get();
    }
    ReadContentSettingsFromPrefForPartition(
        PartitionKey(), prefs_->GetDict(pref_name_), mutable_partition.get());
  }

  // Read for non-default PartitionKeys.
  {
    std::unique_ptr<prefs::ScopedDictionaryPrefUpdate> update;
    // Don't create `update` in off the record mode to avoid accidentally
    // modifying the pref.
    if (!off_the_record_) {
      update = std::make_unique<prefs::ScopedDictionaryPrefUpdate>(
          prefs_, partitioned_pref_name_);
    }

    std::vector<std::string> partitions_to_remove;

    const auto& partitions = prefs_->GetDict(partitioned_pref_name_);
    for (const auto&& [key, value] : partitions) {
      auto partition_key = PartitionKey::Deserialize(key);
      if (!partition_key.has_value()) {
        LOG(ERROR) << "failed to deserialize partition key " << key;
        partitions_to_remove.emplace_back(key);
        continue;
      }

      std::unique_ptr<prefs::DictionaryValueUpdate> mutable_partition;
      if (update) {
        (*update)->GetDictionaryWithoutPathExpansion(key, &mutable_partition);
      }
      ReadContentSettingsFromPrefForPartition(*partition_key, value.GetDict(),
                                              mutable_partition.get());

      if (mutable_partition && mutable_partition->empty()) {
        partitions_to_remove.push_back(key);
      }
    }

    if (update) {
      CHECK(!off_the_record_);
      for (auto partition : partitions_to_remove) {
        (*update)->RemoveWithoutPathExpansion(partition, nullptr);
      }
    }
  }
}

void ContentSettingsPref::ReadContentSettingsFromPrefForPartition(
    const PartitionKey& partition_key,
    const base::Value::Dict& partition,
    prefs::DictionaryValueUpdate* mutable_partition) {
  CHECK(!partition_key.in_memory());
  // Accumulates non-canonical pattern strings found in Prefs for which the
  // corresponding canonical pattern is also in Prefs. In these cases the
  // canonical version takes priority, and the non-canonical pattern is removed.
  std::vector<std::string> non_canonical_patterns_to_remove;

  // Keeps track of expired pattern strings found in Prefs, in these cases we
  // will remove the expired entries.
  std::vector<std::string> expired_patterns_to_remove;

  // Keeps track of pattern strings with expired last used permission found in
  // Prefs, in these cases we will remove the expired field.
  std::vector<std::string> expired_permission_usage_to_remove;

  // Accumulates non-canonical pattern strings found in Prefs for which the
  // canonical pattern is not found in Prefs. The exception data for these
  // patterns is to be re-keyed under the canonical pattern.
  base::StringPairs non_canonical_patterns_to_canonical_pattern;

  for (const auto&& i : partition) {
    const std::string& pattern_str(i.first);
    PatternPair pattern_pair = ParsePatternString(pattern_str);
    if (!pattern_pair.first.IsValid() || !pattern_pair.second.IsValid()) {
      // TODO: Change this to DFATAL when crbug.com/132659 is fixed.
      LOG(ERROR) << "Invalid pattern strings: " << pattern_str;
      continue;
    }

    const std::string canonicalized_pattern_str =
        CreatePatternString(pattern_pair.first, pattern_pair.second);
    DCHECK(!canonicalized_pattern_str.empty());
    if (canonicalized_pattern_str != pattern_str) {
      if (partition.Find(canonicalized_pattern_str)) {
        non_canonical_patterns_to_remove.push_back(pattern_str);
        continue;
      } else {
        // Need a container that preserves ordering of insertions, so that if
        // multiple non-canonical patterns map to the same canonical pattern,
        // the Preferences updating logic after this loop will preserve the same
        // value in Prefs that this loop ultimately leaves in |value_map_|.
        non_canonical_patterns_to_canonical_pattern.emplace_back(
            pattern_str, canonicalized_pattern_str);
      }
    }

    // Get settings dictionary for the current pattern string, and read
    // settings from the dictionary.
    if(!i.second.is_dict()) {
      LOG(ERROR) << "Invalid settings dictionary for pattern string: "
                 << pattern_str << " with value: " << i.second.DebugString();
      continue;
    }
    const base::Value::Dict& settings_dictionary = i.second.GetDict();

    // Check to see if the setting is expired or not. This may be due to a past
    // expiration date or a SessionModel of UserSession.
    base::Time expiration = GetExpiration(settings_dictionary);
    mojom::SessionModel session_model = GetSessionModel(settings_dictionary);
    if (ShouldRemoveSetting(expiration, session_model)) {
      expired_patterns_to_remove.push_back(pattern_str);
      continue;
    }
    // Users may edit the stored fields directly, so we cannot assume their
    // presence and validity.
    base::TimeDelta lifetime = content_settings::RuleMetaData::ComputeLifetime(
        /*lifetime=*/GetLifetime(settings_dictionary),
        /*expiration=*/expiration);

    const base::Value* value = settings_dictionary.Find(kSettingKey);
    if (value) {
      base::Time last_modified;
      base::Time last_used;
      base::Time last_visited;
      if (!off_the_record_) {
        // Don't copy over timestamps for OTR profiles because some features
        // rely on this to differentiate inherited from fresh OTR permissions.
        // See RecentSiteSettingsHelperTest.IncognitoPermissionTimestamps
        last_modified = GetLastModified(settings_dictionary);
        last_used = GetLastUsed(settings_dictionary);
        if (last_used != base::Time() &&
            clock_->Now() - last_used >= kLastUsedPermissionExpiration) {
          expired_permission_usage_to_remove.push_back(pattern_str);
          last_used = base::Time();
        }
        last_visited = GetLastVisit(settings_dictionary);
      }
      DCHECK(IsValueAllowedForType(*value, content_type_));
      RuleMetaData metadata;
      metadata.set_last_modified(last_modified);
      metadata.set_last_used(last_used);
      metadata.set_last_visited(last_visited);
      metadata.SetExpirationAndLifetime(expiration, lifetime);
      metadata.set_session_model(session_model);
      metadata.set_decided_by_related_website_sets(
          GetDecidedByRelatedWebsiteSets(settings_dictionary));

      value_map_.SetValue(std::move(pattern_pair.first),
                          std::move(pattern_pair.second), content_type_,
                          value->Clone(), std::move(metadata), partition_key);
    }
  }

  // Canonicalization and expiration are unnecessary when |off_the_record_|.
  // Both off_the_record and non off_the_record read from the same pref and non
  // off_the_record reads occur before off_the_record reads. Thus, by the time
  // the off_the_record call to ReadContentSettingsFromPref() occurs, the
  // regular profile will have canonicalized the stored pref data.
  if (!off_the_record_) {
    for (const auto& pattern : non_canonical_patterns_to_remove) {
      mutable_partition->RemoveWithoutPathExpansion(pattern, nullptr);
    }

    for (const auto& pattern : expired_patterns_to_remove) {
      mutable_partition->RemoveWithoutPathExpansion(pattern, nullptr);
    }

    for (const auto& pattern : expired_permission_usage_to_remove) {
      if (mutable_partition->HasKey(pattern)) {
        std::unique_ptr<prefs::DictionaryValueUpdate> dict;
        mutable_partition->GetDictionaryWithoutPathExpansion(pattern, &dict);
        dict->RemoveWithoutPathExpansion(kLastUsedKey, nullptr);
      }
    }

    for (const auto& old_to_new_pattern :
         non_canonical_patterns_to_canonical_pattern) {
      base::Value pattern_settings_dictionary;
      mutable_partition->RemoveWithoutPathExpansion(
          old_to_new_pattern.first, &pattern_settings_dictionary);
      mutable_partition->SetWithoutPathExpansion(
          old_to_new_pattern.second, std::move(pattern_settings_dictionary));
    }
  }
}

bool ContentSettingsPref::ShouldRemoveSetting(
    base::Time expiration,
    content_settings::mojom::SessionModel session_model) {
  if (!content_settings::ShouldTypeExpireActively(content_type_) &&
      !expiration.is_null() && expiration < clock_->Now()) {
    // Delete if an expiration date is set and in the past.
    return true;
  }

  // Off the Record preferences are inherited from the parent profile, which
  // has already been culled.
  if (off_the_record_) {
    return false;
  }

  // Clear non-restorable user session settings, or non-Durable settings when no
  // restoring a previous session.
  switch (session_model) {
    case content_settings::mojom::SessionModel::DURABLE:
      return false;
    case content_settings::mojom::SessionModel::USER_SESSION:
    case content_settings::mojom::SessionModel::ONE_TIME:
      return !restore_session_;
  }
}

void ContentSettingsPref::OnPrefChanged() {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (updating_preferences_)
    return;

  ReadContentSettingsFromPref();

  notify_callback_.Run(ContentSettingsPattern::Wildcard(),
                       ContentSettingsPattern::Wildcard(), content_type_,
                       nullptr);
}

void ContentSettingsPref::UpdatePref(
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern,
    base::Value value,
    const RuleMetaData& metadata,
    const PartitionKey& partition_key) {
  // Ensure that |lock_| is not held by this thread, since this function will
  // send out notifications (by |~ScopedDictionaryPrefUpdate|).
  AssertLockNotHeld();
  CHECK(!off_the_record_);
  CHECK(!partition_key.in_memory());

  base::AutoReset<bool> auto_reset(&updating_preferences_, true);
  {
    prefs::ScopedDictionaryPrefUpdate update(
        prefs_,
        partition_key.is_default() ? pref_name_ : partitioned_pref_name_);
    std::unique_ptr<prefs::DictionaryValueUpdate> pattern_pairs_settings;
    const auto serialized_partition_key = partition_key.Serialize();
    if (partition_key.is_default()) {
      pattern_pairs_settings = update.Get();
    } else {
      if (!update->GetDictionaryWithoutPathExpansion(serialized_partition_key,
                                                     &pattern_pairs_settings)) {
        // The partition does not have any data.

        if (value.is_none()) {
          // Nothing to do.
          return;
        } else {
          pattern_pairs_settings = update->SetDictionaryWithoutPathExpansion(
              serialized_partition_key, base::Value::Dict());
        }
      }
    }

    // Get settings dictionary for the given patterns.
    std::string pattern_str(
        CreatePatternString(primary_pattern, secondary_pattern));
    std::unique_ptr<prefs::DictionaryValueUpdate> settings_dictionary;
    bool found = pattern_pairs_settings->GetDictionaryWithoutPathExpansion(
        pattern_str, &settings_dictionary);

    if (!found && !value.is_none()) {
      settings_dictionary =
          pattern_pairs_settings->SetDictionaryWithoutPathExpansion(
              pattern_str, base::Value::Dict());
    }

    if (!settings_dictionary) {
      // This happens when there isn't existing data for the pattern, and
      // `value` is none. So there is nothing to do.
      return;
    }

    // Update settings dictionary.
    if (value.is_none()) {
      settings_dictionary->RemoveWithoutPathExpansion(kSettingKey, nullptr);
      settings_dictionary->RemoveWithoutPathExpansion(kLastModifiedKey,
                                                      nullptr);
      settings_dictionary->RemoveWithoutPathExpansion(kLastVisitKey, nullptr);
      settings_dictionary->RemoveWithoutPathExpansion(kExpirationKey, nullptr);
      settings_dictionary->RemoveWithoutPathExpansion(kSessionModelKey,
                                                      nullptr);
      settings_dictionary->RemoveWithoutPathExpansion(kLifetimeKey, nullptr);
      settings_dictionary->RemoveWithoutPathExpansion(
          kDecidedByRelatedWebsiteSets, nullptr);
    } else {
      settings_dictionary->SetKey(kSettingKey, std::move(value));
      if (metadata.last_modified() != base::Time()) {
        settings_dictionary->SetKey(
            kLastModifiedKey, base::TimeToValue(metadata.last_modified()));
      }
      if (metadata.expiration() != base::Time()) {
        settings_dictionary->SetKey(kExpirationKey,
                                    base::TimeToValue(metadata.expiration()));
      }
      if (metadata.session_model() != mojom::SessionModel::DURABLE) {
        settings_dictionary->SetKey(
            kSessionModelKey,
            base::Value(static_cast<int>(metadata.session_model())));
      }
      if (metadata.last_used() != base::Time()) {
        settings_dictionary->SetKey(kLastUsedKey,
                                    base::TimeToValue(metadata.last_used()));
      }
      if (metadata.last_visited() != base::Time()) {
        settings_dictionary->SetKey(kLastVisitKey,
                                    base::TimeToValue(metadata.last_visited()));
      }
      if (!metadata.lifetime().is_zero()) {
        settings_dictionary->SetKey(
            kLifetimeKey, base::TimeDeltaToValue(metadata.lifetime()));
      }
      if (metadata.decided_by_related_website_sets()) {
        settings_dictionary->SetKey(
            kDecidedByRelatedWebsiteSets,
            base::Value(metadata.decided_by_related_website_sets()));
      }
    }

    // Remove the settings dictionary if it is empty.
    if (settings_dictionary->empty()) {
      pattern_pairs_settings->RemoveWithoutPathExpansion(pattern_str, nullptr);
    }
    if (!partition_key.is_default() && pattern_pairs_settings->empty()) {
      update->RemoveWithoutPathExpansion(serialized_partition_key, nullptr);
    }
  }
}

void ContentSettingsPref::AssertLockNotHeld() const {
#if !defined(NDEBUG)
  // |Lock::Acquire()| will assert if the lock is held by this thread.
  value_map_.GetLock().Acquire();
  value_map_.GetLock().Release();
#endif
}

void ContentSettingsPref::SetClockForTesting(const base::Clock* clock) {
  clock_ = clock;
  value_map_.SetClockForTesting(clock);                 // IN-TEST
  off_the_record_value_map_.SetClockForTesting(clock);  // IN-TEST
}

}  // namespace content_settings