File: chrome_browsing_data_lifetime_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 (479 lines) | stat: -rw-r--r-- 19,162 bytes parent folder | download | duplicates (5)
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
// 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 "chrome/browser/browsing_data/chrome_browsing_data_lifetime_manager.h"

#include <algorithm>
#include <limits>
#include <set>
#include <string>
#include <utility>

#include "base/command_line.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/scoped_observation.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_traits.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
#include "chrome/browser/lifetime/browser_shutdown.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/signin_util.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/browsing_data/core/browsing_data_policies_utils.h"
#include "components/browsing_data/core/pref_names.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "components/keep_alive_registry/scoped_keep_alive.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/sync/service/sync_service.h"
#include "components/sync/service/sync_user_settings.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_filter_builder.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/web_contents.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "url/gurl.h"
#include "url/origin.h"

#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#else
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#endif

namespace {

constexpr int kInitialCleanupDelayInSeconds = 15;
constexpr int kTestCleanupPeriodInMinutes = 5;
constexpr int kDefaultCleanupPeriodInMinutes = 30;

using ScheduledRemovalSettings =
    ChromeBrowsingDataLifetimeManager::ScheduledRemovalSettings;

// An observer of all the browsing data removal tasks that are started by the
// ChromeBrowsingDataLifetimeManager that records the the tasks starts and
// completed states as well as their durations.
class BrowsingDataRemoverObserver
    : public content::BrowsingDataRemover::Observer {
 public:
  ~BrowsingDataRemoverObserver() override = default;

  // Creates an instance of BrowsingDataRemoverObserver that
  // manages its own lifetime. The instance will be deleted after
  // |OnBrowsingDataRemoverDone| is called. |keep_alive| is an optional
  // parameter to pass to ensure that the browser does not initiates a shutdown
  // before the browsing data clearing is complete.
  static content::BrowsingDataRemover::Observer* Create(
      content::BrowsingDataRemover* remover,
      bool filterable_deletion,
      Profile* profile,
      bool keep_browser_alive = false) {
    return new BrowsingDataRemoverObserver(remover, filterable_deletion,
                                           profile, keep_browser_alive);
  }

  // content::BrowsingDataRemover::Observer:
  void OnBrowsingDataRemoverDone(uint64_t failed_data_types) override {
    base::UmaHistogramMediumTimes(duration_histogram(),
                                  base::TimeTicks::Now() - start_time_);
    // Having |keep_browser_alive_| being true means that the deletion that just
    // finished was happening at the browser exit, therefore
    // |kClearBrowsingDataOnExitDeletionPending| is no more necessary;
    if (keep_browser_alive_) {
      profile_->GetPrefs()->ClearPref(
          browsing_data::prefs::kClearBrowsingDataOnExitDeletionPending);
    }
    // The profile and browser should not be shutting down yet.
    DCHECK(!keep_browser_alive_ || !profile_->ShutdownStarted());
    delete this;
  }

 private:
  BrowsingDataRemoverObserver(content::BrowsingDataRemover* remover,
                              bool filterable_deletion,
                              Profile* profile,
                              bool keep_browser_alive)
      : start_time_(base::TimeTicks::Now()),
        filterable_deletion_(filterable_deletion),
        profile_(profile),
        keep_browser_alive_(keep_browser_alive) {
#if !BUILDFLAG(IS_ANDROID)
    if (keep_browser_alive) {
      keep_alive_ = std::make_unique<ScopedKeepAlive>(
          KeepAliveOrigin::BROWSING_DATA_LIFETIME_MANAGER,
          KeepAliveRestartOption::DISABLED);
    }
#endif
    browsing_data_remover_observer_.Observe(remover);
  }

  const char* duration_histogram() const {
    static constexpr char kDurationScheduledFilterableDeletion[] =
        "History.BrowsingDataLifetime.Duration.ScheduledFilterableDeletion";
    static constexpr char kDurationScheduledUnfilterableDeletion[] =
        "History.BrowsingDataLifetime.Duration.ScheduledUnfilterableDeletion";
    static constexpr char kDurationBrowserShutdownDeletion[] =
        "History.BrowsingDataLifetime.Duration.BrowserShutdownDeletion";
    return keep_browser_alive_
               ? kDurationBrowserShutdownDeletion
               : filterable_deletion_ ? kDurationScheduledFilterableDeletion
                                      : kDurationScheduledUnfilterableDeletion;
  }

  base::ScopedObservation<content::BrowsingDataRemover,
                          content::BrowsingDataRemover::Observer>
      browsing_data_remover_observer_{this};
  const base::TimeTicks start_time_;
  const bool filterable_deletion_;

  const raw_ptr<Profile> profile_;
  bool keep_browser_alive_;
#if !BUILDFLAG(IS_ANDROID)
  std::unique_ptr<ScopedKeepAlive> keep_alive_;
#endif
};

uint64_t GetOriginTypeMask(const base::Value::List& data_types) {
  uint64_t result = 0;
  for (const auto& data_type : data_types) {
    std::optional<browsing_data::PolicyDataType> policy_data_type =
        browsing_data::NameToPolicyDataType(data_type.GetString());
    if (!policy_data_type.has_value()) {
      continue;
    }
    switch (*policy_data_type) {
      case browsing_data::PolicyDataType::kCookiesAndOtherSiteData:
        result |= content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB;
        break;
      case browsing_data::PolicyDataType::kHostedAppData:
        result |= content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB;
        break;
      default:
        break;
    }
  }
  return result;
}

uint64_t GetRemoveMask(const base::Value::List& data_types) {
  uint64_t result = 0;
  for (const auto& data_type : data_types) {
    std::optional<browsing_data::PolicyDataType> policy_data_type =
        browsing_data::NameToPolicyDataType(data_type.GetString());
    if (!policy_data_type.has_value()) {
      continue;
    }
    switch (*policy_data_type) {
      case browsing_data::PolicyDataType::kBrowsingHistory:
        result |= chrome_browsing_data_remover::DATA_TYPE_HISTORY;
        break;
      case browsing_data::PolicyDataType::kDownloadHistory:
        result |= content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS;
        break;
      case browsing_data::PolicyDataType::kCookiesAndOtherSiteData:
        result |= chrome_browsing_data_remover::DATA_TYPE_SITE_DATA;
        break;
      case browsing_data::PolicyDataType::kCachedImagesAndFiles:
        result |= content::BrowsingDataRemover::DATA_TYPE_CACHE;
        break;
      case browsing_data::PolicyDataType::kPasswordSignin:
        result |= chrome_browsing_data_remover::DATA_TYPE_PASSWORDS;
        break;
      case browsing_data::PolicyDataType::kAutofill:
        result |= chrome_browsing_data_remover::DATA_TYPE_FORM_DATA;
        break;
      case browsing_data::PolicyDataType::kSiteSettings:
        result |= chrome_browsing_data_remover::DATA_TYPE_CONTENT_SETTINGS;
        break;
      case browsing_data::PolicyDataType::kHostedAppData:
        result |= chrome_browsing_data_remover::DATA_TYPE_SITE_DATA;
        break;
      case browsing_data::PolicyDataType::kNumTypes:
        NOTREACHED();
    }
  }
  return result;
}

std::vector<ScheduledRemovalSettings> ConvertToScheduledRemovalSettings(
    const base::Value::List& browsing_data_settings) {
  std::vector<ScheduledRemovalSettings> scheduled_removals_settings;
  for (const auto& setting : browsing_data_settings) {
    const auto* data_types =
        setting.GetDict().FindList(browsing_data::policy_fields::kDataTypes);
    const auto time_to_live_in_hours = setting.GetDict().FindInt(
        browsing_data::policy_fields::kTimeToLiveInHours);
    DCHECK(data_types);
    scheduled_removals_settings.push_back({GetRemoveMask(*data_types),
                                           GetOriginTypeMask(*data_types),
                                           *time_to_live_in_hours});
  }
  return scheduled_removals_settings;
}

std::set<GURL> GetOpenedUrlsAndOngoingDownloads(Profile* profile) {
  std::set<GURL> result;
  // TODO (crbug/1288416): Enable this for android.
#if !BUILDFLAG(IS_ANDROID)
  for (Browser* browser : *BrowserList::GetInstance()) {
    if (browser->profile() != profile) {
      continue;
    }
    for (int i = 0; i < browser->tab_strip_model()->count(); ++i) {
      result.insert(browser->tab_strip_model()->GetWebContentsAt(i)->GetURL());
    }
  }
#else
  for (const TabModel* model : TabModelList::models()) {
    for (int index = 0; index < model->GetTabCount(); ++index) {
      TabAndroid* tab = model->GetTabAt(index);
      if (tab)
        result.insert(tab->GetURL());
    }
  }
#endif

  download::SimpleDownloadManager::DownloadVector downloads;
  if (auto* download_manager = profile->GetDownloadManager()) {
    download_manager->GetAllDownloads(&downloads);
  }
  for (const download::DownloadItem* download : downloads) {
    auto state = download->GetState();
    if (state != download::DownloadItem::DownloadState::IN_PROGRESS) {
      continue;
    }
    result.insert(download->GetURL());
  }
  return result;
}

// Returns the sync types that might be reuired to be disabled for the browsing
// data types specified in the policy value.
syncer::UserSelectableTypeSet GetSyncTypesForPolicyPref(
    Profile* profile,
    const std::string& pref_name) {
  DCHECK(pref_name == browsing_data::prefs::kBrowsingDataLifetime ||
         pref_name == browsing_data::prefs::kClearBrowsingDataOnExitList);

  const base::Value& data_lifetime_value =
      profile->GetPrefs()->GetValue(pref_name);

  return pref_name == browsing_data::prefs::kBrowsingDataLifetime
             ? browsing_data::GetSyncTypesForBrowsingDataLifetime(
                   data_lifetime_value)
             : browsing_data::GetSyncTypesForClearBrowsingData(
                   data_lifetime_value);
}

}  // namespace

namespace browsing_data {

namespace policy_fields {

const char kTimeToLiveInHours[] = "time_to_live_in_hours";
const char kDataTypes[] = "data_types";

}  // namespace policy_fields
}  // namespace browsing_data

ChromeBrowsingDataLifetimeManager::ChromeBrowsingDataLifetimeManager(
    content::BrowserContext* browser_context)
    : profile_(Profile::FromBrowserContext(browser_context)) {
  DCHECK(!profile_->IsGuestSession() || profile_->IsOffTheRecord());
  pref_change_registrar_.Init(profile_->GetPrefs());
  pref_change_registrar_.Add(
      browsing_data::prefs::kBrowsingDataLifetime,
      base::BindRepeating(
          &ChromeBrowsingDataLifetimeManager::UpdateScheduledRemovalSettings,
          base::Unretained(this)));

  // When the service is instantiated, wait a few minutes after Chrome startup
  // to start deleting data.
  content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
      ->PostDelayedTask(FROM_HERE,
                        base::BindOnce(&ChromeBrowsingDataLifetimeManager::
                                           UpdateScheduledRemovalSettings,
                                       weak_ptr_factory_.GetWeakPtr()),
                        base::Seconds(kInitialCleanupDelayInSeconds));
}

ChromeBrowsingDataLifetimeManager::~ChromeBrowsingDataLifetimeManager() =
    default;

void ChromeBrowsingDataLifetimeManager::Shutdown() {
  pref_change_registrar_.RemoveAll();
  weak_ptr_factory_.InvalidateWeakPtrs();
}

void ChromeBrowsingDataLifetimeManager::ClearBrowsingDataForOnExitPolicy(
    bool keep_browser_alive) {
  const base::Value::List& data_types = profile_->GetPrefs()->GetList(
      browsing_data::prefs::kClearBrowsingDataOnExitList);

  if (!data_types.empty() &&
      IsConditionSatisfiedForBrowsingDataRemoval(GetSyncTypesForPolicyPref(
          profile_, browsing_data::prefs::kClearBrowsingDataOnExitList))) {
    profile_->GetPrefs()->SetBoolean(
        browsing_data::prefs::kClearBrowsingDataOnExitDeletionPending, true);
    auto* remover = profile_->GetBrowsingDataRemover();
    // Add a ScopedKeepAlive to hold the browser shutdown until the browsing
    // data is deleted and the profile is destroyed.
#if DCHECK_IS_ON()
    if (browser_shutdown::HasShutdownStarted())
      DCHECK(keep_browser_alive);
#endif
    remover->RemoveAndReply(base::Time(), base::Time::Max(),
                            GetRemoveMask(data_types),
                            GetOriginTypeMask(data_types),
                            BrowsingDataRemoverObserver::Create(
                                remover, /*filterable_deletion=*/true, profile_,
                                keep_browser_alive));
  } else {
    profile_->GetPrefs()->ClearPref(
        browsing_data::prefs::kClearBrowsingDataOnExitDeletionPending);
  }
}

void ChromeBrowsingDataLifetimeManager::UpdateScheduledRemovalSettings() {
  weak_ptr_factory_.InvalidateWeakPtrs();
  scheduled_removals_settings_ =
      ConvertToScheduledRemovalSettings(profile_->GetPrefs()->GetList(
          browsing_data::prefs::kBrowsingDataLifetime));

  if (!scheduled_removals_settings_.empty())
    StartScheduledBrowsingDataRemoval();
}

void ChromeBrowsingDataLifetimeManager::StartScheduledBrowsingDataRemoval() {
  bool has_sim_switch = base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kSimulateBrowsingDataLifetime);
  int cleanup_period = has_sim_switch ? kTestCleanupPeriodInMinutes
                                      : kDefaultCleanupPeriodInMinutes;

  content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
      ->PostDelayedTask(FROM_HERE,
                        base::BindOnce(&ChromeBrowsingDataLifetimeManager::
                                           StartScheduledBrowsingDataRemoval,
                                       weak_ptr_factory_.GetWeakPtr()),
                        base::Minutes(cleanup_period));

  if (!IsConditionSatisfiedForBrowsingDataRemoval(GetSyncTypesForPolicyPref(
          profile_, browsing_data::prefs::kBrowsingDataLifetime))) {
    return;
  }

  content::BrowsingDataRemover* remover = profile_->GetBrowsingDataRemover();

  for (auto& removal_settings : scheduled_removals_settings_) {
    if (!has_sim_switch && removal_settings.time_to_live_in_hours <= 0) {
      continue;
    }

    auto deletion_end_time =
        has_sim_switch
            ? base::Time::Now() - base::Minutes(3)
            : end_time_for_testing_.value_or(
                  base::Time::Now() -
                  base::Hours(removal_settings.time_to_live_in_hours));

    auto filterable_remove_mask =
        removal_settings.remove_mask &
        chrome_browsing_data_remover::FILTERABLE_DATA_TYPES;
    if (filterable_remove_mask) {
      auto filter_builder = content::BrowsingDataFilterBuilder::Create(
          content::BrowsingDataFilterBuilder::Mode::kPreserve);
      for (const auto& url : GetOpenedUrlsAndOngoingDownloads(profile_)) {
        std::string domain = GetDomainAndRegistry(
            url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
        if (domain.empty()) {
          domain = url.host();  // IP address or internal hostname.
        }
        filter_builder->AddRegisterableDomain(domain);
      }
      remover->RemoveWithFilterAndReply(
          base::Time::Min(), deletion_end_time, filterable_remove_mask,
          removal_settings.origin_type_mask, std::move(filter_builder),
          testing_data_remover_observer_
              ? testing_data_remover_observer_.get()
              : BrowsingDataRemoverObserver::Create(
                    remover, /*filterable_deletion=*/true, profile_));
    }

    auto unfilterable_remove_mask =
        removal_settings.remove_mask &
        ~chrome_browsing_data_remover::FILTERABLE_DATA_TYPES;
    if (unfilterable_remove_mask) {
      remover->RemoveAndReply(
          base::Time::Min(), deletion_end_time, unfilterable_remove_mask,
          removal_settings.origin_type_mask,
          testing_data_remover_observer_
              ? testing_data_remover_observer_.get()
              : BrowsingDataRemoverObserver::Create(
                    remover, /*filterable_deletion=*/false, profile_));
    }
  }
}

bool ChromeBrowsingDataLifetimeManager::
    IsConditionSatisfiedForBrowsingDataRemoval(
        const syncer::UserSelectableTypeSet sync_types) {
  bool sync_disabled = !SyncServiceFactory::IsSyncAllowed(profile_);
  // Condition is satisfied if sync is fully disabled by policy.
  if (sync_disabled) {
    return sync_disabled;
  }

#if !BUILDFLAG(IS_CHROMEOS)
  // Allow clearing data if browser signin is disabled.
  if (!profile_->GetPrefs()->GetBoolean(prefs::kSigninAllowed)) {
    return true;
  }
  // If signin will be disabled on next startup, delay the browsing data
  // clearing until then.
  if (!profile_->GetPrefs()->GetBoolean(prefs::kSigninAllowedOnNextStartup)) {
    profile_->GetPrefs()->SetBoolean(
        browsing_data::prefs::kClearBrowsingDataOnExitDeletionPending, true);
    return false;
  }
#endif

  // Check that sync types have been disabled if neither sync nor browser sign
  // in is disabled.
  syncer::SyncService* sync_service =
      SyncServiceFactory::GetForProfile(profile_);

  // If the sync service is not available, data can be safely cleared as it is
  // not synced.
  if (!sync_service) {
    return true;
  }

  for (syncer::UserSelectableType type : sync_types) {
    if (!sync_service->GetUserSettings()->IsTypeManagedByPolicy(type)) {
      return false;
    } else if (sync_service->GetActiveDataTypes().HasAny(
                   syncer::UserSelectableTypeToAllDataTypes(type))) {
      // If the sync type is disabled by policy, but the sync service has not
      // deactivated the type yet, then data can not be safely cleared yet.
      return false;
    }
  }
  return true;
}