Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(92)

Side by Side Diff: chrome/browser/browsing_data/browsing_data_remover_unittest.cc

Issue 2651673002: Reland "Split BrowsingDataRemoverTest into two tests for Impl and Delegate." (Closed)
Patch Set: Added a TODO. Created 3 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <stddef.h>
6 #include <stdint.h>
7
8 #include <list>
9 #include <memory>
10 #include <set>
11 #include <string>
12 #include <utility>
13 #include <vector>
14
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/guid.h"
20 #include "base/location.h"
21 #include "base/logging.h"
22 #include "base/macros.h"
23 #include "base/memory/ptr_util.h"
24 #include "base/message_loop/message_loop.h"
25 #include "base/run_loop.h"
26 #include "base/single_thread_task_runner.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/task/cancelable_task_tracker.h"
30 #include "base/threading/thread_task_runner_handle.h"
31 #include "build/build_config.h"
32 #include "chrome/browser/autofill/personal_data_manager_factory.h"
33 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
34 #include "chrome/browser/browsing_data/browsing_data_filter_builder.h"
35 #include "chrome/browser/browsing_data/browsing_data_helper.h"
36 #include "chrome/browser/browsing_data/browsing_data_remover.h"
37 #include "chrome/browser/browsing_data/browsing_data_remover_factory.h"
38 #include "chrome/browser/browsing_data/browsing_data_remover_impl.h"
39 #include "chrome/browser/browsing_data/browsing_data_remover_test_util.h"
40 #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
41 #include "chrome/browser/browsing_data/registrable_domain_filter_builder.h"
42 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
43 #include "chrome/browser/domain_reliability/service_factory.h"
44 #include "chrome/browser/download/chrome_download_manager_delegate.h"
45 #include "chrome/browser/favicon/favicon_service_factory.h"
46 #include "chrome/browser/history/history_service_factory.h"
47 #include "chrome/browser/password_manager/password_store_factory.h"
48 #include "chrome/browser/permissions/permission_decision_auto_blocker.h"
49 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
50 #include "chrome/browser/storage/durable_storage_permission_context.h"
51 #include "chrome/common/pref_names.h"
52 #include "chrome/test/base/testing_browser_process.h"
53 #include "chrome/test/base/testing_profile.h"
54 #include "components/autofill/core/browser/autofill_profile.h"
55 #include "components/autofill/core/browser/autofill_test_utils.h"
56 #include "components/autofill/core/browser/credit_card.h"
57 #include "components/autofill/core/browser/personal_data_manager.h"
58 #include "components/autofill/core/browser/personal_data_manager_observer.h"
59 #include "components/autofill/core/common/autofill_constants.h"
60 #include "components/bookmarks/browser/bookmark_model.h"
61 #include "components/bookmarks/test/bookmark_test_helpers.h"
62 #include "components/browsing_data/core/browsing_data_utils.h"
63 #include "components/content_settings/core/browser/host_content_settings_map.h"
64 #include "components/content_settings/core/common/content_settings.h"
65 #include "components/content_settings/core/common/content_settings_pattern.h"
66 #include "components/domain_reliability/clear_mode.h"
67 #include "components/domain_reliability/monitor.h"
68 #include "components/domain_reliability/service.h"
69 #include "components/favicon/core/favicon_service.h"
70 #include "components/history/core/browser/history_service.h"
71 #include "components/ntp_snippets/bookmarks/bookmark_last_visit_utils.h"
72 #include "components/omnibox/browser/omnibox_pref_names.h"
73 #include "components/os_crypt/os_crypt_mocker.h"
74 #include "components/password_manager/core/browser/mock_password_store.h"
75 #include "components/password_manager/core/browser/password_manager_test_utils.h "
76 #include "components/password_manager/core/browser/password_store_consumer.h"
77 #include "components/prefs/testing_pref_service.h"
78 #include "content/public/browser/browser_context.h"
79 #include "content/public/browser/cookie_store_factory.h"
80 #include "content/public/browser/dom_storage_context.h"
81 #include "content/public/browser/local_storage_usage_info.h"
82 #include "content/public/browser/permission_type.h"
83 #include "content/public/browser/storage_partition.h"
84 #include "content/public/test/mock_download_manager.h"
85 #include "content/public/test/test_browser_thread.h"
86 #include "content/public/test/test_browser_thread_bundle.h"
87 #include "content/public/test/test_utils.h"
88 #include "extensions/features/features.h"
89 #include "net/cookies/cookie_store.h"
90 #include "net/http/http_network_session.h"
91 #include "net/http/http_transaction_factory.h"
92 #include "net/ssl/channel_id_service.h"
93 #include "net/ssl/channel_id_store.h"
94 #include "net/ssl/ssl_client_cert_type.h"
95 #include "net/url_request/url_request_context.h"
96 #include "net/url_request/url_request_context_getter.h"
97 #include "ppapi/features/features.h"
98 #include "testing/gmock/include/gmock/gmock.h"
99 #include "testing/gtest/include/gtest/gtest.h"
100 #include "third_party/skia/include/core/SkBitmap.h"
101 #include "ui/gfx/favicon_size.h"
102 #include "url/origin.h"
103
104 #if defined(OS_ANDROID)
105 #include "chrome/browser/android/webapps/webapp_registry.h"
106 #endif
107
108 #if defined(OS_CHROMEOS)
109 #include "chrome/browser/chromeos/login/users/mock_user_manager.h"
110 #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
111 #include "chrome/browser/chromeos/settings/cros_settings.h"
112 #include "chrome/browser/chromeos/settings/device_settings_service.h"
113 #include "chromeos/dbus/dbus_thread_manager.h"
114 #include "chromeos/dbus/mock_cryptohome_client.h"
115 #include "components/signin/core/account_id/account_id.h"
116 #endif
117
118 #if BUILDFLAG(ENABLE_EXTENSIONS)
119 #include "chrome/browser/extensions/mock_extension_special_storage_policy.h"
120 #endif
121
122 #if BUILDFLAG(ENABLE_PLUGINS)
123 #include "chrome/browser/browsing_data/mock_browsing_data_flash_lso_helper.h"
124 #endif
125
126 class MockExtensionSpecialStoragePolicy;
127
128 using content::BrowserThread;
129 using content::StoragePartition;
130 using domain_reliability::CLEAR_BEACONS;
131 using domain_reliability::CLEAR_CONTEXTS;
132 using domain_reliability::DomainReliabilityClearMode;
133 using domain_reliability::DomainReliabilityMonitor;
134 using domain_reliability::DomainReliabilityService;
135 using domain_reliability::DomainReliabilityServiceFactory;
136 using testing::_;
137 using testing::ByRef;
138 using testing::Eq;
139 using testing::Invoke;
140 using testing::IsEmpty;
141 using testing::Matcher;
142 using testing::MakeMatcher;
143 using testing::MatcherInterface;
144 using testing::MatchResultListener;
145 using testing::Not;
146 using testing::Return;
147 using testing::SizeIs;
148 using testing::WithArgs;
149
150 namespace {
151
152 const char kTestOrigin1[] = "http://host1.com:1/";
153 const char kTestRegisterableDomain1[] = "host1.com";
154 const char kTestOrigin2[] = "http://host2.com:1/";
155 const char kTestOrigin3[] = "http://host3.com:1/";
156 const char kTestRegisterableDomain3[] = "host3.com";
157 const char kTestOrigin4[] = "https://host3.com:1/";
158 const char kTestOriginExt[] = "chrome-extension://abcdefghijklmnopqrstuvwxyz/";
159 const char kTestOriginDevTools[] = "chrome-devtools://abcdefghijklmnopqrstuvw/";
160
161 // For Autofill.
162 const char kWebOrigin[] = "https://www.example.com/";
163
164 // For HTTP auth.
165 const char kTestRealm[] = "TestRealm";
166
167 const GURL kOrigin1(kTestOrigin1);
168 const GURL kOrigin2(kTestOrigin2);
169 const GURL kOrigin3(kTestOrigin3);
170 const GURL kOrigin4(kTestOrigin4);
171 const GURL kOriginExt(kTestOriginExt);
172 const GURL kOriginDevTools(kTestOriginDevTools);
173
174 const base::FilePath::CharType kDomStorageOrigin1[] =
175 FILE_PATH_LITERAL("http_host1_1.localstorage");
176
177 const base::FilePath::CharType kDomStorageOrigin2[] =
178 FILE_PATH_LITERAL("http_host2_1.localstorage");
179
180 const base::FilePath::CharType kDomStorageOrigin3[] =
181 FILE_PATH_LITERAL("http_host3_1.localstorage");
182
183 const base::FilePath::CharType kDomStorageExt[] = FILE_PATH_LITERAL(
184 "chrome-extension_abcdefghijklmnopqrstuvwxyz_0.localstorage");
185
186 #if defined(OS_CHROMEOS)
187 void FakeDBusCall(const chromeos::BoolDBusMethodCallback& callback) {
188 base::ThreadTaskRunnerHandle::Get()->PostTask(
189 FROM_HERE,
190 base::Bind(callback, chromeos::DBUS_METHOD_CALL_SUCCESS, true));
191 }
192 #endif
193
194 struct StoragePartitionRemovalData {
195 uint32_t remove_mask = 0;
196 uint32_t quota_storage_remove_mask = 0;
197 base::Time remove_begin;
198 base::Time remove_end;
199 StoragePartition::OriginMatcherFunction origin_matcher;
200 StoragePartition::CookieMatcherFunction cookie_matcher;
201
202 StoragePartitionRemovalData() {}
203 };
204
205 net::CanonicalCookie CreateCookieWithHost(const GURL& source) {
206 std::unique_ptr<net::CanonicalCookie> cookie(net::CanonicalCookie::Create(
207 source, "A", "1", std::string(), "/", base::Time::Now(),
208 base::Time::Now(), false, false, net::CookieSameSite::DEFAULT_MODE, false,
209 net::COOKIE_PRIORITY_MEDIUM));
210 EXPECT_TRUE(cookie);
211 return *cookie;
212 }
213
214 class TestStoragePartition : public StoragePartition {
215 public:
216 TestStoragePartition() {}
217 ~TestStoragePartition() override {}
218
219 // content::StoragePartition implementation.
220 base::FilePath GetPath() override { return base::FilePath(); }
221 net::URLRequestContextGetter* GetURLRequestContext() override {
222 return nullptr;
223 }
224 net::URLRequestContextGetter* GetMediaURLRequestContext() override {
225 return nullptr;
226 }
227 storage::QuotaManager* GetQuotaManager() override { return nullptr; }
228 content::AppCacheService* GetAppCacheService() override { return nullptr; }
229 storage::FileSystemContext* GetFileSystemContext() override {
230 return nullptr;
231 }
232 storage::DatabaseTracker* GetDatabaseTracker() override { return nullptr; }
233 content::DOMStorageContext* GetDOMStorageContext() override {
234 return nullptr;
235 }
236 content::IndexedDBContext* GetIndexedDBContext() override { return nullptr; }
237 content::ServiceWorkerContext* GetServiceWorkerContext() override {
238 return nullptr;
239 }
240 content::CacheStorageContext* GetCacheStorageContext() override {
241 return nullptr;
242 }
243 content::PlatformNotificationContext* GetPlatformNotificationContext()
244 override {
245 return nullptr;
246 }
247 content::HostZoomMap* GetHostZoomMap() override { return nullptr; }
248 content::HostZoomLevelContext* GetHostZoomLevelContext() override {
249 return nullptr;
250 }
251 content::ZoomLevelDelegate* GetZoomLevelDelegate() override {
252 return nullptr;
253 }
254
255 void ClearDataForOrigin(uint32_t remove_mask,
256 uint32_t quota_storage_remove_mask,
257 const GURL& storage_origin,
258 net::URLRequestContextGetter* rq_context,
259 const base::Closure& callback) override {
260 BrowserThread::PostTask(BrowserThread::UI,
261 FROM_HERE,
262 base::Bind(&TestStoragePartition::AsyncRunCallback,
263 base::Unretained(this),
264 callback));
265 }
266
267 void ClearData(uint32_t remove_mask,
268 uint32_t quota_storage_remove_mask,
269 const GURL& storage_origin,
270 const OriginMatcherFunction& origin_matcher,
271 const base::Time begin,
272 const base::Time end,
273 const base::Closure& callback) override {
274 // Store stuff to verify parameters' correctness later.
275 storage_partition_removal_data_.remove_mask = remove_mask;
276 storage_partition_removal_data_.quota_storage_remove_mask =
277 quota_storage_remove_mask;
278 storage_partition_removal_data_.remove_begin = begin;
279 storage_partition_removal_data_.remove_end = end;
280 storage_partition_removal_data_.origin_matcher = origin_matcher;
281
282 BrowserThread::PostTask(
283 BrowserThread::UI,
284 FROM_HERE,
285 base::Bind(&TestStoragePartition::AsyncRunCallback,
286 base::Unretained(this), callback));
287 }
288
289 void ClearData(uint32_t remove_mask,
290 uint32_t quota_storage_remove_mask,
291 const OriginMatcherFunction& origin_matcher,
292 const CookieMatcherFunction& cookie_matcher,
293 const base::Time begin,
294 const base::Time end,
295 const base::Closure& callback) override {
296 // Store stuff to verify parameters' correctness later.
297 storage_partition_removal_data_.remove_mask = remove_mask;
298 storage_partition_removal_data_.quota_storage_remove_mask =
299 quota_storage_remove_mask;
300 storage_partition_removal_data_.remove_begin = begin;
301 storage_partition_removal_data_.remove_end = end;
302 storage_partition_removal_data_.origin_matcher = origin_matcher;
303 storage_partition_removal_data_.cookie_matcher = cookie_matcher;
304
305 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
306 base::Bind(&TestStoragePartition::AsyncRunCallback,
307 base::Unretained(this), callback));
308 }
309
310 void Flush() override {}
311
312 StoragePartitionRemovalData GetStoragePartitionRemovalData() {
313 return storage_partition_removal_data_;
314 }
315
316 private:
317 void AsyncRunCallback(const base::Closure& callback) {
318 callback.Run();
319 }
320
321 StoragePartitionRemovalData storage_partition_removal_data_;
322
323 DISALLOW_COPY_AND_ASSIGN(TestStoragePartition);
324 };
325
326 #if defined(OS_ANDROID)
327 class TestWebappRegistry : public WebappRegistry {
328 public:
329 TestWebappRegistry() : WebappRegistry() { }
330
331 void UnregisterWebappsForUrls(
332 const base::Callback<bool(const GURL&)>& url_filter) override {
333 // Mocks out a JNI call.
334 }
335
336 void ClearWebappHistoryForUrls(
337 const base::Callback<bool(const GURL&)>& url_filter) override {
338 // Mocks out a JNI call.
339 }
340 };
341 #endif
342
343 // Custom matcher to test the equivalence of two URL filters. Since those are
344 // blackbox predicates, we can only approximate the equivalence by testing
345 // whether the filter give the same answer for several URLs. This is currently
346 // good enough for our testing purposes, to distinguish whitelists
347 // and blacklists, empty and non-empty filters and such.
348 // TODO(msramek): BrowsingDataRemover and some of its backends support URL
349 // filters, but its constructor currently only takes a single URL and constructs
350 // its own url filter. If an url filter was directly passed to
351 // BrowsingDataRemover (what should eventually be the case), we can use the same
352 // instance in the test as well, and thus simply test base::Callback::Equals()
353 // in this matcher.
354 class ProbablySameFilterMatcher
355 : public MatcherInterface<const base::Callback<bool(const GURL&)>&> {
356 public:
357 explicit ProbablySameFilterMatcher(
358 const base::Callback<bool(const GURL&)>& filter)
359 : to_match_(filter) {
360 }
361
362 virtual bool MatchAndExplain(const base::Callback<bool(const GURL&)>& filter,
363 MatchResultListener* listener) const {
364 if (filter.is_null() && to_match_.is_null())
365 return true;
366 if (filter.is_null() != to_match_.is_null())
367 return false;
368
369 const GURL urls_to_test_[] =
370 {kOrigin1, kOrigin2, kOrigin3, GURL("invalid spec")};
371 for (GURL url : urls_to_test_) {
372 if (filter.Run(url) != to_match_.Run(url)) {
373 if (listener)
374 *listener << "The filters differ on the URL " << url;
375 return false;
376 }
377 }
378 return true;
379 }
380
381 virtual void DescribeTo(::std::ostream* os) const {
382 *os << "is probably the same url filter as " << &to_match_;
383 }
384
385 virtual void DescribeNegationTo(::std::ostream* os) const {
386 *os << "is definitely NOT the same url filter as " << &to_match_;
387 }
388
389 private:
390 const base::Callback<bool(const GURL&)>& to_match_;
391 };
392
393 inline Matcher<const base::Callback<bool(const GURL&)>&> ProbablySameFilter(
394 const base::Callback<bool(const GURL&)>& filter) {
395 return MakeMatcher(new ProbablySameFilterMatcher(filter));
396 }
397
398 bool ProbablySameFilters(
399 const base::Callback<bool(const GURL&)>& filter1,
400 const base::Callback<bool(const GURL&)>& filter2) {
401 return ProbablySameFilter(filter1).MatchAndExplain(filter2, nullptr);
402 }
403
404 base::Time AnHourAgo() {
405 return base::Time::Now() - base::TimeDelta::FromHours(1);
406 }
407
408 } // namespace
409
410 // Testers -------------------------------------------------------------------
411
412 class RemoveCookieTester {
413 public:
414 RemoveCookieTester() {}
415
416 // Returns true, if the given cookie exists in the cookie store.
417 bool ContainsCookie() {
418 scoped_refptr<content::MessageLoopRunner> message_loop_runner =
419 new content::MessageLoopRunner;
420 quit_closure_ = message_loop_runner->QuitClosure();
421 get_cookie_success_ = false;
422 cookie_store_->GetCookiesWithOptionsAsync(
423 kOrigin1, net::CookieOptions(),
424 base::Bind(&RemoveCookieTester::GetCookieCallback,
425 base::Unretained(this)));
426 message_loop_runner->Run();
427 return get_cookie_success_;
428 }
429
430 void AddCookie() {
431 scoped_refptr<content::MessageLoopRunner> message_loop_runner =
432 new content::MessageLoopRunner;
433 quit_closure_ = message_loop_runner->QuitClosure();
434 cookie_store_->SetCookieWithOptionsAsync(
435 kOrigin1, "A=1", net::CookieOptions(),
436 base::Bind(&RemoveCookieTester::SetCookieCallback,
437 base::Unretained(this)));
438 message_loop_runner->Run();
439 }
440
441 protected:
442 void SetCookieStore(net::CookieStore* cookie_store) {
443 cookie_store_ = cookie_store;
444 }
445
446 private:
447 void GetCookieCallback(const std::string& cookies) {
448 if (cookies == "A=1") {
449 get_cookie_success_ = true;
450 } else {
451 EXPECT_EQ("", cookies);
452 get_cookie_success_ = false;
453 }
454 quit_closure_.Run();
455 }
456
457 void SetCookieCallback(bool result) {
458 ASSERT_TRUE(result);
459 quit_closure_.Run();
460 }
461
462 bool get_cookie_success_ = false;
463 base::Closure quit_closure_;
464
465 // CookieStore must out live |this|.
466 net::CookieStore* cookie_store_ = nullptr;
467
468 DISALLOW_COPY_AND_ASSIGN(RemoveCookieTester);
469 };
470
471 void RunClosureAfterCookiesCleared(const base::Closure& task,
472 int cookies_deleted) {
473 task.Run();
474 }
475
476 class RemoveSafeBrowsingCookieTester : public RemoveCookieTester {
477 public:
478 RemoveSafeBrowsingCookieTester()
479 : browser_process_(TestingBrowserProcess::GetGlobal()) {
480 scoped_refptr<safe_browsing::SafeBrowsingService> sb_service =
481 safe_browsing::SafeBrowsingService::CreateSafeBrowsingService();
482 browser_process_->SetSafeBrowsingService(sb_service.get());
483 sb_service->Initialize();
484 base::RunLoop().RunUntilIdle();
485
486 // Make sure the safe browsing cookie store has no cookies.
487 // TODO(mmenke): Is this really needed?
488 base::RunLoop run_loop;
489 net::URLRequestContext* request_context =
490 sb_service->url_request_context()->GetURLRequestContext();
491 request_context->cookie_store()->DeleteAllAsync(
492 base::Bind(&RunClosureAfterCookiesCleared, run_loop.QuitClosure()));
493 run_loop.Run();
494
495 SetCookieStore(request_context->cookie_store());
496 }
497
498 virtual ~RemoveSafeBrowsingCookieTester() {
499 browser_process_->safe_browsing_service()->ShutDown();
500 base::RunLoop().RunUntilIdle();
501 browser_process_->SetSafeBrowsingService(nullptr);
502 }
503
504 private:
505 TestingBrowserProcess* browser_process_;
506
507 DISALLOW_COPY_AND_ASSIGN(RemoveSafeBrowsingCookieTester);
508 };
509
510 class RemoveChannelIDTester : public net::SSLConfigService::Observer {
511 public:
512 explicit RemoveChannelIDTester(TestingProfile* profile) {
513 channel_id_service_ = profile->GetRequestContext()->
514 GetURLRequestContext()->channel_id_service();
515 ssl_config_service_ = profile->GetSSLConfigService();
516 ssl_config_service_->AddObserver(this);
517 }
518
519 ~RemoveChannelIDTester() override {
520 ssl_config_service_->RemoveObserver(this);
521 }
522
523 int ChannelIDCount() { return channel_id_service_->channel_id_count(); }
524
525 // Add a server bound cert for |server| with specific creation and expiry
526 // times. The cert and key data will be filled with dummy values.
527 void AddChannelIDWithTimes(const std::string& server_identifier,
528 base::Time creation_time) {
529 GetChannelIDStore()->SetChannelID(
530 base::MakeUnique<net::ChannelIDStore::ChannelID>(
531 server_identifier, creation_time, crypto::ECPrivateKey::Create()));
532 }
533
534 // Add a server bound cert for |server|, with the current time as the
535 // creation time. The cert and key data will be filled with dummy values.
536 void AddChannelID(const std::string& server_identifier) {
537 base::Time now = base::Time::Now();
538 AddChannelIDWithTimes(server_identifier, now);
539 }
540
541 void GetChannelIDList(net::ChannelIDStore::ChannelIDList* channel_ids) {
542 GetChannelIDStore()->GetAllChannelIDs(
543 base::Bind(&RemoveChannelIDTester::GetAllChannelIDsCallback,
544 channel_ids));
545 }
546
547 net::ChannelIDStore* GetChannelIDStore() {
548 return channel_id_service_->GetChannelIDStore();
549 }
550
551 int ssl_config_changed_count() const {
552 return ssl_config_changed_count_;
553 }
554
555 // net::SSLConfigService::Observer implementation:
556 void OnSSLConfigChanged() override { ssl_config_changed_count_++; }
557
558 private:
559 static void GetAllChannelIDsCallback(
560 net::ChannelIDStore::ChannelIDList* dest,
561 const net::ChannelIDStore::ChannelIDList& result) {
562 *dest = result;
563 }
564
565 net::ChannelIDService* channel_id_service_;
566 scoped_refptr<net::SSLConfigService> ssl_config_service_;
567 int ssl_config_changed_count_ = 0;
568
569 DISALLOW_COPY_AND_ASSIGN(RemoveChannelIDTester);
570 };
571
572 class RemoveHistoryTester {
573 public:
574 RemoveHistoryTester() {}
575
576 bool Init(TestingProfile* profile) WARN_UNUSED_RESULT {
577 if (!profile->CreateHistoryService(true, false))
578 return false;
579 history_service_ = HistoryServiceFactory::GetForProfile(
580 profile, ServiceAccessType::EXPLICIT_ACCESS);
581 return true;
582 }
583
584 // Returns true, if the given URL exists in the history service.
585 bool HistoryContainsURL(const GURL& url) {
586 scoped_refptr<content::MessageLoopRunner> message_loop_runner =
587 new content::MessageLoopRunner;
588 quit_closure_ = message_loop_runner->QuitClosure();
589 history_service_->QueryURL(
590 url,
591 true,
592 base::Bind(&RemoveHistoryTester::SaveResultAndQuit,
593 base::Unretained(this)),
594 &tracker_);
595 message_loop_runner->Run();
596 return query_url_success_;
597 }
598
599 void AddHistory(const GURL& url, base::Time time) {
600 history_service_->AddPage(url, time, nullptr, 0, GURL(),
601 history::RedirectList(), ui::PAGE_TRANSITION_LINK,
602 history::SOURCE_BROWSED, false);
603 }
604
605 private:
606 // Callback for HistoryService::QueryURL.
607 void SaveResultAndQuit(bool success,
608 const history::URLRow&,
609 const history::VisitVector&) {
610 query_url_success_ = success;
611 quit_closure_.Run();
612 }
613
614 // For History requests.
615 base::CancelableTaskTracker tracker_;
616 bool query_url_success_ = false;
617 base::Closure quit_closure_;
618
619 // TestingProfile owns the history service; we shouldn't delete it.
620 history::HistoryService* history_service_ = nullptr;
621
622 DISALLOW_COPY_AND_ASSIGN(RemoveHistoryTester);
623 };
624
625 class RemoveFaviconTester {
626 public:
627 RemoveFaviconTester() {}
628
629 bool Init(TestingProfile* profile) WARN_UNUSED_RESULT {
630 // Create the history service if it has not been created yet.
631 history_service_ = HistoryServiceFactory::GetForProfile(
632 profile, ServiceAccessType::EXPLICIT_ACCESS);
633 if (!history_service_) {
634 if (!profile->CreateHistoryService(true, false))
635 return false;
636 history_service_ = HistoryServiceFactory::GetForProfile(
637 profile, ServiceAccessType::EXPLICIT_ACCESS);
638 }
639
640 profile->CreateFaviconService();
641 favicon_service_ = FaviconServiceFactory::GetForProfile(
642 profile, ServiceAccessType::EXPLICIT_ACCESS);
643 return true;
644 }
645
646 // Returns true if there is a favicon stored for |page_url| in the favicon
647 // database.
648 bool HasFaviconForPageURL(const GURL& page_url) {
649 RequestFaviconSyncForPageURL(page_url);
650 return got_favicon_;
651 }
652
653 // Returns true if:
654 // - There is a favicon stored for |page_url| in the favicon database.
655 // - The stored favicon is expired.
656 bool HasExpiredFaviconForPageURL(const GURL& page_url) {
657 RequestFaviconSyncForPageURL(page_url);
658 return got_expired_favicon_;
659 }
660
661 // Adds a visit to history and stores an arbitrary favicon bitmap for
662 // |page_url|.
663 void VisitAndAddFavicon(const GURL& page_url) {
664 history_service_->AddPage(page_url, base::Time::Now(), nullptr, 0, GURL(),
665 history::RedirectList(), ui::PAGE_TRANSITION_LINK,
666 history::SOURCE_BROWSED, false);
667
668 SkBitmap bitmap;
669 bitmap.allocN32Pixels(gfx::kFaviconSize, gfx::kFaviconSize);
670 bitmap.eraseColor(SK_ColorBLUE);
671 favicon_service_->SetFavicons(page_url, page_url, favicon_base::FAVICON,
672 gfx::Image::CreateFrom1xBitmap(bitmap));
673 }
674
675 private:
676 // Synchronously requests the favicon for |page_url| from the favicon
677 // database.
678 void RequestFaviconSyncForPageURL(const GURL& page_url) {
679 base::RunLoop run_loop;
680 quit_closure_ = run_loop.QuitClosure();
681 favicon_service_->GetRawFaviconForPageURL(
682 page_url,
683 favicon_base::FAVICON,
684 gfx::kFaviconSize,
685 base::Bind(&RemoveFaviconTester::SaveResultAndQuit,
686 base::Unretained(this)),
687 &tracker_);
688 run_loop.Run();
689 }
690
691 // Callback for HistoryService::QueryURL.
692 void SaveResultAndQuit(const favicon_base::FaviconRawBitmapResult& result) {
693 got_favicon_ = result.is_valid();
694 got_expired_favicon_ = result.is_valid() && result.expired;
695 quit_closure_.Run();
696 }
697
698 // For favicon requests.
699 base::CancelableTaskTracker tracker_;
700 bool got_favicon_ = false;
701 bool got_expired_favicon_ = false;
702 base::Closure quit_closure_;
703
704 // Owned by TestingProfile.
705 history::HistoryService* history_service_ = nullptr;
706 favicon::FaviconService* favicon_service_ = nullptr;
707
708 DISALLOW_COPY_AND_ASSIGN(RemoveFaviconTester);
709 };
710
711 class RemoveAutofillTester : public autofill::PersonalDataManagerObserver {
712 public:
713 explicit RemoveAutofillTester(TestingProfile* profile)
714 : personal_data_manager_(
715 autofill::PersonalDataManagerFactory::GetForProfile(profile)) {
716 autofill::test::DisableSystemServices(profile->GetPrefs());
717 personal_data_manager_->AddObserver(this);
718 }
719
720 ~RemoveAutofillTester() override {
721 personal_data_manager_->RemoveObserver(this);
722 autofill::test::ReenableSystemServices();
723 }
724
725 // Returns true if there are autofill profiles.
726 bool HasProfile() {
727 return !personal_data_manager_->GetProfiles().empty() &&
728 !personal_data_manager_->GetCreditCards().empty();
729 }
730
731 bool HasOrigin(const std::string& origin) {
732 const std::vector<autofill::AutofillProfile*>& profiles =
733 personal_data_manager_->GetProfiles();
734 for (const autofill::AutofillProfile* profile : profiles) {
735 if (profile->origin() == origin)
736 return true;
737 }
738
739 const std::vector<autofill::CreditCard*>& credit_cards =
740 personal_data_manager_->GetCreditCards();
741 for (const autofill::CreditCard* credit_card : credit_cards) {
742 if (credit_card->origin() == origin)
743 return true;
744 }
745
746 return false;
747 }
748
749 // Add two profiles and two credit cards to the database. In each pair, one
750 // entry has a web origin and the other has a Chrome origin.
751 void AddProfilesAndCards() {
752 std::vector<autofill::AutofillProfile> profiles;
753 autofill::AutofillProfile profile;
754 profile.set_guid(base::GenerateGUID());
755 profile.set_origin(kWebOrigin);
756 profile.SetRawInfo(autofill::NAME_FIRST, base::ASCIIToUTF16("Bob"));
757 profile.SetRawInfo(autofill::NAME_LAST, base::ASCIIToUTF16("Smith"));
758 profile.SetRawInfo(autofill::ADDRESS_HOME_ZIP, base::ASCIIToUTF16("94043"));
759 profile.SetRawInfo(autofill::EMAIL_ADDRESS,
760 base::ASCIIToUTF16("sue@example.com"));
761 profile.SetRawInfo(autofill::COMPANY_NAME, base::ASCIIToUTF16("Company X"));
762 profiles.push_back(profile);
763
764 profile.set_guid(base::GenerateGUID());
765 profile.set_origin(autofill::kSettingsOrigin);
766 profiles.push_back(profile);
767
768 personal_data_manager_->SetProfiles(&profiles);
769 base::RunLoop().Run();
770
771 std::vector<autofill::CreditCard> cards;
772 autofill::CreditCard card;
773 card.set_guid(base::GenerateGUID());
774 card.set_origin(kWebOrigin);
775 card.SetRawInfo(autofill::CREDIT_CARD_NUMBER,
776 base::ASCIIToUTF16("1234-5678-9012-3456"));
777 cards.push_back(card);
778
779 card.set_guid(base::GenerateGUID());
780 card.set_origin(autofill::kSettingsOrigin);
781 cards.push_back(card);
782
783 personal_data_manager_->SetCreditCards(&cards);
784 base::RunLoop().Run();
785 }
786
787 private:
788 void OnPersonalDataChanged() override {
789 base::MessageLoop::current()->QuitWhenIdle();
790 }
791
792 autofill::PersonalDataManager* personal_data_manager_;
793 DISALLOW_COPY_AND_ASSIGN(RemoveAutofillTester);
794 };
795
796 class RemoveLocalStorageTester {
797 public:
798 explicit RemoveLocalStorageTester(TestingProfile* profile)
799 : profile_(profile) {
800 dom_storage_context_ =
801 content::BrowserContext::GetDefaultStoragePartition(profile)->
802 GetDOMStorageContext();
803 }
804
805 // Returns true, if the given origin URL exists.
806 bool DOMStorageExistsForOrigin(const GURL& origin) {
807 scoped_refptr<content::MessageLoopRunner> message_loop_runner =
808 new content::MessageLoopRunner;
809 quit_closure_ = message_loop_runner->QuitClosure();
810 GetLocalStorageUsage();
811 message_loop_runner->Run();
812 for (size_t i = 0; i < infos_.size(); ++i) {
813 if (origin == infos_[i].origin)
814 return true;
815 }
816 return false;
817 }
818
819 void AddDOMStorageTestData() {
820 // Note: This test depends on details of how the dom_storage library
821 // stores data in the host file system.
822 base::FilePath storage_path =
823 profile_->GetPath().AppendASCII("Local Storage");
824 base::CreateDirectory(storage_path);
825
826 // Write some files.
827 base::WriteFile(storage_path.Append(kDomStorageOrigin1), nullptr, 0);
828 base::WriteFile(storage_path.Append(kDomStorageOrigin2), nullptr, 0);
829 base::WriteFile(storage_path.Append(kDomStorageOrigin3), nullptr, 0);
830 base::WriteFile(storage_path.Append(kDomStorageExt), nullptr, 0);
831
832 // Tweak their dates.
833 base::Time now = base::Time::Now();
834 base::TouchFile(storage_path.Append(kDomStorageOrigin1), now, now);
835
836 base::Time one_day_ago = now - base::TimeDelta::FromDays(1);
837 base::TouchFile(storage_path.Append(kDomStorageOrigin2),
838 one_day_ago, one_day_ago);
839
840 base::Time sixty_days_ago = now - base::TimeDelta::FromDays(60);
841 base::TouchFile(storage_path.Append(kDomStorageOrigin3),
842 sixty_days_ago, sixty_days_ago);
843
844 base::TouchFile(storage_path.Append(kDomStorageExt), now, now);
845 }
846
847 private:
848 void GetLocalStorageUsage() {
849 dom_storage_context_->GetLocalStorageUsage(
850 base::Bind(&RemoveLocalStorageTester::OnGotLocalStorageUsage,
851 base::Unretained(this)));
852 }
853 void OnGotLocalStorageUsage(
854 const std::vector<content::LocalStorageUsageInfo>& infos) {
855 infos_ = infos;
856 quit_closure_.Run();
857 }
858
859 // We don't own these pointers.
860 TestingProfile* profile_;
861 content::DOMStorageContext* dom_storage_context_ = nullptr;
862
863 std::vector<content::LocalStorageUsageInfo> infos_;
864 base::Closure quit_closure_;
865
866 DISALLOW_COPY_AND_ASSIGN(RemoveLocalStorageTester);
867 };
868
869 class MockDomainReliabilityService : public DomainReliabilityService {
870 public:
871 MockDomainReliabilityService() {}
872
873 ~MockDomainReliabilityService() override {}
874
875 std::unique_ptr<DomainReliabilityMonitor> CreateMonitor(
876 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner)
877 override {
878 NOTREACHED();
879 return std::unique_ptr<DomainReliabilityMonitor>();
880 }
881
882 void ClearBrowsingData(
883 DomainReliabilityClearMode clear_mode,
884 const base::Callback<bool(const GURL&)>& origin_filter,
885 const base::Closure& callback) override {
886 clear_count_++;
887 last_clear_mode_ = clear_mode;
888 last_filter_ = origin_filter;
889 callback.Run();
890 }
891
892 void GetWebUIData(const base::Callback<void(std::unique_ptr<base::Value>)>&
893 callback) const override {
894 NOTREACHED();
895 }
896
897 void SetDiscardUploadsForTesting(bool discard_uploads) override {
898 NOTREACHED();
899 }
900
901 void AddContextForTesting(
902 std::unique_ptr<const domain_reliability::DomainReliabilityConfig> config)
903 override {
904 NOTREACHED();
905 }
906
907 void ForceUploadsForTesting() override { NOTREACHED(); }
908
909 int clear_count() const { return clear_count_; }
910
911 DomainReliabilityClearMode last_clear_mode() const {
912 return last_clear_mode_;
913 }
914
915 const base::Callback<bool(const GURL&)>& last_filter() const {
916 return last_filter_;
917 }
918
919 private:
920 unsigned clear_count_ = 0;
921 DomainReliabilityClearMode last_clear_mode_;
922 base::Callback<bool(const GURL&)> last_filter_;
923 };
924
925 struct TestingDomainReliabilityServiceFactoryUserData
926 : public base::SupportsUserData::Data {
927 TestingDomainReliabilityServiceFactoryUserData(
928 content::BrowserContext* context,
929 MockDomainReliabilityService* service)
930 : context(context),
931 service(service),
932 attached(false) {}
933 ~TestingDomainReliabilityServiceFactoryUserData() override {}
934
935 content::BrowserContext* const context;
936 MockDomainReliabilityService* const service;
937 bool attached;
938
939 static const void* kKey;
940 };
941
942 // static
943 const void* TestingDomainReliabilityServiceFactoryUserData::kKey =
944 &TestingDomainReliabilityServiceFactoryUserData::kKey;
945
946 std::unique_ptr<KeyedService> TestingDomainReliabilityServiceFactoryFunction(
947 content::BrowserContext* context) {
948 const void* kKey = TestingDomainReliabilityServiceFactoryUserData::kKey;
949
950 TestingDomainReliabilityServiceFactoryUserData* data =
951 static_cast<TestingDomainReliabilityServiceFactoryUserData*>(
952 context->GetUserData(kKey));
953 EXPECT_TRUE(data);
954 EXPECT_EQ(data->context, context);
955 EXPECT_FALSE(data->attached);
956
957 data->attached = true;
958 return base::WrapUnique(data->service);
959 }
960
961 class ClearDomainReliabilityTester {
962 public:
963 explicit ClearDomainReliabilityTester(TestingProfile* profile) :
964 profile_(profile),
965 mock_service_(new MockDomainReliabilityService()) {
966 AttachService();
967 }
968
969 unsigned clear_count() const { return mock_service_->clear_count(); }
970
971 DomainReliabilityClearMode last_clear_mode() const {
972 return mock_service_->last_clear_mode();
973 }
974
975 const base::Callback<bool(const GURL&)>& last_filter() const {
976 return mock_service_->last_filter();
977 }
978
979 private:
980 void AttachService() {
981 const void* kKey = TestingDomainReliabilityServiceFactoryUserData::kKey;
982
983 // Attach kludgey UserData struct to profile.
984 TestingDomainReliabilityServiceFactoryUserData* data =
985 new TestingDomainReliabilityServiceFactoryUserData(profile_,
986 mock_service_);
987 EXPECT_FALSE(profile_->GetUserData(kKey));
988 profile_->SetUserData(kKey, data);
989
990 // Set and use factory that will attach service stuffed in kludgey struct.
991 DomainReliabilityServiceFactory::GetInstance()->SetTestingFactoryAndUse(
992 profile_,
993 &TestingDomainReliabilityServiceFactoryFunction);
994
995 // Verify and detach kludgey struct.
996 EXPECT_EQ(data, profile_->GetUserData(kKey));
997 EXPECT_TRUE(data->attached);
998 profile_->RemoveUserData(kKey);
999 }
1000
1001 TestingProfile* profile_;
1002 MockDomainReliabilityService* mock_service_;
1003 };
1004
1005 class RemoveDownloadsTester {
1006 public:
1007 explicit RemoveDownloadsTester(TestingProfile* testing_profile)
1008 : download_manager_(new content::MockDownloadManager()),
1009 chrome_download_manager_delegate_(testing_profile) {
1010 content::BrowserContext::SetDownloadManagerForTesting(testing_profile,
1011 download_manager_);
1012 EXPECT_EQ(download_manager_,
1013 content::BrowserContext::GetDownloadManager(testing_profile));
1014
1015 EXPECT_CALL(*download_manager_, GetDelegate())
1016 .WillOnce(Return(&chrome_download_manager_delegate_));
1017 EXPECT_CALL(*download_manager_, Shutdown());
1018 }
1019
1020 ~RemoveDownloadsTester() { chrome_download_manager_delegate_.Shutdown(); }
1021
1022 content::MockDownloadManager* download_manager() { return download_manager_; }
1023
1024 private:
1025 content::MockDownloadManager* download_manager_;
1026 ChromeDownloadManagerDelegate chrome_download_manager_delegate_;
1027
1028 DISALLOW_COPY_AND_ASSIGN(RemoveDownloadsTester);
1029 };
1030
1031 class RemovePasswordsTester {
1032 public:
1033 explicit RemovePasswordsTester(TestingProfile* testing_profile) {
1034 PasswordStoreFactory::GetInstance()->SetTestingFactoryAndUse(
1035 testing_profile,
1036 password_manager::BuildPasswordStore<
1037 content::BrowserContext,
1038 testing::NiceMock<password_manager::MockPasswordStore>>);
1039
1040 store_ = static_cast<password_manager::MockPasswordStore*>(
1041 PasswordStoreFactory::GetInstance()
1042 ->GetForProfile(testing_profile, ServiceAccessType::EXPLICIT_ACCESS)
1043 .get());
1044
1045 OSCryptMocker::SetUpWithSingleton();
1046 }
1047
1048 ~RemovePasswordsTester() { OSCryptMocker::TearDown(); }
1049
1050 password_manager::MockPasswordStore* store() { return store_; }
1051
1052 private:
1053 password_manager::MockPasswordStore* store_;
1054
1055 DISALLOW_COPY_AND_ASSIGN(RemovePasswordsTester);
1056 };
1057
1058 class RemovePermissionPromptCountsTest {
1059 public:
1060 explicit RemovePermissionPromptCountsTest(TestingProfile* profile)
1061 : profile_(profile) {}
1062
1063 int GetDismissCount(const GURL& url, content::PermissionType permission) {
1064 return PermissionDecisionAutoBlocker::GetDismissCount(
1065 url, permission, profile_);
1066 }
1067
1068 int GetIgnoreCount(const GURL& url, content::PermissionType permission) {
1069 return PermissionDecisionAutoBlocker::GetIgnoreCount(
1070 url, permission, profile_);
1071 }
1072
1073 int RecordIgnore(const GURL& url, content::PermissionType permission) {
1074 return PermissionDecisionAutoBlocker::RecordIgnore(url, permission,
1075 profile_);
1076 }
1077
1078 bool ShouldChangeDismissalToBlock(const GURL& url,
1079 content::PermissionType permission) {
1080 return PermissionDecisionAutoBlocker::ShouldChangeDismissalToBlock(
1081 url, permission, profile_);
1082 }
1083
1084 private:
1085 TestingProfile* profile_;
1086
1087 DISALLOW_COPY_AND_ASSIGN(RemovePermissionPromptCountsTest);
1088 };
1089
1090 #if BUILDFLAG(ENABLE_PLUGINS)
1091 // A small modification to MockBrowsingDataFlashLSOHelper so that it responds
1092 // immediately and does not wait for the Notify() call. Otherwise it would
1093 // deadlock BrowsingDataRemoverImpl::RemoveImpl.
1094 class TestBrowsingDataFlashLSOHelper : public MockBrowsingDataFlashLSOHelper {
1095 public:
1096 explicit TestBrowsingDataFlashLSOHelper(TestingProfile* profile)
1097 : MockBrowsingDataFlashLSOHelper(profile) {}
1098
1099 void StartFetching(const GetSitesWithFlashDataCallback& callback) override {
1100 MockBrowsingDataFlashLSOHelper::StartFetching(callback);
1101 Notify();
1102 }
1103
1104 private:
1105 ~TestBrowsingDataFlashLSOHelper() override {}
1106
1107 DISALLOW_COPY_AND_ASSIGN(TestBrowsingDataFlashLSOHelper);
1108 };
1109
1110 class RemovePluginDataTester {
1111 public:
1112 explicit RemovePluginDataTester(TestingProfile* profile)
1113 : helper_(new TestBrowsingDataFlashLSOHelper(profile)) {
1114 static_cast<ChromeBrowsingDataRemoverDelegate*>(
1115 BrowsingDataRemoverFactory::GetForBrowserContext(profile)
1116 ->GetEmbedderDelegate())->OverrideFlashLSOHelperForTesting(helper_);
1117 }
1118
1119 void AddDomain(const std::string& domain) {
1120 helper_->AddFlashLSODomain(domain);
1121 }
1122
1123 const std::vector<std::string>& GetDomains() {
1124 // TestBrowsingDataFlashLSOHelper is synchronous, so we can immediately
1125 // return the fetched domains.
1126 helper_->StartFetching(
1127 base::Bind(&RemovePluginDataTester::OnSitesWithFlashDataFetched,
1128 base::Unretained(this)));
1129 return domains_;
1130 }
1131
1132 private:
1133 void OnSitesWithFlashDataFetched(const std::vector<std::string>& sites) {
1134 domains_ = sites;
1135 }
1136
1137 std::vector<std::string> domains_;
1138 scoped_refptr<TestBrowsingDataFlashLSOHelper> helper_;
1139
1140 DISALLOW_COPY_AND_ASSIGN(RemovePluginDataTester);
1141 };
1142 #endif
1143
1144 // Test Class ----------------------------------------------------------------
1145
1146 class BrowsingDataRemoverTest : public testing::Test {
1147 public:
1148 BrowsingDataRemoverTest()
1149 : profile_(new TestingProfile()),
1150 clear_domain_reliability_tester_(GetProfile()) {
1151 remover_ = static_cast<BrowsingDataRemoverImpl*>(
1152 BrowsingDataRemoverFactory::GetForBrowserContext(profile_.get()));
1153
1154 #if defined(OS_ANDROID)
1155 static_cast<ChromeBrowsingDataRemoverDelegate*>(
1156 remover_->GetEmbedderDelegate())->OverrideWebappRegistryForTesting(
1157 base::WrapUnique<WebappRegistry>(new TestWebappRegistry()));
1158 #endif
1159 }
1160
1161 ~BrowsingDataRemoverTest() override {}
1162
1163 void TearDown() override {
1164 #if BUILDFLAG(ENABLE_EXTENSIONS)
1165 mock_policy_ = nullptr;
1166 #endif
1167
1168 // TestingProfile contains a DOMStorageContext. BrowserContext's destructor
1169 // posts a message to the WEBKIT thread to delete some of its member
1170 // variables. We need to ensure that the profile is destroyed, and that
1171 // the message loop is cleared out, before destroying the threads and loop.
1172 // Otherwise we leak memory.
1173 profile_.reset();
1174 base::RunLoop().RunUntilIdle();
1175
1176 TestingBrowserProcess::GetGlobal()->SetLocalState(nullptr);
1177 }
1178
1179 void BlockUntilBrowsingDataRemoved(const base::Time& delete_begin,
1180 const base::Time& delete_end,
1181 int remove_mask,
1182 bool include_protected_origins) {
1183 TestStoragePartition storage_partition;
1184 remover_->OverrideStoragePartitionForTesting(&storage_partition);
1185
1186 int origin_type_mask = BrowsingDataHelper::UNPROTECTED_WEB;
1187 if (include_protected_origins)
1188 origin_type_mask |= BrowsingDataHelper::PROTECTED_WEB;
1189
1190 BrowsingDataRemoverCompletionObserver completion_observer(remover_);
1191 remover_->RemoveAndReply(
1192 delete_begin, delete_end, remove_mask, origin_type_mask,
1193 &completion_observer);
1194 completion_observer.BlockUntilCompletion();
1195
1196 // Save so we can verify later.
1197 storage_partition_removal_data_ =
1198 storage_partition.GetStoragePartitionRemovalData();
1199 }
1200
1201 void BlockUntilOriginDataRemoved(
1202 const base::Time& delete_begin,
1203 const base::Time& delete_end,
1204 int remove_mask,
1205 const BrowsingDataFilterBuilder& filter_builder) {
1206 TestStoragePartition storage_partition;
1207 remover_->OverrideStoragePartitionForTesting(&storage_partition);
1208
1209 BrowsingDataRemoverCompletionInhibitor completion_inhibitor;
1210 remover_->RemoveImpl(delete_begin, delete_end, remove_mask, filter_builder,
1211 BrowsingDataHelper::UNPROTECTED_WEB);
1212 completion_inhibitor.BlockUntilNearCompletion();
1213 completion_inhibitor.ContinueToCompletion();
1214
1215 // Save so we can verify later.
1216 storage_partition_removal_data_ =
1217 storage_partition.GetStoragePartitionRemovalData();
1218 }
1219
1220 TestingProfile* GetProfile() {
1221 return profile_.get();
1222 }
1223
1224 void DestroyProfile() { profile_.reset(); }
1225
1226 const base::Time& GetBeginTime() {
1227 return remover_->GetLastUsedBeginTime();
1228 }
1229
1230 int GetRemovalMask() {
1231 return remover_->GetLastUsedRemovalMask();
1232 }
1233
1234 int GetOriginTypeMask() {
1235 return remover_->GetLastUsedOriginTypeMask();
1236 }
1237
1238 StoragePartitionRemovalData GetStoragePartitionRemovalData() {
1239 return storage_partition_removal_data_;
1240 }
1241
1242 MockExtensionSpecialStoragePolicy* CreateMockPolicy() {
1243 #if BUILDFLAG(ENABLE_EXTENSIONS)
1244 mock_policy_ = new MockExtensionSpecialStoragePolicy;
1245 return mock_policy_.get();
1246 #else
1247 NOTREACHED();
1248 return nullptr;
1249 #endif
1250 }
1251
1252 storage::SpecialStoragePolicy* mock_policy() {
1253 #if BUILDFLAG(ENABLE_EXTENSIONS)
1254 return mock_policy_.get();
1255 #else
1256 return nullptr;
1257 #endif
1258 }
1259
1260 // If |kOrigin1| is protected when extensions are enabled, the expected
1261 // result for tests where the OriginMatcherFunction result is variable.
1262 bool ShouldRemoveForProtectedOriginOne() const {
1263 #if BUILDFLAG(ENABLE_EXTENSIONS)
1264 return false;
1265 #else
1266 return true;
1267 #endif
1268 }
1269
1270 const ClearDomainReliabilityTester& clear_domain_reliability_tester() {
1271 return clear_domain_reliability_tester_;
1272 }
1273
1274 private:
1275 // Cached pointer to BrowsingDataRemoverImpl for access to testing methods.
1276 BrowsingDataRemoverImpl* remover_;
1277
1278 content::TestBrowserThreadBundle thread_bundle_;
1279 std::unique_ptr<TestingProfile> profile_;
1280
1281 StoragePartitionRemovalData storage_partition_removal_data_;
1282
1283 #if BUILDFLAG(ENABLE_EXTENSIONS)
1284 scoped_refptr<MockExtensionSpecialStoragePolicy> mock_policy_;
1285 #endif
1286
1287 // Needed to mock out DomainReliabilityService, even for unrelated tests.
1288 ClearDomainReliabilityTester clear_domain_reliability_tester_;
1289
1290 DISALLOW_COPY_AND_ASSIGN(BrowsingDataRemoverTest);
1291 };
1292
1293 // Tests ---------------------------------------------------------------------
1294
1295 TEST_F(BrowsingDataRemoverTest, RemoveCookieForever) {
1296 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1297 BrowsingDataRemover::REMOVE_COOKIES, false);
1298
1299 EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
1300 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1301
1302 // Verify that storage partition was instructed to remove the cookies.
1303 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1304 EXPECT_EQ(removal_data.remove_mask,
1305 StoragePartition::REMOVE_DATA_MASK_COOKIES);
1306 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1307 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1308 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1309 }
1310
1311 TEST_F(BrowsingDataRemoverTest, RemoveCookieLastHour) {
1312 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
1313 BrowsingDataRemover::REMOVE_COOKIES, false);
1314
1315 EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
1316 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1317
1318 // Verify that storage partition was instructed to remove the cookies.
1319 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1320 EXPECT_EQ(removal_data.remove_mask,
1321 StoragePartition::REMOVE_DATA_MASK_COOKIES);
1322 // Removing with time period other than all time should not clear
1323 // persistent storage data.
1324 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1325 ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT);
1326 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1327 }
1328
1329 TEST_F(BrowsingDataRemoverTest, RemoveCookiesDomainBlacklist) {
1330 RegistrableDomainFilterBuilder filter(
1331 RegistrableDomainFilterBuilder::BLACKLIST);
1332 filter.AddRegisterableDomain(kTestRegisterableDomain1);
1333 filter.AddRegisterableDomain(kTestRegisterableDomain3);
1334 BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
1335 BrowsingDataRemover::REMOVE_COOKIES, filter);
1336
1337 EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
1338 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1339
1340 // Verify that storage partition was instructed to remove the cookies.
1341 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1342 EXPECT_EQ(removal_data.remove_mask,
1343 StoragePartition::REMOVE_DATA_MASK_COOKIES);
1344 // Removing with time period other than all time should not clear
1345 // persistent storage data.
1346 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1347 ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT);
1348 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1349 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1350 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1351 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1352 // Even though it's a different origin, it's the same domain.
1353 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin4, mock_policy()));
1354
1355 EXPECT_FALSE(removal_data.cookie_matcher.Run(CreateCookieWithHost(kOrigin1)));
1356 EXPECT_TRUE(removal_data.cookie_matcher.Run(CreateCookieWithHost(kOrigin2)));
1357 EXPECT_FALSE(removal_data.cookie_matcher.Run(CreateCookieWithHost(kOrigin3)));
1358 // This is false, because this is the same domain as 3, just with a different
1359 // scheme.
1360 EXPECT_FALSE(removal_data.cookie_matcher.Run(CreateCookieWithHost(kOrigin4)));
1361 }
1362
1363 TEST_F(BrowsingDataRemoverTest, RemoveSafeBrowsingCookieForever) {
1364 RemoveSafeBrowsingCookieTester tester;
1365
1366 tester.AddCookie();
1367 ASSERT_TRUE(tester.ContainsCookie());
1368
1369 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1370 BrowsingDataRemover::REMOVE_COOKIES, false);
1371
1372 EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
1373 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1374 EXPECT_FALSE(tester.ContainsCookie());
1375 }
1376
1377 TEST_F(BrowsingDataRemoverTest, RemoveSafeBrowsingCookieLastHour) {
1378 RemoveSafeBrowsingCookieTester tester;
1379
1380 tester.AddCookie();
1381 ASSERT_TRUE(tester.ContainsCookie());
1382
1383 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
1384 BrowsingDataRemover::REMOVE_COOKIES, false);
1385
1386 EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
1387 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1388 // Removing with time period other than all time should not clear safe
1389 // browsing cookies.
1390 EXPECT_TRUE(tester.ContainsCookie());
1391 }
1392
1393 TEST_F(BrowsingDataRemoverTest, RemoveSafeBrowsingCookieForeverWithPredicate) {
1394 RemoveSafeBrowsingCookieTester tester;
1395
1396 tester.AddCookie();
1397 ASSERT_TRUE(tester.ContainsCookie());
1398 RegistrableDomainFilterBuilder filter(
1399 RegistrableDomainFilterBuilder::BLACKLIST);
1400 filter.AddRegisterableDomain(kTestRegisterableDomain1);
1401 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
1402 BrowsingDataRemover::REMOVE_COOKIES, filter);
1403
1404 EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
1405 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1406 EXPECT_TRUE(tester.ContainsCookie());
1407
1408 RegistrableDomainFilterBuilder filter2(
1409 RegistrableDomainFilterBuilder::WHITELIST);
1410 filter2.AddRegisterableDomain(kTestRegisterableDomain1);
1411 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
1412 BrowsingDataRemover::REMOVE_COOKIES, filter2);
1413 EXPECT_FALSE(tester.ContainsCookie());
1414 }
1415
1416 TEST_F(BrowsingDataRemoverTest, RemoveChannelIDForever) {
1417 RemoveChannelIDTester tester(GetProfile());
1418
1419 tester.AddChannelID(kTestOrigin1);
1420 EXPECT_EQ(0, tester.ssl_config_changed_count());
1421 EXPECT_EQ(1, tester.ChannelIDCount());
1422
1423 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1424 BrowsingDataRemover::REMOVE_CHANNEL_IDS, false);
1425
1426 EXPECT_EQ(BrowsingDataRemover::REMOVE_CHANNEL_IDS, GetRemovalMask());
1427 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1428 EXPECT_EQ(1, tester.ssl_config_changed_count());
1429 EXPECT_EQ(0, tester.ChannelIDCount());
1430 }
1431
1432 TEST_F(BrowsingDataRemoverTest, RemoveChannelIDLastHour) {
1433 RemoveChannelIDTester tester(GetProfile());
1434
1435 base::Time now = base::Time::Now();
1436 tester.AddChannelID(kTestOrigin1);
1437 tester.AddChannelIDWithTimes(kTestOrigin2,
1438 now - base::TimeDelta::FromHours(2));
1439 EXPECT_EQ(0, tester.ssl_config_changed_count());
1440 EXPECT_EQ(2, tester.ChannelIDCount());
1441
1442 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
1443 BrowsingDataRemover::REMOVE_CHANNEL_IDS, false);
1444
1445 EXPECT_EQ(BrowsingDataRemover::REMOVE_CHANNEL_IDS, GetRemovalMask());
1446 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1447 EXPECT_EQ(1, tester.ssl_config_changed_count());
1448 ASSERT_EQ(1, tester.ChannelIDCount());
1449 net::ChannelIDStore::ChannelIDList channel_ids;
1450 tester.GetChannelIDList(&channel_ids);
1451 ASSERT_EQ(1U, channel_ids.size());
1452 EXPECT_EQ(kTestOrigin2, channel_ids.front().server_identifier());
1453 }
1454
1455 TEST_F(BrowsingDataRemoverTest, RemoveChannelIDsForServerIdentifiers) {
1456 RemoveChannelIDTester tester(GetProfile());
1457
1458 tester.AddChannelID(kTestRegisterableDomain1);
1459 tester.AddChannelID(kTestRegisterableDomain3);
1460 EXPECT_EQ(2, tester.ChannelIDCount());
1461
1462 RegistrableDomainFilterBuilder filter_builder(
1463 RegistrableDomainFilterBuilder::WHITELIST);
1464 filter_builder.AddRegisterableDomain(kTestRegisterableDomain1);
1465
1466 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
1467 BrowsingDataRemover::REMOVE_CHANNEL_IDS,
1468 filter_builder);
1469
1470 EXPECT_EQ(1, tester.ChannelIDCount());
1471 net::ChannelIDStore::ChannelIDList channel_ids;
1472 tester.GetChannelIDList(&channel_ids);
1473 EXPECT_EQ(kTestRegisterableDomain3, channel_ids.front().server_identifier());
1474 }
1475
1476 TEST_F(BrowsingDataRemoverTest, RemoveUnprotectedLocalStorageForever) {
1477 #if BUILDFLAG(ENABLE_EXTENSIONS)
1478 MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
1479 // Protect kOrigin1.
1480 policy->AddProtected(kOrigin1.GetOrigin());
1481 #endif
1482
1483 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1484 BrowsingDataRemover::REMOVE_LOCAL_STORAGE,
1485 false);
1486
1487 EXPECT_EQ(BrowsingDataRemover::REMOVE_LOCAL_STORAGE, GetRemovalMask());
1488 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1489
1490 // Verify that storage partition was instructed to remove the data correctly.
1491 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1492 EXPECT_EQ(removal_data.remove_mask,
1493 StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE);
1494 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1495 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1496 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1497
1498 // Check origin matcher.
1499 EXPECT_EQ(ShouldRemoveForProtectedOriginOne(),
1500 removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1501 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1502 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1503 EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
1504 }
1505
1506 TEST_F(BrowsingDataRemoverTest, RemoveProtectedLocalStorageForever) {
1507 #if BUILDFLAG(ENABLE_EXTENSIONS)
1508 // Protect kOrigin1.
1509 MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
1510 policy->AddProtected(kOrigin1.GetOrigin());
1511 #endif
1512
1513 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1514 BrowsingDataRemover::REMOVE_LOCAL_STORAGE,
1515 true);
1516
1517 EXPECT_EQ(BrowsingDataRemover::REMOVE_LOCAL_STORAGE, GetRemovalMask());
1518 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB |
1519 BrowsingDataHelper::PROTECTED_WEB, GetOriginTypeMask());
1520
1521 // Verify that storage partition was instructed to remove the data correctly.
1522 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1523 EXPECT_EQ(removal_data.remove_mask,
1524 StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE);
1525 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1526 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1527 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1528
1529 // Check origin matcher all http origin will match since we specified
1530 // both protected and unprotected.
1531 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1532 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1533 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1534 EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
1535 }
1536
1537 TEST_F(BrowsingDataRemoverTest, RemoveLocalStorageForLastWeek) {
1538 #if BUILDFLAG(ENABLE_EXTENSIONS)
1539 CreateMockPolicy();
1540 #endif
1541
1542 BlockUntilBrowsingDataRemoved(
1543 base::Time::Now() - base::TimeDelta::FromDays(7), base::Time::Max(),
1544 BrowsingDataRemover::REMOVE_LOCAL_STORAGE, false);
1545
1546 EXPECT_EQ(BrowsingDataRemover::REMOVE_LOCAL_STORAGE, GetRemovalMask());
1547 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1548
1549 // Verify that storage partition was instructed to remove the data correctly.
1550 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1551 EXPECT_EQ(removal_data.remove_mask,
1552 StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE);
1553 // Persistent storage won't be deleted.
1554 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1555 ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT);
1556 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1557
1558 // Check origin matcher.
1559 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1560 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1561 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1562 EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
1563 }
1564
1565 TEST_F(BrowsingDataRemoverTest, RemoveHistoryForever) {
1566 RemoveHistoryTester tester;
1567 ASSERT_TRUE(tester.Init(GetProfile()));
1568
1569 tester.AddHistory(kOrigin1, base::Time::Now());
1570 ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1571
1572 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1573 BrowsingDataRemover::REMOVE_HISTORY, false);
1574
1575 EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1576 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1577 EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
1578 }
1579
1580 TEST_F(BrowsingDataRemoverTest, RemoveHistoryForLastHour) {
1581 RemoveHistoryTester tester;
1582 ASSERT_TRUE(tester.Init(GetProfile()));
1583
1584 base::Time two_hours_ago = base::Time::Now() - base::TimeDelta::FromHours(2);
1585
1586 tester.AddHistory(kOrigin1, base::Time::Now());
1587 tester.AddHistory(kOrigin2, two_hours_ago);
1588 ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1589 ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
1590
1591 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
1592 BrowsingDataRemover::REMOVE_HISTORY, false);
1593
1594 EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1595 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1596 EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
1597 EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
1598 }
1599
1600 // This should crash (DCHECK) in Debug, but death tests don't work properly
1601 // here.
1602 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
1603 TEST_F(BrowsingDataRemoverTest, RemoveHistoryProhibited) {
1604 RemoveHistoryTester tester;
1605 ASSERT_TRUE(tester.Init(GetProfile()));
1606 PrefService* prefs = GetProfile()->GetPrefs();
1607 prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
1608
1609 base::Time two_hours_ago = base::Time::Now() - base::TimeDelta::FromHours(2);
1610
1611 tester.AddHistory(kOrigin1, base::Time::Now());
1612 tester.AddHistory(kOrigin2, two_hours_ago);
1613 ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1614 ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
1615
1616 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
1617 BrowsingDataRemover::REMOVE_HISTORY, false);
1618 EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1619 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1620
1621 // Nothing should have been deleted.
1622 EXPECT_TRUE(tester.HistoryContainsURL(kOrigin1));
1623 EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
1624 }
1625 #endif
1626
1627 TEST_F(BrowsingDataRemoverTest, RemoveMultipleTypes) {
1628 // Add some history.
1629 RemoveHistoryTester history_tester;
1630 ASSERT_TRUE(history_tester.Init(GetProfile()));
1631 history_tester.AddHistory(kOrigin1, base::Time::Now());
1632 ASSERT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
1633
1634 int removal_mask = BrowsingDataRemover::REMOVE_HISTORY |
1635 BrowsingDataRemover::REMOVE_COOKIES;
1636
1637 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1638 removal_mask, false);
1639
1640 EXPECT_EQ(removal_mask, GetRemovalMask());
1641 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1642 EXPECT_FALSE(history_tester.HistoryContainsURL(kOrigin1));
1643
1644 // The cookie would be deleted throught the StorageParition, check if the
1645 // partition was requested to remove cookie.
1646 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1647 EXPECT_EQ(removal_data.remove_mask,
1648 StoragePartition::REMOVE_DATA_MASK_COOKIES);
1649 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1650 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1651 }
1652
1653 // This should crash (DCHECK) in Debug, but death tests don't work properly
1654 // here.
1655 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
1656 TEST_F(BrowsingDataRemoverTest, RemoveMultipleTypesHistoryProhibited) {
1657 PrefService* prefs = GetProfile()->GetPrefs();
1658 prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
1659
1660 // Add some history.
1661 RemoveHistoryTester history_tester;
1662 ASSERT_TRUE(history_tester.Init(GetProfile()));
1663 history_tester.AddHistory(kOrigin1, base::Time::Now());
1664 ASSERT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
1665
1666 int removal_mask = BrowsingDataRemover::REMOVE_HISTORY |
1667 BrowsingDataRemover::REMOVE_COOKIES;
1668
1669 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
1670 removal_mask, false);
1671 EXPECT_EQ(removal_mask, GetRemovalMask());
1672 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1673
1674 // 1/2. History should remain.
1675 EXPECT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
1676
1677 // 2/2. The cookie(s) would be deleted throught the StorageParition, check if
1678 // the partition was requested to remove cookie.
1679 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1680 EXPECT_EQ(removal_data.remove_mask,
1681 StoragePartition::REMOVE_DATA_MASK_COOKIES);
1682 // Persistent storage won't be deleted, since the time period is not all time.
1683 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1684 ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT);
1685 }
1686 #endif
1687
1688 // Test that clearing history deletes favicons not associated with bookmarks.
1689 TEST_F(BrowsingDataRemoverTest, RemoveFaviconsForever) {
1690 GURL page_url("http://a");
1691
1692 RemoveFaviconTester favicon_tester;
1693 ASSERT_TRUE(favicon_tester.Init(GetProfile()));
1694 favicon_tester.VisitAndAddFavicon(page_url);
1695 ASSERT_TRUE(favicon_tester.HasFaviconForPageURL(page_url));
1696
1697 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1698 BrowsingDataRemover::REMOVE_HISTORY, false);
1699 EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1700 EXPECT_FALSE(favicon_tester.HasFaviconForPageURL(page_url));
1701 }
1702
1703 // Test that a bookmark's favicon is expired and not deleted when clearing
1704 // history. Expiring the favicon causes the bookmark's favicon to be updated
1705 // when the user next visits the bookmarked page. Expiring the bookmark's
1706 // favicon is useful when the bookmark's favicon becomes incorrect (See
1707 // crbug.com/474421 for a sample bug which causes this).
1708 TEST_F(BrowsingDataRemoverTest, ExpireBookmarkFavicons) {
1709 GURL bookmarked_page("http://a");
1710
1711 TestingProfile* profile = GetProfile();
1712 profile->CreateBookmarkModel(true);
1713 bookmarks::BookmarkModel* bookmark_model =
1714 BookmarkModelFactory::GetForBrowserContext(profile);
1715 bookmarks::test::WaitForBookmarkModelToLoad(bookmark_model);
1716 bookmark_model->AddURL(bookmark_model->bookmark_bar_node(), 0,
1717 base::ASCIIToUTF16("a"), bookmarked_page);
1718
1719 RemoveFaviconTester favicon_tester;
1720 ASSERT_TRUE(favicon_tester.Init(GetProfile()));
1721 favicon_tester.VisitAndAddFavicon(bookmarked_page);
1722 ASSERT_TRUE(favicon_tester.HasFaviconForPageURL(bookmarked_page));
1723
1724 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
1725 BrowsingDataRemover::REMOVE_HISTORY, false);
1726 EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1727 EXPECT_TRUE(favicon_tester.HasExpiredFaviconForPageURL(bookmarked_page));
1728 }
1729
1730 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverBoth) {
1731 BlockUntilBrowsingDataRemoved(
1732 base::Time(), base::Time::Max(),
1733 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1734 BrowsingDataRemover::REMOVE_WEBSQL |
1735 BrowsingDataRemover::REMOVE_APPCACHE |
1736 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1737 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1738 BrowsingDataRemover::REMOVE_INDEXEDDB,
1739 false);
1740
1741 EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1742 BrowsingDataRemover::REMOVE_WEBSQL |
1743 BrowsingDataRemover::REMOVE_APPCACHE |
1744 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1745 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1746 BrowsingDataRemover::REMOVE_INDEXEDDB,
1747 GetRemovalMask());
1748 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1749
1750 // Verify storage partition related stuffs.
1751 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1752 EXPECT_EQ(removal_data.remove_mask,
1753 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1754 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1755 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1756 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1757 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
1758 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1759 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1760 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1761 }
1762
1763 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverOnlyTemporary) {
1764 #if BUILDFLAG(ENABLE_EXTENSIONS)
1765 CreateMockPolicy();
1766 #endif
1767
1768 BlockUntilBrowsingDataRemoved(
1769 base::Time(), base::Time::Max(),
1770 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1771 BrowsingDataRemover::REMOVE_WEBSQL |
1772 BrowsingDataRemover::REMOVE_APPCACHE |
1773 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1774 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1775 BrowsingDataRemover::REMOVE_INDEXEDDB,
1776 false);
1777
1778 EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1779 BrowsingDataRemover::REMOVE_WEBSQL |
1780 BrowsingDataRemover::REMOVE_APPCACHE |
1781 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1782 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1783 BrowsingDataRemover::REMOVE_INDEXEDDB,
1784 GetRemovalMask());
1785 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1786
1787 // Verify storage partition related stuffs.
1788 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1789
1790 EXPECT_EQ(removal_data.remove_mask,
1791 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1792 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1793 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1794 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1795 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
1796 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1797 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1798 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1799
1800 // Check that all related origin data would be removed, that is, origin
1801 // matcher would match these origin.
1802 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1803 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1804 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1805 }
1806
1807 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverOnlyPersistent) {
1808 #if BUILDFLAG(ENABLE_EXTENSIONS)
1809 CreateMockPolicy();
1810 #endif
1811
1812 BlockUntilBrowsingDataRemoved(
1813 base::Time(), base::Time::Max(),
1814 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1815 BrowsingDataRemover::REMOVE_WEBSQL |
1816 BrowsingDataRemover::REMOVE_APPCACHE |
1817 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1818 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1819 BrowsingDataRemover::REMOVE_INDEXEDDB,
1820 false);
1821
1822 EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1823 BrowsingDataRemover::REMOVE_WEBSQL |
1824 BrowsingDataRemover::REMOVE_APPCACHE |
1825 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1826 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1827 BrowsingDataRemover::REMOVE_INDEXEDDB,
1828 GetRemovalMask());
1829 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1830
1831 // Verify storage partition related stuffs.
1832 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1833
1834 EXPECT_EQ(removal_data.remove_mask,
1835 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1836 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1837 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1838 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1839 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
1840 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1841 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1842 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1843
1844 // Check that all related origin data would be removed, that is, origin
1845 // matcher would match these origin.
1846 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1847 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1848 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1849 }
1850
1851 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverNeither) {
1852 #if BUILDFLAG(ENABLE_EXTENSIONS)
1853 CreateMockPolicy();
1854 #endif
1855
1856 BlockUntilBrowsingDataRemoved(
1857 base::Time(), base::Time::Max(),
1858 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1859 BrowsingDataRemover::REMOVE_WEBSQL |
1860 BrowsingDataRemover::REMOVE_APPCACHE |
1861 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1862 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1863 BrowsingDataRemover::REMOVE_INDEXEDDB,
1864 false);
1865
1866 EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1867 BrowsingDataRemover::REMOVE_WEBSQL |
1868 BrowsingDataRemover::REMOVE_APPCACHE |
1869 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1870 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1871 BrowsingDataRemover::REMOVE_INDEXEDDB,
1872 GetRemovalMask());
1873 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1874
1875 // Verify storage partition related stuffs.
1876 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1877
1878 EXPECT_EQ(removal_data.remove_mask,
1879 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1880 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1881 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1882 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1883 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
1884 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1885 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1886 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1887
1888 // Check that all related origin data would be removed, that is, origin
1889 // matcher would match these origin.
1890 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1891 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1892 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1893 }
1894
1895 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverSpecificOrigin) {
1896 RegistrableDomainFilterBuilder builder(
1897 RegistrableDomainFilterBuilder::WHITELIST);
1898 builder.AddRegisterableDomain(kTestRegisterableDomain1);
1899 // Remove Origin 1.
1900 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
1901 BrowsingDataRemover::REMOVE_APPCACHE |
1902 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1903 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1904 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1905 BrowsingDataRemover::REMOVE_INDEXEDDB |
1906 BrowsingDataRemover::REMOVE_WEBSQL,
1907 builder);
1908
1909 EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
1910 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1911 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1912 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1913 BrowsingDataRemover::REMOVE_INDEXEDDB |
1914 BrowsingDataRemover::REMOVE_WEBSQL,
1915 GetRemovalMask());
1916 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1917
1918 // Verify storage partition related stuffs.
1919 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1920
1921 EXPECT_EQ(removal_data.remove_mask,
1922 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1923 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1924 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1925 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1926 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
1927 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1928 EXPECT_EQ(removal_data.quota_storage_remove_mask,
1929 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1930 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1931 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1932 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1933 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin4, mock_policy()));
1934 }
1935
1936 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForLastHour) {
1937 BlockUntilBrowsingDataRemoved(
1938 AnHourAgo(), base::Time::Max(),
1939 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1940 BrowsingDataRemover::REMOVE_WEBSQL |
1941 BrowsingDataRemover::REMOVE_APPCACHE |
1942 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1943 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1944 BrowsingDataRemover::REMOVE_INDEXEDDB,
1945 false);
1946
1947 EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1948 BrowsingDataRemover::REMOVE_WEBSQL |
1949 BrowsingDataRemover::REMOVE_APPCACHE |
1950 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1951 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1952 BrowsingDataRemover::REMOVE_INDEXEDDB,
1953 GetRemovalMask());
1954 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1955
1956 // Verify storage partition related stuffs.
1957 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1958
1959 EXPECT_EQ(removal_data.remove_mask,
1960 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1961 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1962 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1963 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1964 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
1965 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1966
1967 // Persistent data would be left out since we are not removing from
1968 // beginning of time.
1969 uint32_t expected_quota_mask =
1970 ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
1971 EXPECT_EQ(removal_data.quota_storage_remove_mask, expected_quota_mask);
1972 // Check removal begin time.
1973 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1974 }
1975
1976 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForLastWeek) {
1977 BlockUntilBrowsingDataRemoved(
1978 base::Time::Now() - base::TimeDelta::FromDays(7), base::Time::Max(),
1979 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1980 BrowsingDataRemover::REMOVE_WEBSQL |
1981 BrowsingDataRemover::REMOVE_APPCACHE |
1982 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1983 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1984 BrowsingDataRemover::REMOVE_INDEXEDDB,
1985 false);
1986
1987 EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1988 BrowsingDataRemover::REMOVE_WEBSQL |
1989 BrowsingDataRemover::REMOVE_APPCACHE |
1990 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1991 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
1992 BrowsingDataRemover::REMOVE_INDEXEDDB,
1993 GetRemovalMask());
1994 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
1995
1996 // Verify storage partition related stuffs.
1997 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1998
1999 EXPECT_EQ(removal_data.remove_mask,
2000 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
2001 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
2002 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
2003 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
2004 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
2005 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
2006
2007 // Persistent data would be left out since we are not removing from
2008 // beginning of time.
2009 uint32_t expected_quota_mask =
2010 ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
2011 EXPECT_EQ(removal_data.quota_storage_remove_mask, expected_quota_mask);
2012 // Check removal begin time.
2013 EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
2014 }
2015
2016 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedUnprotectedOrigins) {
2017 #if BUILDFLAG(ENABLE_EXTENSIONS)
2018 MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
2019 // Protect kOrigin1.
2020 policy->AddProtected(kOrigin1.GetOrigin());
2021 #endif
2022
2023 BlockUntilBrowsingDataRemoved(
2024 base::Time(), base::Time::Max(),
2025 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2026 BrowsingDataRemover::REMOVE_WEBSQL |
2027 BrowsingDataRemover::REMOVE_APPCACHE |
2028 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2029 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2030 BrowsingDataRemover::REMOVE_INDEXEDDB,
2031 false);
2032
2033 EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2034 BrowsingDataRemover::REMOVE_WEBSQL |
2035 BrowsingDataRemover::REMOVE_APPCACHE |
2036 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2037 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2038 BrowsingDataRemover::REMOVE_INDEXEDDB,
2039 GetRemovalMask());
2040 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2041
2042 // Verify storage partition related stuffs.
2043 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
2044
2045 EXPECT_EQ(removal_data.remove_mask,
2046 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
2047 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
2048 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
2049 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
2050 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
2051 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
2052 EXPECT_EQ(removal_data.quota_storage_remove_mask,
2053 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
2054
2055 // Check OriginMatcherFunction.
2056 EXPECT_EQ(ShouldRemoveForProtectedOriginOne(),
2057 removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
2058 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
2059 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
2060 }
2061
2062 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedProtectedSpecificOrigin) {
2063 #if BUILDFLAG(ENABLE_EXTENSIONS)
2064 MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
2065 // Protect kOrigin1.
2066 policy->AddProtected(kOrigin1.GetOrigin());
2067 #endif
2068
2069 RegistrableDomainFilterBuilder builder(
2070 RegistrableDomainFilterBuilder::WHITELIST);
2071 builder.AddRegisterableDomain(kTestRegisterableDomain1);
2072
2073 // Try to remove kOrigin1. Expect failure.
2074 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
2075 BrowsingDataRemover::REMOVE_APPCACHE |
2076 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2077 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2078 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2079 BrowsingDataRemover::REMOVE_INDEXEDDB |
2080 BrowsingDataRemover::REMOVE_WEBSQL,
2081 builder);
2082
2083 EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
2084 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2085 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2086 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2087 BrowsingDataRemover::REMOVE_INDEXEDDB |
2088 BrowsingDataRemover::REMOVE_WEBSQL,
2089 GetRemovalMask());
2090 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2091
2092 // Verify storage partition related stuffs.
2093 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
2094
2095 EXPECT_EQ(removal_data.remove_mask,
2096 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
2097 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
2098 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
2099 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
2100 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
2101 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
2102 EXPECT_EQ(removal_data.quota_storage_remove_mask,
2103 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
2104
2105 // Check OriginMatcherFunction.
2106 EXPECT_EQ(ShouldRemoveForProtectedOriginOne(),
2107 removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
2108 // Since we use the matcher function to validate origins now, this should
2109 // return false for the origins we're not trying to clear.
2110 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
2111 EXPECT_FALSE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
2112 }
2113
2114 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedProtectedOrigins) {
2115 #if BUILDFLAG(ENABLE_EXTENSIONS)
2116 MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
2117 // Protect kOrigin1.
2118 policy->AddProtected(kOrigin1.GetOrigin());
2119 #endif
2120
2121 // Try to remove kOrigin1. Expect success.
2122 BlockUntilBrowsingDataRemoved(
2123 base::Time(), base::Time::Max(),
2124 BrowsingDataRemover::REMOVE_APPCACHE |
2125 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2126 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2127 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2128 BrowsingDataRemover::REMOVE_INDEXEDDB |
2129 BrowsingDataRemover::REMOVE_WEBSQL,
2130 true);
2131
2132 EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
2133 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2134 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2135 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2136 BrowsingDataRemover::REMOVE_INDEXEDDB |
2137 BrowsingDataRemover::REMOVE_WEBSQL,
2138 GetRemovalMask());
2139 EXPECT_EQ(BrowsingDataHelper::PROTECTED_WEB |
2140 BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2141
2142 // Verify storage partition related stuffs.
2143 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
2144
2145 EXPECT_EQ(removal_data.remove_mask,
2146 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
2147 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
2148 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
2149 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
2150 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
2151 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
2152 EXPECT_EQ(removal_data.quota_storage_remove_mask,
2153 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
2154
2155 // Check OriginMatcherFunction, |kOrigin1| would match mask since we
2156 // would have 'protected' specified in origin_type_mask.
2157 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
2158 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
2159 EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
2160 }
2161
2162 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedIgnoreExtensionsAndDevTools) {
2163 #if BUILDFLAG(ENABLE_EXTENSIONS)
2164 CreateMockPolicy();
2165 #endif
2166
2167 BlockUntilBrowsingDataRemoved(
2168 base::Time(), base::Time::Max(),
2169 BrowsingDataRemover::REMOVE_APPCACHE |
2170 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2171 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2172 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2173 BrowsingDataRemover::REMOVE_INDEXEDDB |
2174 BrowsingDataRemover::REMOVE_WEBSQL,
2175 false);
2176
2177 EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
2178 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
2179 BrowsingDataRemover::REMOVE_CACHE_STORAGE |
2180 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
2181 BrowsingDataRemover::REMOVE_INDEXEDDB |
2182 BrowsingDataRemover::REMOVE_WEBSQL,
2183 GetRemovalMask());
2184 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2185
2186 // Verify storage partition related stuffs.
2187 StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
2188
2189 EXPECT_EQ(removal_data.remove_mask,
2190 StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
2191 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
2192 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
2193 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
2194 StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE |
2195 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
2196 EXPECT_EQ(removal_data.quota_storage_remove_mask,
2197 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
2198
2199 // Check that extension and devtools data wouldn't be removed, that is,
2200 // origin matcher would not match these origin.
2201 EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
2202 EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginDevTools, mock_policy()));
2203 }
2204
2205 TEST_F(BrowsingDataRemoverTest, TimeBasedHistoryRemoval) {
2206 RemoveHistoryTester tester;
2207 ASSERT_TRUE(tester.Init(GetProfile()));
2208
2209 base::Time two_hours_ago = base::Time::Now() - base::TimeDelta::FromHours(2);
2210
2211 tester.AddHistory(kOrigin1, base::Time::Now());
2212 tester.AddHistory(kOrigin2, two_hours_ago);
2213 ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
2214 ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
2215
2216 RegistrableDomainFilterBuilder builder(
2217 RegistrableDomainFilterBuilder::BLACKLIST);
2218 BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
2219 BrowsingDataRemover::REMOVE_HISTORY, builder);
2220
2221 EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
2222 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2223 EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
2224 EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
2225 }
2226
2227 // Verify that clearing autofill form data works.
2228 TEST_F(BrowsingDataRemoverTest, AutofillRemovalLastHour) {
2229 GetProfile()->CreateWebDataService();
2230 RemoveAutofillTester tester(GetProfile());
2231
2232 ASSERT_FALSE(tester.HasProfile());
2233 tester.AddProfilesAndCards();
2234 ASSERT_TRUE(tester.HasProfile());
2235
2236 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
2237 BrowsingDataRemover::REMOVE_FORM_DATA, false);
2238
2239 EXPECT_EQ(BrowsingDataRemover::REMOVE_FORM_DATA, GetRemovalMask());
2240 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2241 ASSERT_FALSE(tester.HasProfile());
2242 }
2243
2244 TEST_F(BrowsingDataRemoverTest, AutofillRemovalEverything) {
2245 GetProfile()->CreateWebDataService();
2246 RemoveAutofillTester tester(GetProfile());
2247
2248 ASSERT_FALSE(tester.HasProfile());
2249 tester.AddProfilesAndCards();
2250 ASSERT_TRUE(tester.HasProfile());
2251
2252 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2253 BrowsingDataRemover::REMOVE_FORM_DATA, false);
2254
2255 EXPECT_EQ(BrowsingDataRemover::REMOVE_FORM_DATA, GetRemovalMask());
2256 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2257 ASSERT_FALSE(tester.HasProfile());
2258 }
2259
2260 // Verify that clearing autofill form data works.
2261 TEST_F(BrowsingDataRemoverTest, AutofillOriginsRemovedWithHistory) {
2262 GetProfile()->CreateWebDataService();
2263 RemoveAutofillTester tester(GetProfile());
2264
2265 tester.AddProfilesAndCards();
2266 EXPECT_FALSE(tester.HasOrigin(std::string()));
2267 EXPECT_TRUE(tester.HasOrigin(kWebOrigin));
2268 EXPECT_TRUE(tester.HasOrigin(autofill::kSettingsOrigin));
2269
2270 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
2271 BrowsingDataRemover::REMOVE_HISTORY, false);
2272
2273 EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
2274 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2275 EXPECT_TRUE(tester.HasOrigin(std::string()));
2276 EXPECT_FALSE(tester.HasOrigin(kWebOrigin));
2277 EXPECT_TRUE(tester.HasOrigin(autofill::kSettingsOrigin));
2278 }
2279
2280 class InspectableCompletionObserver
2281 : public BrowsingDataRemoverCompletionObserver {
2282 public:
2283 explicit InspectableCompletionObserver(BrowsingDataRemover* remover)
2284 : BrowsingDataRemoverCompletionObserver(remover) {}
2285 ~InspectableCompletionObserver() override {}
2286
2287 bool called() { return called_; }
2288
2289 protected:
2290 void OnBrowsingDataRemoverDone() override {
2291 BrowsingDataRemoverCompletionObserver::OnBrowsingDataRemoverDone();
2292 called_ = true;
2293 }
2294
2295 private:
2296 bool called_ = false;
2297 };
2298
2299 TEST_F(BrowsingDataRemoverTest, CompletionInhibition) {
2300 // The |completion_inhibitor| on the stack should prevent removal sessions
2301 // from completing until after ContinueToCompletion() is called.
2302 BrowsingDataRemoverCompletionInhibitor completion_inhibitor;
2303
2304 BrowsingDataRemoverImpl* remover = static_cast<BrowsingDataRemoverImpl*>(
2305 BrowsingDataRemoverFactory::GetForBrowserContext(GetProfile()));
2306 InspectableCompletionObserver completion_observer(remover);
2307 remover->RemoveAndReply(base::Time(), base::Time::Max(),
2308 BrowsingDataRemover::REMOVE_HISTORY,
2309 BrowsingDataHelper::UNPROTECTED_WEB,
2310 &completion_observer);
2311
2312 // Process messages until the inhibitor is notified, and then some, to make
2313 // sure we do not complete asynchronously before ContinueToCompletion() is
2314 // called.
2315 completion_inhibitor.BlockUntilNearCompletion();
2316 base::RunLoop().RunUntilIdle();
2317
2318 // Verify that the removal has not yet been completed and the observer has
2319 // not been called.
2320 EXPECT_TRUE(remover->is_removing());
2321 EXPECT_FALSE(completion_observer.called());
2322
2323 // Now run the removal process until completion, and verify that observers are
2324 // now notified, and the notifications is sent out.
2325 completion_inhibitor.ContinueToCompletion();
2326 completion_observer.BlockUntilCompletion();
2327
2328 EXPECT_FALSE(remover->is_removing());
2329 EXPECT_TRUE(completion_observer.called());
2330 }
2331
2332 TEST_F(BrowsingDataRemoverTest, EarlyShutdown) {
2333 BrowsingDataRemoverImpl* remover = static_cast<BrowsingDataRemoverImpl*>(
2334 BrowsingDataRemoverFactory::GetForBrowserContext(GetProfile()));
2335 InspectableCompletionObserver completion_observer(remover);
2336 BrowsingDataRemoverCompletionInhibitor completion_inhibitor;
2337 remover->RemoveAndReply(base::Time(), base::Time::Max(),
2338 BrowsingDataRemover::REMOVE_HISTORY,
2339 BrowsingDataHelper::UNPROTECTED_WEB,
2340 &completion_observer);
2341
2342 completion_inhibitor.BlockUntilNearCompletion();
2343
2344 // Verify that the deletion has not yet been completed and the observer has
2345 // not been called.
2346 EXPECT_TRUE(remover->is_removing());
2347 EXPECT_FALSE(completion_observer.called());
2348
2349 // Destroying the profile should trigger the notification.
2350 DestroyProfile();
2351
2352 EXPECT_TRUE(completion_observer.called());
2353
2354 // Finishing after shutdown shouldn't break anything.
2355 completion_inhibitor.ContinueToCompletion();
2356 completion_observer.BlockUntilCompletion();
2357 }
2358
2359 TEST_F(BrowsingDataRemoverTest, ZeroSuggestCacheClear) {
2360 PrefService* prefs = GetProfile()->GetPrefs();
2361 prefs->SetString(omnibox::kZeroSuggestCachedResults,
2362 "[\"\", [\"foo\", \"bar\"]]");
2363 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2364 BrowsingDataRemover::REMOVE_COOKIES, false);
2365
2366 // Expect the prefs to be cleared when cookies are removed.
2367 EXPECT_TRUE(prefs->GetString(omnibox::kZeroSuggestCachedResults).empty());
2368 EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
2369 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2370 }
2371
2372 #if defined(OS_CHROMEOS)
2373 TEST_F(BrowsingDataRemoverTest, ContentProtectionPlatformKeysRemoval) {
2374 chromeos::ScopedTestDeviceSettingsService test_device_settings_service;
2375 chromeos::ScopedTestCrosSettings test_cros_settings;
2376 chromeos::MockUserManager* mock_user_manager =
2377 new testing::NiceMock<chromeos::MockUserManager>();
2378 mock_user_manager->SetActiveUser(
2379 AccountId::FromUserEmail("test@example.com"));
2380 chromeos::ScopedUserManagerEnabler user_manager_enabler(mock_user_manager);
2381
2382 std::unique_ptr<chromeos::DBusThreadManagerSetter> dbus_setter =
2383 chromeos::DBusThreadManager::GetSetterForTesting();
2384 chromeos::MockCryptohomeClient* cryptohome_client =
2385 new chromeos::MockCryptohomeClient;
2386 dbus_setter->SetCryptohomeClient(
2387 std::unique_ptr<chromeos::CryptohomeClient>(cryptohome_client));
2388
2389 // Expect exactly one call. No calls means no attempt to delete keys and more
2390 // than one call means a significant performance problem.
2391 EXPECT_CALL(*cryptohome_client, TpmAttestationDeleteKeys(_, _, _, _))
2392 .WillOnce(WithArgs<3>(Invoke(FakeDBusCall)));
2393
2394 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2395 BrowsingDataRemover::REMOVE_MEDIA_LICENSES,
2396 false);
2397
2398 chromeos::DBusThreadManager::Shutdown();
2399 }
2400 #endif
2401
2402 TEST_F(BrowsingDataRemoverTest, DomainReliability_Null) {
2403 const ClearDomainReliabilityTester& tester =
2404 clear_domain_reliability_tester();
2405
2406 EXPECT_EQ(0u, tester.clear_count());
2407 }
2408
2409 TEST_F(BrowsingDataRemoverTest, DomainReliability_Beacons) {
2410 const ClearDomainReliabilityTester& tester =
2411 clear_domain_reliability_tester();
2412
2413 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2414 BrowsingDataRemover::REMOVE_HISTORY, false);
2415 EXPECT_EQ(1u, tester.clear_count());
2416 EXPECT_EQ(CLEAR_BEACONS, tester.last_clear_mode());
2417 EXPECT_TRUE(ProbablySameFilters(
2418 BrowsingDataFilterBuilder::BuildNoopFilter(), tester.last_filter()));
2419 }
2420
2421 TEST_F(BrowsingDataRemoverTest, DomainReliability_Beacons_WithFilter) {
2422 const ClearDomainReliabilityTester& tester =
2423 clear_domain_reliability_tester();
2424
2425 RegistrableDomainFilterBuilder builder(
2426 RegistrableDomainFilterBuilder::WHITELIST);
2427 builder.AddRegisterableDomain(kTestRegisterableDomain1);
2428
2429 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
2430 BrowsingDataRemover::REMOVE_HISTORY, builder);
2431 EXPECT_EQ(1u, tester.clear_count());
2432 EXPECT_EQ(CLEAR_BEACONS, tester.last_clear_mode());
2433 EXPECT_TRUE(ProbablySameFilters(
2434 builder.BuildGeneralFilter(), tester.last_filter()));
2435 }
2436
2437 TEST_F(BrowsingDataRemoverTest, DomainReliability_Contexts) {
2438 const ClearDomainReliabilityTester& tester =
2439 clear_domain_reliability_tester();
2440
2441 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2442 BrowsingDataRemover::REMOVE_COOKIES, false);
2443 EXPECT_EQ(1u, tester.clear_count());
2444 EXPECT_EQ(CLEAR_CONTEXTS, tester.last_clear_mode());
2445 EXPECT_TRUE(ProbablySameFilters(
2446 BrowsingDataFilterBuilder::BuildNoopFilter(), tester.last_filter()));
2447 }
2448
2449 TEST_F(BrowsingDataRemoverTest, DomainReliability_Contexts_WithFilter) {
2450 const ClearDomainReliabilityTester& tester =
2451 clear_domain_reliability_tester();
2452
2453 RegistrableDomainFilterBuilder builder(
2454 RegistrableDomainFilterBuilder::WHITELIST);
2455 builder.AddRegisterableDomain(kTestRegisterableDomain1);
2456
2457 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
2458 BrowsingDataRemover::REMOVE_COOKIES, builder);
2459 EXPECT_EQ(1u, tester.clear_count());
2460 EXPECT_EQ(CLEAR_CONTEXTS, tester.last_clear_mode());
2461 EXPECT_TRUE(ProbablySameFilters(
2462 builder.BuildGeneralFilter(), tester.last_filter()));
2463 }
2464
2465 TEST_F(BrowsingDataRemoverTest, DomainReliability_ContextsWin) {
2466 const ClearDomainReliabilityTester& tester =
2467 clear_domain_reliability_tester();
2468
2469 BlockUntilBrowsingDataRemoved(
2470 base::Time(), base::Time::Max(),
2471 BrowsingDataRemover::REMOVE_HISTORY | BrowsingDataRemover::REMOVE_COOKIES,
2472 false);
2473 EXPECT_EQ(1u, tester.clear_count());
2474 EXPECT_EQ(CLEAR_CONTEXTS, tester.last_clear_mode());
2475 }
2476
2477 TEST_F(BrowsingDataRemoverTest, DomainReliability_ProtectedOrigins) {
2478 const ClearDomainReliabilityTester& tester =
2479 clear_domain_reliability_tester();
2480
2481 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2482 BrowsingDataRemover::REMOVE_COOKIES, true);
2483 EXPECT_EQ(1u, tester.clear_count());
2484 EXPECT_EQ(CLEAR_CONTEXTS, tester.last_clear_mode());
2485 }
2486
2487 // TODO(juliatuttle): This isn't actually testing the no-monitor case, since
2488 // BrowsingDataRemoverTest now creates one unconditionally, since it's needed
2489 // for some unrelated test cases. This should be fixed so it tests the no-
2490 // monitor case again.
2491 TEST_F(BrowsingDataRemoverTest, DISABLED_DomainReliability_NoMonitor) {
2492 BlockUntilBrowsingDataRemoved(
2493 base::Time(), base::Time::Max(),
2494 BrowsingDataRemover::REMOVE_HISTORY | BrowsingDataRemover::REMOVE_COOKIES,
2495 false);
2496 }
2497
2498 TEST_F(BrowsingDataRemoverTest, RemoveDownloadsByTimeOnly) {
2499 RemoveDownloadsTester tester(GetProfile());
2500 base::Callback<bool(const GURL&)> filter =
2501 BrowsingDataFilterBuilder::BuildNoopFilter();
2502
2503 EXPECT_CALL(
2504 *tester.download_manager(),
2505 RemoveDownloadsByURLAndTime(ProbablySameFilter(filter), _, _));
2506
2507 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2508 BrowsingDataRemover::REMOVE_DOWNLOADS, false);
2509 }
2510
2511 TEST_F(BrowsingDataRemoverTest, RemoveDownloadsByOrigin) {
2512 RemoveDownloadsTester tester(GetProfile());
2513 RegistrableDomainFilterBuilder builder(
2514 RegistrableDomainFilterBuilder::WHITELIST);
2515 builder.AddRegisterableDomain(kTestRegisterableDomain1);
2516 base::Callback<bool(const GURL&)> filter = builder.BuildGeneralFilter();
2517
2518 EXPECT_CALL(
2519 *tester.download_manager(),
2520 RemoveDownloadsByURLAndTime(ProbablySameFilter(filter), _, _));
2521
2522 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
2523 BrowsingDataRemover::REMOVE_DOWNLOADS, builder);
2524 }
2525
2526 TEST_F(BrowsingDataRemoverTest, RemovePasswordStatistics) {
2527 RemovePasswordsTester tester(GetProfile());
2528 base::Callback<bool(const GURL&)> empty_filter;
2529
2530 EXPECT_CALL(*tester.store(), RemoveStatisticsByOriginAndTimeImpl(
2531 ProbablySameFilter(empty_filter),
2532 base::Time(), base::Time::Max()));
2533 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2534 BrowsingDataRemover::REMOVE_HISTORY, false);
2535 }
2536
2537 TEST_F(BrowsingDataRemoverTest, RemovePasswordStatisticsByOrigin) {
2538 RemovePasswordsTester tester(GetProfile());
2539
2540 RegistrableDomainFilterBuilder builder(
2541 RegistrableDomainFilterBuilder::WHITELIST);
2542 builder.AddRegisterableDomain(kTestRegisterableDomain1);
2543 base::Callback<bool(const GURL&)> filter = builder.BuildGeneralFilter();
2544
2545 EXPECT_CALL(*tester.store(),
2546 RemoveStatisticsByOriginAndTimeImpl(
2547 ProbablySameFilter(filter), base::Time(), base::Time::Max()));
2548 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
2549 BrowsingDataRemover::REMOVE_HISTORY, builder);
2550 }
2551
2552 TEST_F(BrowsingDataRemoverTest, RemovePasswordsByTimeOnly) {
2553 RemovePasswordsTester tester(GetProfile());
2554 base::Callback<bool(const GURL&)> filter =
2555 BrowsingDataFilterBuilder::BuildNoopFilter();
2556
2557 EXPECT_CALL(*tester.store(),
2558 RemoveLoginsByURLAndTimeImpl(ProbablySameFilter(filter), _, _))
2559 .WillOnce(Return(password_manager::PasswordStoreChangeList()));
2560 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2561 BrowsingDataRemover::REMOVE_PASSWORDS, false);
2562 }
2563
2564 TEST_F(BrowsingDataRemoverTest, RemovePasswordsByOrigin) {
2565 RemovePasswordsTester tester(GetProfile());
2566 RegistrableDomainFilterBuilder builder(
2567 RegistrableDomainFilterBuilder::WHITELIST);
2568 builder.AddRegisterableDomain(kTestRegisterableDomain1);
2569 base::Callback<bool(const GURL&)> filter = builder.BuildGeneralFilter();
2570
2571 EXPECT_CALL(*tester.store(),
2572 RemoveLoginsByURLAndTimeImpl(ProbablySameFilter(filter), _, _))
2573 .WillOnce(Return(password_manager::PasswordStoreChangeList()));
2574 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
2575 BrowsingDataRemover::REMOVE_PASSWORDS, builder);
2576 }
2577
2578 TEST_F(BrowsingDataRemoverTest, DisableAutoSignIn) {
2579 RemovePasswordsTester tester(GetProfile());
2580 base::Callback<bool(const GURL&)> empty_filter =
2581 BrowsingDataFilterBuilder::BuildNoopFilter();
2582
2583 EXPECT_CALL(
2584 *tester.store(),
2585 DisableAutoSignInForOriginsImpl(ProbablySameFilter(empty_filter)))
2586 .WillOnce(Return(password_manager::PasswordStoreChangeList()));
2587
2588 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2589 BrowsingDataRemover::REMOVE_COOKIES, false);
2590 }
2591
2592 TEST_F(BrowsingDataRemoverTest, DisableAutoSignInAfterRemovingPasswords) {
2593 RemovePasswordsTester tester(GetProfile());
2594 base::Callback<bool(const GURL&)> empty_filter =
2595 BrowsingDataFilterBuilder::BuildNoopFilter();
2596
2597 EXPECT_CALL(*tester.store(), RemoveLoginsByURLAndTimeImpl(_, _, _))
2598 .WillOnce(Return(password_manager::PasswordStoreChangeList()));
2599 EXPECT_CALL(
2600 *tester.store(),
2601 DisableAutoSignInForOriginsImpl(ProbablySameFilter(empty_filter)))
2602 .WillOnce(Return(password_manager::PasswordStoreChangeList()));
2603
2604 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2605 BrowsingDataRemover::REMOVE_COOKIES |
2606 BrowsingDataRemover::REMOVE_PASSWORDS,
2607 false);
2608 }
2609
2610 TEST_F(BrowsingDataRemoverTest, RemoveContentSettingsWithBlacklist) {
2611 // Add our settings.
2612 HostContentSettingsMap* host_content_settings_map =
2613 HostContentSettingsMapFactory::GetForProfile(GetProfile());
2614 host_content_settings_map->SetWebsiteSettingDefaultScope(
2615 kOrigin1, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(),
2616 base::MakeUnique<base::DictionaryValue>());
2617 host_content_settings_map->SetWebsiteSettingDefaultScope(
2618 kOrigin2, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(),
2619 base::MakeUnique<base::DictionaryValue>());
2620 host_content_settings_map->SetWebsiteSettingDefaultScope(
2621 kOrigin3, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(),
2622 base::MakeUnique<base::DictionaryValue>());
2623 host_content_settings_map->SetWebsiteSettingDefaultScope(
2624 kOrigin4, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(),
2625 base::MakeUnique<base::DictionaryValue>());
2626
2627 // Clear all except for origin1 and origin3.
2628 RegistrableDomainFilterBuilder filter(
2629 RegistrableDomainFilterBuilder::BLACKLIST);
2630 filter.AddRegisterableDomain(kTestRegisterableDomain1);
2631 filter.AddRegisterableDomain(kTestRegisterableDomain3);
2632 BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
2633 BrowsingDataRemover::REMOVE_SITE_USAGE_DATA,
2634 filter);
2635
2636 EXPECT_EQ(BrowsingDataRemover::REMOVE_SITE_USAGE_DATA, GetRemovalMask());
2637 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2638
2639 // Verify we only have true, and they're origin1, origin3, and origin4.
2640 ContentSettingsForOneType host_settings;
2641 host_content_settings_map->GetSettingsForOneType(
2642 CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(), &host_settings);
2643 EXPECT_EQ(3u, host_settings.size());
2644 EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin1),
2645 host_settings[0].primary_pattern)
2646 << host_settings[0].primary_pattern.ToString();
2647 EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin4),
2648 host_settings[1].primary_pattern)
2649 << host_settings[1].primary_pattern.ToString();
2650 EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin3),
2651 host_settings[2].primary_pattern)
2652 << host_settings[2].primary_pattern.ToString();
2653 }
2654
2655 TEST_F(BrowsingDataRemoverTest, RemoveDurablePermission) {
2656 // Add our settings.
2657 HostContentSettingsMap* host_content_settings_map =
2658 HostContentSettingsMapFactory::GetForProfile(GetProfile());
2659
2660 DurableStoragePermissionContext durable_permission(GetProfile());
2661 durable_permission.UpdateContentSetting(kOrigin1, GURL(),
2662 CONTENT_SETTING_ALLOW);
2663 durable_permission.UpdateContentSetting(kOrigin2, GURL(),
2664 CONTENT_SETTING_ALLOW);
2665
2666 // Clear all except for origin1 and origin3.
2667 RegistrableDomainFilterBuilder filter(
2668 RegistrableDomainFilterBuilder::BLACKLIST);
2669 filter.AddRegisterableDomain(kTestRegisterableDomain1);
2670 filter.AddRegisterableDomain(kTestRegisterableDomain3);
2671 BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
2672 BrowsingDataRemover::REMOVE_DURABLE_PERMISSION,
2673 filter);
2674
2675 EXPECT_EQ(BrowsingDataRemover::REMOVE_DURABLE_PERMISSION, GetRemovalMask());
2676 EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginTypeMask());
2677
2678 // Verify we only have allow for the first origin.
2679 ContentSettingsForOneType host_settings;
2680 host_content_settings_map->GetSettingsForOneType(
2681 CONTENT_SETTINGS_TYPE_DURABLE_STORAGE, std::string(), &host_settings);
2682
2683 ASSERT_EQ(2u, host_settings.size());
2684 // Only the first should should have a setting.
2685 EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin1),
2686 host_settings[0].primary_pattern)
2687 << host_settings[0].primary_pattern.ToString();
2688 EXPECT_EQ(CONTENT_SETTING_ALLOW, host_settings[0].setting);
2689
2690 // And our wildcard.
2691 EXPECT_EQ(ContentSettingsPattern::Wildcard(),
2692 host_settings[1].primary_pattern)
2693 << host_settings[1].primary_pattern.ToString();
2694 EXPECT_EQ(CONTENT_SETTING_ASK, host_settings[1].setting);
2695 }
2696
2697 // Test that removing cookies clears HTTP auth data.
2698 TEST_F(BrowsingDataRemoverTest, ClearHttpAuthCache_RemoveCookies) {
2699 net::HttpNetworkSession* http_session = GetProfile()
2700 ->GetRequestContext()
2701 ->GetURLRequestContext()
2702 ->http_transaction_factory()
2703 ->GetSession();
2704 DCHECK(http_session);
2705
2706 net::HttpAuthCache* http_auth_cache = http_session->http_auth_cache();
2707 http_auth_cache->Add(kOrigin1, kTestRealm, net::HttpAuth::AUTH_SCHEME_BASIC,
2708 "test challenge",
2709 net::AuthCredentials(base::ASCIIToUTF16("foo"),
2710 base::ASCIIToUTF16("bar")),
2711 "/");
2712 CHECK(http_auth_cache->Lookup(kOrigin1, kTestRealm,
2713 net::HttpAuth::AUTH_SCHEME_BASIC));
2714
2715 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2716 BrowsingDataRemover::REMOVE_COOKIES, false);
2717
2718 EXPECT_EQ(nullptr, http_auth_cache->Lookup(kOrigin1, kTestRealm,
2719 net::HttpAuth::AUTH_SCHEME_BASIC));
2720 }
2721
2722 // Test that removing passwords clears HTTP auth data.
2723 TEST_F(BrowsingDataRemoverTest, ClearHttpAuthCache_RemovePasswords) {
2724 net::HttpNetworkSession* http_session = GetProfile()
2725 ->GetRequestContext()
2726 ->GetURLRequestContext()
2727 ->http_transaction_factory()
2728 ->GetSession();
2729 DCHECK(http_session);
2730
2731 net::HttpAuthCache* http_auth_cache = http_session->http_auth_cache();
2732 http_auth_cache->Add(kOrigin1, kTestRealm, net::HttpAuth::AUTH_SCHEME_BASIC,
2733 "test challenge",
2734 net::AuthCredentials(base::ASCIIToUTF16("foo"),
2735 base::ASCIIToUTF16("bar")),
2736 "/");
2737 CHECK(http_auth_cache->Lookup(kOrigin1, kTestRealm,
2738 net::HttpAuth::AUTH_SCHEME_BASIC));
2739
2740 BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
2741 BrowsingDataRemover::REMOVE_PASSWORDS, false);
2742
2743 EXPECT_EQ(nullptr, http_auth_cache->Lookup(kOrigin1, kTestRealm,
2744 net::HttpAuth::AUTH_SCHEME_BASIC));
2745 }
2746
2747 TEST_F(BrowsingDataRemoverTest, ClearPermissionPromptCounts) {
2748 RemovePermissionPromptCountsTest tester(GetProfile());
2749
2750 RegistrableDomainFilterBuilder filter_builder_1(
2751 RegistrableDomainFilterBuilder::WHITELIST);
2752 filter_builder_1.AddRegisterableDomain(kTestRegisterableDomain1);
2753
2754 RegistrableDomainFilterBuilder filter_builder_2(
2755 RegistrableDomainFilterBuilder::BLACKLIST);
2756 filter_builder_2.AddRegisterableDomain(kTestRegisterableDomain1);
2757
2758 {
2759 // Test REMOVE_HISTORY.
2760 EXPECT_EQ(1, tester.RecordIgnore(kOrigin1,
2761 content::PermissionType::GEOLOCATION));
2762 EXPECT_EQ(2, tester.RecordIgnore(kOrigin1,
2763 content::PermissionType::GEOLOCATION));
2764 EXPECT_EQ(1, tester.RecordIgnore(kOrigin1,
2765 content::PermissionType::NOTIFICATIONS));
2766 tester.ShouldChangeDismissalToBlock(kOrigin1,
2767 content::PermissionType::MIDI_SYSEX);
2768 EXPECT_EQ(1, tester.RecordIgnore(kOrigin2,
2769 content::PermissionType::DURABLE_STORAGE));
2770 tester.ShouldChangeDismissalToBlock(kOrigin2,
2771 content::PermissionType::NOTIFICATIONS);
2772
2773 BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
2774 BrowsingDataRemover::REMOVE_SITE_USAGE_DATA,
2775 filter_builder_1);
2776
2777 // kOrigin1 should be gone, but kOrigin2 remains.
2778 EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin1,
2779 content::PermissionType::GEOLOCATION));
2780 EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin1,
2781 content::PermissionType::NOTIFICATIONS));
2782 EXPECT_EQ(0, tester.GetDismissCount(kOrigin1,
2783 content::PermissionType::MIDI_SYSEX));
2784 EXPECT_EQ(1, tester.GetIgnoreCount(
2785 kOrigin2, content::PermissionType::DURABLE_STORAGE));
2786 EXPECT_EQ(1, tester.GetDismissCount(
2787 kOrigin2, content::PermissionType::NOTIFICATIONS));
2788
2789 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
2790 BrowsingDataRemover::REMOVE_HISTORY, false);
2791
2792 // Everything should be gone.
2793 EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin1,
2794 content::PermissionType::GEOLOCATION));
2795 EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin1,
2796 content::PermissionType::NOTIFICATIONS));
2797 EXPECT_EQ(0, tester.GetDismissCount(kOrigin1,
2798 content::PermissionType::MIDI_SYSEX));
2799 EXPECT_EQ(0, tester.GetIgnoreCount(
2800 kOrigin2, content::PermissionType::DURABLE_STORAGE));
2801 EXPECT_EQ(0, tester.GetDismissCount(
2802 kOrigin2, content::PermissionType::NOTIFICATIONS));
2803 }
2804 {
2805 // Test REMOVE_SITE_DATA.
2806 EXPECT_EQ(1, tester.RecordIgnore(kOrigin1,
2807 content::PermissionType::GEOLOCATION));
2808 EXPECT_EQ(2, tester.RecordIgnore(kOrigin1,
2809 content::PermissionType::GEOLOCATION));
2810 EXPECT_EQ(1, tester.RecordIgnore(kOrigin1,
2811 content::PermissionType::NOTIFICATIONS));
2812 tester.ShouldChangeDismissalToBlock(kOrigin1,
2813 content::PermissionType::MIDI_SYSEX);
2814 EXPECT_EQ(1, tester.RecordIgnore(kOrigin2,
2815 content::PermissionType::DURABLE_STORAGE));
2816 tester.ShouldChangeDismissalToBlock(kOrigin2,
2817 content::PermissionType::NOTIFICATIONS);
2818
2819 BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
2820 BrowsingDataRemover::REMOVE_SITE_USAGE_DATA,
2821 filter_builder_2);
2822
2823 // kOrigin2 should be gone, but kOrigin1 remains.
2824 EXPECT_EQ(2, tester.GetIgnoreCount(kOrigin1,
2825 content::PermissionType::GEOLOCATION));
2826 EXPECT_EQ(1, tester.GetIgnoreCount(kOrigin1,
2827 content::PermissionType::NOTIFICATIONS));
2828 EXPECT_EQ(1, tester.GetDismissCount(kOrigin1,
2829 content::PermissionType::MIDI_SYSEX));
2830 EXPECT_EQ(0, tester.GetIgnoreCount(
2831 kOrigin2, content::PermissionType::DURABLE_STORAGE));
2832 EXPECT_EQ(0, tester.GetDismissCount(
2833 kOrigin2, content::PermissionType::NOTIFICATIONS));
2834
2835 BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
2836 BrowsingDataRemover::REMOVE_SITE_USAGE_DATA,
2837 false);
2838
2839 // Everything should be gone.
2840 EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin1,
2841 content::PermissionType::GEOLOCATION));
2842 EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin1,
2843 content::PermissionType::NOTIFICATIONS));
2844 EXPECT_EQ(0, tester.GetDismissCount(kOrigin1,
2845 content::PermissionType::MIDI_SYSEX));
2846 EXPECT_EQ(0, tester.GetIgnoreCount(
2847 kOrigin2, content::PermissionType::DURABLE_STORAGE));
2848 EXPECT_EQ(0, tester.GetDismissCount(
2849 kOrigin2, content::PermissionType::NOTIFICATIONS));
2850 }
2851 }
2852
2853 #if BUILDFLAG(ENABLE_PLUGINS)
2854 TEST_F(BrowsingDataRemoverTest, RemovePluginData) {
2855 RemovePluginDataTester tester(GetProfile());
2856
2857 tester.AddDomain(kOrigin1.host());
2858 tester.AddDomain(kOrigin2.host());
2859 tester.AddDomain(kOrigin3.host());
2860
2861 std::vector<std::string> expected = {
2862 kOrigin1.host(), kOrigin2.host(), kOrigin3.host() };
2863 EXPECT_EQ(expected, tester.GetDomains());
2864
2865 // Delete data with a filter for the registrable domain of |kOrigin3|.
2866 RegistrableDomainFilterBuilder filter_builder(
2867 RegistrableDomainFilterBuilder::WHITELIST);
2868 filter_builder.AddRegisterableDomain(kTestRegisterableDomain3);
2869 BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
2870 BrowsingDataRemover::REMOVE_PLUGIN_DATA,
2871 filter_builder);
2872
2873 // Plugin data for |kOrigin3.host()| should have been removed.
2874 expected.pop_back();
2875 EXPECT_EQ(expected, tester.GetDomains());
2876
2877 // TODO(msramek): Mock PluginDataRemover and test the complete deletion
2878 // of plugin data as well.
2879 }
2880 #endif
2881
2882 class MultipleTasksObserver {
2883 public:
2884 // A simple implementation of BrowsingDataRemover::Observer.
2885 // MultipleTasksObserver will use several instances of Target to test
2886 // that completion callbacks are returned to the correct one.
2887 class Target : public BrowsingDataRemover::Observer {
2888 public:
2889 Target(MultipleTasksObserver* parent, BrowsingDataRemover* remover)
2890 : parent_(parent),
2891 observer_(this) {
2892 observer_.Add(remover);
2893 }
2894 ~Target() override {}
2895
2896 void OnBrowsingDataRemoverDone() override {
2897 parent_->SetLastCalledTarget(this);
2898 }
2899
2900 private:
2901 MultipleTasksObserver* parent_;
2902 ScopedObserver<BrowsingDataRemover, BrowsingDataRemover::Observer>
2903 observer_;
2904 };
2905
2906 explicit MultipleTasksObserver(BrowsingDataRemover* remover)
2907 : target_a_(this, remover),
2908 target_b_(this, remover),
2909 last_called_target_(nullptr) {}
2910 ~MultipleTasksObserver() {}
2911
2912 void ClearLastCalledTarget() {
2913 last_called_target_ = nullptr;
2914 }
2915
2916 Target* GetLastCalledTarget() {
2917 return last_called_target_;
2918 }
2919
2920 Target* target_a() { return &target_a_; }
2921 Target* target_b() { return &target_b_; }
2922
2923 private:
2924 void SetLastCalledTarget(Target* target) {
2925 DCHECK(!last_called_target_)
2926 << "Call ClearLastCalledTarget() before every removal task.";
2927 last_called_target_ = target;
2928 }
2929
2930 Target target_a_;
2931 Target target_b_;
2932 Target* last_called_target_;
2933 };
2934
2935 TEST_F(BrowsingDataRemoverTest, MultipleTasks) {
2936 BrowsingDataRemoverImpl* remover = static_cast<BrowsingDataRemoverImpl*>(
2937 BrowsingDataRemoverFactory::GetForBrowserContext(GetProfile()));
2938 EXPECT_FALSE(remover->is_removing());
2939
2940 std::unique_ptr<RegistrableDomainFilterBuilder> filter_builder_1(
2941 new RegistrableDomainFilterBuilder(
2942 RegistrableDomainFilterBuilder::WHITELIST));
2943 std::unique_ptr<RegistrableDomainFilterBuilder> filter_builder_2(
2944 new RegistrableDomainFilterBuilder(
2945 RegistrableDomainFilterBuilder::BLACKLIST));
2946 filter_builder_2->AddRegisterableDomain("example.com");
2947
2948 MultipleTasksObserver observer(remover);
2949 BrowsingDataRemoverCompletionInhibitor completion_inhibitor;
2950
2951 // Test several tasks with various configuration of masks, filters, and target
2952 // observers.
2953 std::list<BrowsingDataRemoverImpl::RemovalTask> tasks;
2954 tasks.emplace_back(base::Time(), base::Time::Max(),
2955 BrowsingDataRemover::REMOVE_HISTORY,
2956 BrowsingDataHelper::UNPROTECTED_WEB,
2957 base::MakeUnique<RegistrableDomainFilterBuilder>(
2958 RegistrableDomainFilterBuilder::BLACKLIST),
2959 observer.target_a());
2960 tasks.emplace_back(base::Time(), base::Time::Max(),
2961 BrowsingDataRemover::REMOVE_COOKIES,
2962 BrowsingDataHelper::PROTECTED_WEB,
2963 base::MakeUnique<RegistrableDomainFilterBuilder>(
2964 RegistrableDomainFilterBuilder::BLACKLIST),
2965 nullptr);
2966 tasks.emplace_back(
2967 base::Time::Now(), base::Time::Max(),
2968 BrowsingDataRemover::REMOVE_PASSWORDS, BrowsingDataHelper::ALL,
2969 base::MakeUnique<RegistrableDomainFilterBuilder>(
2970 RegistrableDomainFilterBuilder::BLACKLIST),
2971 observer.target_b());
2972 tasks.emplace_back(
2973 base::Time(), base::Time::UnixEpoch(),
2974 BrowsingDataRemover::REMOVE_WEBSQL,
2975 BrowsingDataHelper::UNPROTECTED_WEB,
2976 std::move(filter_builder_1),
2977 observer.target_b());
2978 tasks.emplace_back(
2979 base::Time::UnixEpoch(), base::Time::Now(),
2980 BrowsingDataRemover::REMOVE_CHANNEL_IDS,
2981 BrowsingDataHelper::ALL,
2982 std::move(filter_builder_2),
2983 nullptr);
2984
2985 for (BrowsingDataRemoverImpl::RemovalTask& task : tasks) {
2986 // All tasks can be directly translated to a RemoveInternal() call. Since
2987 // that is a private method, we must call the four public versions of
2988 // Remove.* instead. This also serves as a test that those methods are all
2989 // correctly reduced to RemoveInternal().
2990 if (!task.observer && task.filter_builder->IsEmptyBlacklist()) {
2991 remover->Remove(task.delete_begin, task.delete_end,
2992 task.remove_mask, task.origin_type_mask);
2993 } else if (task.filter_builder->IsEmptyBlacklist()) {
2994 remover->RemoveAndReply(task.delete_begin, task.delete_end,
2995 task.remove_mask, task.origin_type_mask,
2996 task.observer);
2997 } else if (!task.observer) {
2998 remover->RemoveWithFilter(task.delete_begin, task.delete_end,
2999 task.remove_mask, task.origin_type_mask,
3000 std::move(task.filter_builder));
3001 } else {
3002 remover->RemoveWithFilterAndReply(task.delete_begin, task.delete_end,
3003 task.remove_mask, task.origin_type_mask,
3004 std::move(task.filter_builder),
3005 task.observer);
3006 }
3007 }
3008
3009 // Use the inhibitor to stop after every task and check the results.
3010 for (BrowsingDataRemoverImpl::RemovalTask& task : tasks) {
3011 EXPECT_TRUE(remover->is_removing());
3012 observer.ClearLastCalledTarget();
3013
3014 // Finish the task execution synchronously.
3015 completion_inhibitor.BlockUntilNearCompletion();
3016 completion_inhibitor.ContinueToCompletion();
3017
3018 // Observers, if any, should have been called by now (since we call
3019 // observers on the same thread).
3020 EXPECT_EQ(task.observer, observer.GetLastCalledTarget());
3021
3022 // TODO(msramek): If BrowsingDataRemover took ownership of the last used
3023 // filter builder and exposed it, we could also test it here. Make it so.
3024 EXPECT_EQ(task.remove_mask, GetRemovalMask());
3025 EXPECT_EQ(task.origin_type_mask, GetOriginTypeMask());
3026 EXPECT_EQ(task.delete_begin, GetBeginTime());
3027 }
3028
3029 EXPECT_FALSE(remover->is_removing());
3030 }
3031
3032 // The previous test, BrowsingDataRemoverTest.MultipleTasks, tests that the
3033 // tasks are not mixed up and they are executed in a correct order. However,
3034 // the completion inhibitor kept synchronizing the execution in order to verify
3035 // the parameters. This test demonstrates that even running the tasks without
3036 // inhibition is executed correctly and doesn't crash.
3037 TEST_F(BrowsingDataRemoverTest, MultipleTasksInQuickSuccession) {
3038 BrowsingDataRemoverImpl* remover = static_cast<BrowsingDataRemoverImpl*>(
3039 BrowsingDataRemoverFactory::GetForBrowserContext(GetProfile()));
3040 EXPECT_FALSE(remover->is_removing());
3041
3042 int test_removal_masks[] = {
3043 BrowsingDataRemover::REMOVE_COOKIES,
3044 BrowsingDataRemover::REMOVE_PASSWORDS,
3045 BrowsingDataRemover::REMOVE_COOKIES,
3046 BrowsingDataRemover::REMOVE_COOKIES,
3047 BrowsingDataRemover::REMOVE_COOKIES,
3048 BrowsingDataRemover::REMOVE_HISTORY,
3049 BrowsingDataRemover::REMOVE_HISTORY,
3050 BrowsingDataRemover::REMOVE_HISTORY,
3051 BrowsingDataRemover::REMOVE_COOKIES | BrowsingDataRemover::REMOVE_HISTORY,
3052 BrowsingDataRemover::REMOVE_COOKIES | BrowsingDataRemover::REMOVE_HISTORY,
3053 BrowsingDataRemover::REMOVE_COOKIES |
3054 BrowsingDataRemover::REMOVE_HISTORY |
3055 BrowsingDataRemover::REMOVE_PASSWORDS,
3056 BrowsingDataRemover::REMOVE_PASSWORDS,
3057 BrowsingDataRemover::REMOVE_PASSWORDS,
3058 };
3059
3060 for (int removal_mask : test_removal_masks) {
3061 remover->Remove(base::Time(), base::Time::Max(), removal_mask,
3062 BrowsingDataHelper::UNPROTECTED_WEB);
3063 }
3064
3065 EXPECT_TRUE(remover->is_removing());
3066
3067 // Add one more deletion and wait for it.
3068 BlockUntilBrowsingDataRemoved(
3069 base::Time(), base::Time::Max(),
3070 BrowsingDataRemover::REMOVE_COOKIES,
3071 BrowsingDataHelper::UNPROTECTED_WEB);
3072
3073 EXPECT_FALSE(remover->is_removing());
3074 }
3075
3076 // Test that the remover clears bookmark meta data (normally added in a tab
3077 // helper).
3078 TEST_F(BrowsingDataRemoverTest, BookmarkLastVisitDatesGetCleared) {
3079 TestingProfile profile;
3080 profile.CreateBookmarkModel(true);
3081
3082 bookmarks::BookmarkModel* bookmark_model =
3083 BookmarkModelFactory::GetForBrowserContext(&profile);
3084 bookmarks::test::WaitForBookmarkModelToLoad(bookmark_model);
3085
3086 const base::Time delete_begin =
3087 base::Time::Now() - base::TimeDelta::FromDays(1);
3088
3089 // Create a couple of bookmarks.
3090 bookmark_model->AddURL(bookmark_model->bookmark_bar_node(), 0,
3091 base::string16(),
3092 GURL("http://foo.org/desktop"));
3093 bookmark_model->AddURL(bookmark_model->mobile_node(), 0,
3094 base::string16(),
3095 GURL("http://foo.org/mobile"));
3096
3097 // Simulate their visits (this is using Time::Now() as timestamps).
3098 ntp_snippets::UpdateBookmarkOnURLVisitedInMainFrame(
3099 bookmark_model, GURL("http://foo.org/desktop"),
3100 /*is_mobile_platform=*/false);
3101 ntp_snippets::UpdateBookmarkOnURLVisitedInMainFrame(
3102 bookmark_model, GURL("http://foo.org/mobile"),
3103 /*is_mobile_platform=*/true);
3104
3105 // Add a bookmark with a visited timestamp before the deletion interval.
3106 bookmarks::BookmarkNode::MetaInfoMap meta_info = {
3107 {"last_visited",
3108 base::Int64ToString((delete_begin - base::TimeDelta::FromSeconds(1))
3109 .ToInternalValue())}};
3110 bookmark_model->AddURLWithCreationTimeAndMetaInfo(
3111 bookmark_model->mobile_node(), 0, base::ASCIIToUTF16("my title"),
3112 GURL("http://foo-2.org/"), delete_begin - base::TimeDelta::FromDays(1),
3113 &meta_info);
3114
3115 // There should be some recently visited bookmarks.
3116 EXPECT_THAT(ntp_snippets::GetRecentlyVisitedBookmarks(
3117 bookmark_model, 2, base::Time::UnixEpoch(),
3118 /*consider_visits_from_desktop=*/false),
3119 Not(IsEmpty()));
3120
3121 // Inject the bookmark model into the remover.
3122 BrowsingDataRemover* remover =
3123 BrowsingDataRemoverFactory::GetForBrowserContext(&profile);
3124
3125 BrowsingDataRemoverCompletionObserver completion_observer(remover);
3126 remover->RemoveAndReply(delete_begin, base::Time::Max(),
3127 BrowsingDataRemover::REMOVE_HISTORY,
3128 BrowsingDataHelper::ALL, &completion_observer);
3129 completion_observer.BlockUntilCompletion();
3130
3131 // There should be only 1 recently visited bookmarks.
3132 std::vector<const bookmarks::BookmarkNode*> remaining_nodes =
3133 ntp_snippets::GetRecentlyVisitedBookmarks(
3134 bookmark_model, 3, base::Time::UnixEpoch(),
3135 /*consider_visits_from_desktop=*/true);
3136 EXPECT_THAT(remaining_nodes, SizeIs(1));
3137 EXPECT_THAT(remaining_nodes[0]->url().spec(), Eq("http://foo-2.org/"));
3138 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698