Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / browsing_data / browsing_data_remover_unittest.cc
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 "chrome/browser/browsing_data/browsing_data_remover.h"
6
7 #include <set>
8 #include <string>
9 #include <vector>
10
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/guid.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/prefs/testing_pref_service.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/task/cancelable_task_tracker.h"
20 #include "chrome/browser/autofill/personal_data_manager_factory.h"
21 #include "chrome/browser/browsing_data/browsing_data_helper.h"
22 #include "chrome/browser/browsing_data/browsing_data_remover_test_util.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/domain_reliability/service_factory.h"
25 #include "chrome/browser/history/history_service.h"
26 #include "chrome/browser/history/history_service_factory.h"
27 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
28 #include "chrome/common/pref_names.h"
29 #include "chrome/test/base/testing_browser_process.h"
30 #include "chrome/test/base/testing_profile.h"
31 #include "components/autofill/core/browser/autofill_profile.h"
32 #include "components/autofill/core/browser/autofill_test_utils.h"
33 #include "components/autofill/core/browser/credit_card.h"
34 #include "components/autofill/core/browser/personal_data_manager.h"
35 #include "components/autofill/core/browser/personal_data_manager_observer.h"
36 #include "components/domain_reliability/clear_mode.h"
37 #include "components/domain_reliability/monitor.h"
38 #include "components/domain_reliability/service.h"
39 #include "content/public/browser/cookie_store_factory.h"
40 #include "content/public/browser/dom_storage_context.h"
41 #include "content/public/browser/local_storage_usage_info.h"
42 #include "content/public/browser/notification_service.h"
43 #include "content/public/browser/storage_partition.h"
44 #include "content/public/test/test_browser_thread.h"
45 #include "content/public/test/test_browser_thread_bundle.h"
46 #include "content/public/test/test_utils.h"
47 #include "net/cookies/cookie_store.h"
48 #include "net/ssl/channel_id_service.h"
49 #include "net/ssl/channel_id_store.h"
50 #include "net/ssl/ssl_client_cert_type.h"
51 #include "net/url_request/url_request_context.h"
52 #include "net/url_request/url_request_context_getter.h"
53 #include "testing/gmock/include/gmock/gmock.h"
54 #include "testing/gtest/include/gtest/gtest.h"
55
56 #if defined(OS_CHROMEOS)
57 #include "chrome/browser/chromeos/login/users/mock_user_manager.h"
58 #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
59 #include "chrome/browser/chromeos/settings/cros_settings.h"
60 #include "chrome/browser/chromeos/settings/device_settings_service.h"
61 #include "chromeos/dbus/dbus_thread_manager.h"
62 #include "chromeos/dbus/mock_cryptohome_client.h"
63 #endif
64
65 #if defined(ENABLE_EXTENSIONS)
66 #include "chrome/browser/extensions/mock_extension_special_storage_policy.h"
67 #endif
68
69 class MockExtensionSpecialStoragePolicy;
70
71 using content::BrowserThread;
72 using content::StoragePartition;
73 using domain_reliability::CLEAR_BEACONS;
74 using domain_reliability::CLEAR_CONTEXTS;
75 using domain_reliability::DomainReliabilityClearMode;
76 using domain_reliability::DomainReliabilityMonitor;
77 using domain_reliability::DomainReliabilityService;
78 using domain_reliability::DomainReliabilityServiceFactory;
79 using testing::_;
80 using testing::Invoke;
81 using testing::WithArgs;
82
83 namespace {
84
85 const char kTestOrigin1[] = "http://host1:1/";
86 const char kTestOrigin2[] = "http://host2:1/";
87 const char kTestOrigin3[] = "http://host3:1/";
88 const char kTestOriginExt[] = "chrome-extension://abcdefghijklmnopqrstuvwxyz/";
89 const char kTestOriginDevTools[] = "chrome-devtools://abcdefghijklmnopqrstuvw/";
90
91 // For Autofill.
92 const char kChromeOrigin[] = "Chrome settings";
93 const char kWebOrigin[] = "https://www.example.com/";
94
95 const GURL kOrigin1(kTestOrigin1);
96 const GURL kOrigin2(kTestOrigin2);
97 const GURL kOrigin3(kTestOrigin3);
98 const GURL kOriginExt(kTestOriginExt);
99 const GURL kOriginDevTools(kTestOriginDevTools);
100
101 const base::FilePath::CharType kDomStorageOrigin1[] =
102     FILE_PATH_LITERAL("http_host1_1.localstorage");
103
104 const base::FilePath::CharType kDomStorageOrigin2[] =
105     FILE_PATH_LITERAL("http_host2_1.localstorage");
106
107 const base::FilePath::CharType kDomStorageOrigin3[] =
108     FILE_PATH_LITERAL("http_host3_1.localstorage");
109
110 const base::FilePath::CharType kDomStorageExt[] = FILE_PATH_LITERAL(
111     "chrome-extension_abcdefghijklmnopqrstuvwxyz_0.localstorage");
112
113 #if defined(OS_CHROMEOS)
114 void FakeDBusCall(const chromeos::BoolDBusMethodCallback& callback) {
115   base::MessageLoop::current()->PostTask(
116       FROM_HERE,
117       base::Bind(callback, chromeos::DBUS_METHOD_CALL_SUCCESS, true));
118 }
119 #endif
120
121 struct StoragePartitionRemovalData {
122   uint32 remove_mask;
123   uint32 quota_storage_remove_mask;
124   GURL remove_origin;
125   base::Time remove_begin;
126   base::Time remove_end;
127   StoragePartition::OriginMatcherFunction origin_matcher;
128
129   StoragePartitionRemovalData() : remove_mask(0),
130                                   quota_storage_remove_mask(0) {}
131 };
132
133 class TestStoragePartition : public StoragePartition {
134  public:
135   TestStoragePartition() {}
136   ~TestStoragePartition() override {}
137
138   // content::StoragePartition implementation.
139   base::FilePath GetPath() override { return base::FilePath(); }
140   net::URLRequestContextGetter* GetURLRequestContext() override { return NULL; }
141   net::URLRequestContextGetter* GetMediaURLRequestContext() override {
142     return NULL;
143   }
144   storage::QuotaManager* GetQuotaManager() override { return NULL; }
145   content::AppCacheService* GetAppCacheService() override { return NULL; }
146   storage::FileSystemContext* GetFileSystemContext() override { return NULL; }
147   storage::DatabaseTracker* GetDatabaseTracker() override { return NULL; }
148   content::DOMStorageContext* GetDOMStorageContext() override { return NULL; }
149   content::IndexedDBContext* GetIndexedDBContext() override { return NULL; }
150   content::ServiceWorkerContext* GetServiceWorkerContext() override {
151     return NULL;
152   }
153   content::GeofencingManager* GetGeofencingManager() override { return NULL; }
154
155   void ClearDataForOrigin(uint32 remove_mask,
156                           uint32 quota_storage_remove_mask,
157                           const GURL& storage_origin,
158                           net::URLRequestContextGetter* rq_context,
159                           const base::Closure& callback) override {
160     BrowserThread::PostTask(BrowserThread::UI,
161                             FROM_HERE,
162                             base::Bind(&TestStoragePartition::AsyncRunCallback,
163                                        base::Unretained(this),
164                                        callback));
165   }
166
167   void ClearData(uint32 remove_mask,
168                  uint32 quota_storage_remove_mask,
169                  const GURL& storage_origin,
170                  const OriginMatcherFunction& origin_matcher,
171                  const base::Time begin,
172                  const base::Time end,
173                  const base::Closure& callback) override {
174     // Store stuff to verify parameters' correctness later.
175     storage_partition_removal_data_.remove_mask = remove_mask;
176     storage_partition_removal_data_.quota_storage_remove_mask =
177         quota_storage_remove_mask;
178     storage_partition_removal_data_.remove_origin = storage_origin;
179     storage_partition_removal_data_.remove_begin = begin;
180     storage_partition_removal_data_.remove_end = end;
181     storage_partition_removal_data_.origin_matcher = origin_matcher;
182
183     BrowserThread::PostTask(
184         BrowserThread::UI,
185         FROM_HERE,
186         base::Bind(&TestStoragePartition::AsyncRunCallback,
187                    base::Unretained(this), callback));
188   }
189
190   StoragePartitionRemovalData GetStoragePartitionRemovalData() {
191     return storage_partition_removal_data_;
192   }
193
194  private:
195   void AsyncRunCallback(const base::Closure& callback) {
196     callback.Run();
197   }
198
199   StoragePartitionRemovalData storage_partition_removal_data_;
200
201   DISALLOW_COPY_AND_ASSIGN(TestStoragePartition);
202 };
203
204 }  // namespace
205
206 // Testers -------------------------------------------------------------------
207
208 class RemoveCookieTester {
209  public:
210   RemoveCookieTester() : get_cookie_success_(false), cookie_store_(NULL) {
211   }
212
213   // Returns true, if the given cookie exists in the cookie store.
214   bool ContainsCookie() {
215     scoped_refptr<content::MessageLoopRunner> message_loop_runner =
216         new content::MessageLoopRunner;
217     quit_closure_ = message_loop_runner->QuitClosure();
218     get_cookie_success_ = false;
219     cookie_store_->GetCookiesWithOptionsAsync(
220         kOrigin1, net::CookieOptions(),
221         base::Bind(&RemoveCookieTester::GetCookieCallback,
222                    base::Unretained(this)));
223     message_loop_runner->Run();
224     return get_cookie_success_;
225   }
226
227   void AddCookie() {
228     scoped_refptr<content::MessageLoopRunner> message_loop_runner =
229         new content::MessageLoopRunner;
230     quit_closure_ = message_loop_runner->QuitClosure();
231     cookie_store_->SetCookieWithOptionsAsync(
232         kOrigin1, "A=1", net::CookieOptions(),
233         base::Bind(&RemoveCookieTester::SetCookieCallback,
234                    base::Unretained(this)));
235     message_loop_runner->Run();
236   }
237
238  protected:
239   void SetMonster(net::CookieStore* monster) {
240     cookie_store_ = monster;
241   }
242
243  private:
244   void GetCookieCallback(const std::string& cookies) {
245     if (cookies == "A=1") {
246       get_cookie_success_ = true;
247     } else {
248       EXPECT_EQ("", cookies);
249       get_cookie_success_ = false;
250     }
251     quit_closure_.Run();
252   }
253
254   void SetCookieCallback(bool result) {
255     ASSERT_TRUE(result);
256     quit_closure_.Run();
257   }
258
259   bool get_cookie_success_;
260   base::Closure quit_closure_;
261   net::CookieStore* cookie_store_;
262
263   DISALLOW_COPY_AND_ASSIGN(RemoveCookieTester);
264 };
265
266 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
267 class RemoveSafeBrowsingCookieTester : public RemoveCookieTester {
268  public:
269   RemoveSafeBrowsingCookieTester()
270       : browser_process_(TestingBrowserProcess::GetGlobal()) {
271     scoped_refptr<SafeBrowsingService> sb_service =
272         SafeBrowsingService::CreateSafeBrowsingService();
273     browser_process_->SetSafeBrowsingService(sb_service.get());
274     sb_service->Initialize();
275     base::MessageLoop::current()->RunUntilIdle();
276
277     // Create a cookiemonster that does not have persistant storage, and replace
278     // the SafeBrowsingService created one with it.
279     net::CookieStore* monster =
280         content::CreateCookieStore(content::CookieStoreConfig());
281     sb_service->url_request_context()->GetURLRequestContext()->
282         set_cookie_store(monster);
283     SetMonster(monster);
284   }
285
286   virtual ~RemoveSafeBrowsingCookieTester() {
287     browser_process_->safe_browsing_service()->ShutDown();
288     base::MessageLoop::current()->RunUntilIdle();
289     browser_process_->SetSafeBrowsingService(NULL);
290   }
291
292  private:
293   TestingBrowserProcess* browser_process_;
294
295   DISALLOW_COPY_AND_ASSIGN(RemoveSafeBrowsingCookieTester);
296 };
297 #endif
298
299 class RemoveChannelIDTester : public net::SSLConfigService::Observer {
300  public:
301   explicit RemoveChannelIDTester(TestingProfile* profile)
302       : ssl_config_changed_count_(0) {
303     channel_id_service_ = profile->GetRequestContext()->
304         GetURLRequestContext()->channel_id_service();
305     ssl_config_service_ = profile->GetSSLConfigService();
306     ssl_config_service_->AddObserver(this);
307   }
308
309   ~RemoveChannelIDTester() override {
310     ssl_config_service_->RemoveObserver(this);
311   }
312
313   int ChannelIDCount() {
314     return channel_id_service_->cert_count();
315   }
316
317   // Add a server bound cert for |server| with specific creation and expiry
318   // times.  The cert and key data will be filled with dummy values.
319   void AddChannelIDWithTimes(const std::string& server_identifier,
320                                    base::Time creation_time,
321                                    base::Time expiration_time) {
322     GetChannelIDStore()->SetChannelID(server_identifier,
323                                       creation_time,
324                                       expiration_time,
325                                       "a",
326                                       "b");
327   }
328
329   // Add a server bound cert for |server|, with the current time as the
330   // creation time.  The cert and key data will be filled with dummy values.
331   void AddChannelID(const std::string& server_identifier) {
332     base::Time now = base::Time::Now();
333     AddChannelIDWithTimes(server_identifier,
334                           now,
335                           now + base::TimeDelta::FromDays(1));
336   }
337
338   void GetChannelIDList(net::ChannelIDStore::ChannelIDList* channel_ids) {
339     GetChannelIDStore()->GetAllChannelIDs(
340         base::Bind(&RemoveChannelIDTester::GetAllChannelIDsCallback,
341                    channel_ids));
342   }
343
344   net::ChannelIDStore* GetChannelIDStore() {
345     return channel_id_service_->GetChannelIDStore();
346   }
347
348   int ssl_config_changed_count() const {
349     return ssl_config_changed_count_;
350   }
351
352   // net::SSLConfigService::Observer implementation:
353   void OnSSLConfigChanged() override { ssl_config_changed_count_++; }
354
355  private:
356   static void GetAllChannelIDsCallback(
357       net::ChannelIDStore::ChannelIDList* dest,
358       const net::ChannelIDStore::ChannelIDList& result) {
359     *dest = result;
360   }
361
362   net::ChannelIDService* channel_id_service_;
363   scoped_refptr<net::SSLConfigService> ssl_config_service_;
364   int ssl_config_changed_count_;
365
366   DISALLOW_COPY_AND_ASSIGN(RemoveChannelIDTester);
367 };
368
369 class RemoveHistoryTester {
370  public:
371   RemoveHistoryTester() : query_url_success_(false), history_service_(NULL) {}
372
373   bool Init(TestingProfile* profile) WARN_UNUSED_RESULT {
374     if (!profile->CreateHistoryService(true, false))
375       return false;
376     history_service_ = HistoryServiceFactory::GetForProfile(
377         profile, Profile::EXPLICIT_ACCESS);
378     return true;
379   }
380
381   // Returns true, if the given URL exists in the history service.
382   bool HistoryContainsURL(const GURL& url) {
383     scoped_refptr<content::MessageLoopRunner> message_loop_runner =
384         new content::MessageLoopRunner;
385     quit_closure_ = message_loop_runner->QuitClosure();
386     history_service_->QueryURL(
387         url,
388         true,
389         base::Bind(&RemoveHistoryTester::SaveResultAndQuit,
390                    base::Unretained(this)),
391         &tracker_);
392     message_loop_runner->Run();
393     return query_url_success_;
394   }
395
396   void AddHistory(const GURL& url, base::Time time) {
397     history_service_->AddPage(url, time, NULL, 0, GURL(),
398         history::RedirectList(), ui::PAGE_TRANSITION_LINK,
399         history::SOURCE_BROWSED, false);
400   }
401
402  private:
403   // Callback for HistoryService::QueryURL.
404   void SaveResultAndQuit(bool success,
405                          const history::URLRow&,
406                          const history::VisitVector&) {
407     query_url_success_ = success;
408     quit_closure_.Run();
409   }
410
411   // For History requests.
412   base::CancelableTaskTracker tracker_;
413   bool query_url_success_;
414   base::Closure quit_closure_;
415
416   // TestingProfile owns the history service; we shouldn't delete it.
417   HistoryService* history_service_;
418
419   DISALLOW_COPY_AND_ASSIGN(RemoveHistoryTester);
420 };
421
422 class RemoveAutofillTester : public autofill::PersonalDataManagerObserver {
423  public:
424   explicit RemoveAutofillTester(TestingProfile* profile)
425       : personal_data_manager_(
426             autofill::PersonalDataManagerFactory::GetForProfile(profile)) {
427     autofill::test::DisableSystemServices(profile->GetPrefs());
428     personal_data_manager_->AddObserver(this);
429   }
430
431   ~RemoveAutofillTester() override {
432     personal_data_manager_->RemoveObserver(this);
433   }
434
435   // Returns true if there are autofill profiles.
436   bool HasProfile() {
437     return !personal_data_manager_->GetProfiles().empty() &&
438            !personal_data_manager_->GetCreditCards().empty();
439   }
440
441   bool HasOrigin(const std::string& origin) {
442     const std::vector<autofill::AutofillProfile*>& profiles =
443         personal_data_manager_->GetProfiles();
444     for (std::vector<autofill::AutofillProfile*>::const_iterator it =
445              profiles.begin();
446          it != profiles.end(); ++it) {
447       if ((*it)->origin() == origin)
448         return true;
449     }
450
451     const std::vector<autofill::CreditCard*>& credit_cards =
452         personal_data_manager_->GetCreditCards();
453     for (std::vector<autofill::CreditCard*>::const_iterator it =
454              credit_cards.begin();
455          it != credit_cards.end(); ++it) {
456       if ((*it)->origin() == origin)
457         return true;
458     }
459
460     return false;
461   }
462
463   // Add two profiles and two credit cards to the database.  In each pair, one
464   // entry has a web origin and the other has a Chrome origin.
465   void AddProfilesAndCards() {
466     std::vector<autofill::AutofillProfile> profiles;
467     autofill::AutofillProfile profile;
468     profile.set_guid(base::GenerateGUID());
469     profile.set_origin(kWebOrigin);
470     profile.SetRawInfo(autofill::NAME_FIRST, base::ASCIIToUTF16("Bob"));
471     profile.SetRawInfo(autofill::NAME_LAST, base::ASCIIToUTF16("Smith"));
472     profile.SetRawInfo(autofill::ADDRESS_HOME_ZIP, base::ASCIIToUTF16("94043"));
473     profile.SetRawInfo(autofill::EMAIL_ADDRESS,
474                        base::ASCIIToUTF16("sue@example.com"));
475     profile.SetRawInfo(autofill::COMPANY_NAME, base::ASCIIToUTF16("Company X"));
476     profiles.push_back(profile);
477
478     profile.set_guid(base::GenerateGUID());
479     profile.set_origin(kChromeOrigin);
480     profiles.push_back(profile);
481
482     personal_data_manager_->SetProfiles(&profiles);
483     base::MessageLoop::current()->Run();
484
485     std::vector<autofill::CreditCard> cards;
486     autofill::CreditCard card;
487     card.set_guid(base::GenerateGUID());
488     card.set_origin(kWebOrigin);
489     card.SetRawInfo(autofill::CREDIT_CARD_NUMBER,
490                     base::ASCIIToUTF16("1234-5678-9012-3456"));
491     cards.push_back(card);
492
493     card.set_guid(base::GenerateGUID());
494     card.set_origin(kChromeOrigin);
495     cards.push_back(card);
496
497     personal_data_manager_->SetCreditCards(&cards);
498     base::MessageLoop::current()->Run();
499   }
500
501  private:
502   void OnPersonalDataChanged() override {
503     base::MessageLoop::current()->Quit();
504   }
505
506   autofill::PersonalDataManager* personal_data_manager_;
507   DISALLOW_COPY_AND_ASSIGN(RemoveAutofillTester);
508 };
509
510 class RemoveLocalStorageTester {
511  public:
512   explicit RemoveLocalStorageTester(TestingProfile* profile)
513       : profile_(profile), dom_storage_context_(NULL) {
514     dom_storage_context_ =
515         content::BrowserContext::GetDefaultStoragePartition(profile)->
516             GetDOMStorageContext();
517   }
518
519   // Returns true, if the given origin URL exists.
520   bool DOMStorageExistsForOrigin(const GURL& origin) {
521     scoped_refptr<content::MessageLoopRunner> message_loop_runner =
522         new content::MessageLoopRunner;
523     quit_closure_ = message_loop_runner->QuitClosure();
524     GetLocalStorageUsage();
525     message_loop_runner->Run();
526     for (size_t i = 0; i < infos_.size(); ++i) {
527       if (origin == infos_[i].origin)
528         return true;
529     }
530     return false;
531   }
532
533   void AddDOMStorageTestData() {
534     // Note: This test depends on details of how the dom_storage library
535     // stores data in the host file system.
536     base::FilePath storage_path =
537         profile_->GetPath().AppendASCII("Local Storage");
538     base::CreateDirectory(storage_path);
539
540     // Write some files.
541     base::WriteFile(storage_path.Append(kDomStorageOrigin1), NULL, 0);
542     base::WriteFile(storage_path.Append(kDomStorageOrigin2), NULL, 0);
543     base::WriteFile(storage_path.Append(kDomStorageOrigin3), NULL, 0);
544     base::WriteFile(storage_path.Append(kDomStorageExt), NULL, 0);
545
546     // Tweak their dates.
547     base::Time now = base::Time::Now();
548     base::TouchFile(storage_path.Append(kDomStorageOrigin1), now, now);
549
550     base::Time one_day_ago = now - base::TimeDelta::FromDays(1);
551     base::TouchFile(storage_path.Append(kDomStorageOrigin2),
552                     one_day_ago, one_day_ago);
553
554     base::Time sixty_days_ago = now - base::TimeDelta::FromDays(60);
555     base::TouchFile(storage_path.Append(kDomStorageOrigin3),
556                     sixty_days_ago, sixty_days_ago);
557
558     base::TouchFile(storage_path.Append(kDomStorageExt), now, now);
559   }
560
561  private:
562   void GetLocalStorageUsage() {
563     dom_storage_context_->GetLocalStorageUsage(
564         base::Bind(&RemoveLocalStorageTester::OnGotLocalStorageUsage,
565                    base::Unretained(this)));
566   }
567   void OnGotLocalStorageUsage(
568       const std::vector<content::LocalStorageUsageInfo>& infos) {
569     infos_ = infos;
570     quit_closure_.Run();
571   }
572
573   // We don't own these pointers.
574   TestingProfile* profile_;
575   content::DOMStorageContext* dom_storage_context_;
576
577   std::vector<content::LocalStorageUsageInfo> infos_;
578   base::Closure quit_closure_;
579
580   DISALLOW_COPY_AND_ASSIGN(RemoveLocalStorageTester);
581 };
582
583 class MockDomainReliabilityService : public DomainReliabilityService {
584  public:
585   MockDomainReliabilityService() : clear_count_(0) {}
586
587   ~MockDomainReliabilityService() override {}
588
589   scoped_ptr<DomainReliabilityMonitor> CreateMonitor(
590       scoped_refptr<base::SingleThreadTaskRunner> network_task_runner)
591       override {
592     NOTREACHED();
593     return scoped_ptr<DomainReliabilityMonitor>();
594   }
595
596   void ClearBrowsingData(DomainReliabilityClearMode clear_mode,
597                          const base::Closure& callback) override {
598     clear_count_++;
599     last_clear_mode_ = clear_mode;
600     callback.Run();
601   }
602
603   void GetWebUIData(const base::Callback<void(scoped_ptr<base::Value>)>&
604                         callback) const override {
605     NOTREACHED();
606   }
607
608   int clear_count() const { return clear_count_; }
609
610   DomainReliabilityClearMode last_clear_mode() const {
611     return last_clear_mode_;
612   }
613
614  private:
615   unsigned clear_count_;
616   DomainReliabilityClearMode last_clear_mode_;
617 };
618
619 struct TestingDomainReliabilityServiceFactoryUserData
620     : public base::SupportsUserData::Data {
621   TestingDomainReliabilityServiceFactoryUserData(
622       content::BrowserContext* context,
623       MockDomainReliabilityService* service)
624       : context(context),
625         service(service),
626         attached(false) {}
627   ~TestingDomainReliabilityServiceFactoryUserData() override {}
628
629   content::BrowserContext* const context;
630   MockDomainReliabilityService* const service;
631   bool attached;
632
633   static const void* kKey;
634 };
635
636 // static
637 const void* TestingDomainReliabilityServiceFactoryUserData::kKey =
638     &TestingDomainReliabilityServiceFactoryUserData::kKey;
639
640 KeyedService* TestingDomainReliabilityServiceFactoryFunction(
641     content::BrowserContext* context) {
642   const void* kKey = TestingDomainReliabilityServiceFactoryUserData::kKey;
643
644   TestingDomainReliabilityServiceFactoryUserData* data =
645       static_cast<TestingDomainReliabilityServiceFactoryUserData*>(
646           context->GetUserData(kKey));
647   EXPECT_TRUE(data);
648   EXPECT_EQ(data->context, context);
649   EXPECT_FALSE(data->attached);
650
651   data->attached = true;
652   return data->service;
653 }
654
655 class ClearDomainReliabilityTester {
656  public:
657   explicit ClearDomainReliabilityTester(TestingProfile* profile) :
658       profile_(profile),
659       mock_service_(new MockDomainReliabilityService()) {
660     AttachService();
661   }
662
663   unsigned clear_count() { return mock_service_->clear_count(); }
664
665   DomainReliabilityClearMode last_clear_mode() {
666     return mock_service_->last_clear_mode();
667   }
668
669  private:
670   void AttachService() {
671     const void* kKey = TestingDomainReliabilityServiceFactoryUserData::kKey;
672
673     // Attach kludgey UserData struct to profile.
674     TestingDomainReliabilityServiceFactoryUserData* data =
675         new TestingDomainReliabilityServiceFactoryUserData(profile_,
676                                                            mock_service_);
677     EXPECT_FALSE(profile_->GetUserData(kKey));
678     profile_->SetUserData(kKey, data);
679
680     // Set and use factory that will attach service stuffed in kludgey struct.
681     DomainReliabilityServiceFactory::GetInstance()->SetTestingFactoryAndUse(
682         profile_,
683         &TestingDomainReliabilityServiceFactoryFunction);
684
685     // Verify and detach kludgey struct.
686     EXPECT_EQ(data, profile_->GetUserData(kKey));
687     EXPECT_TRUE(data->attached);
688     profile_->RemoveUserData(kKey);
689   }
690
691   TestingProfile* profile_;
692   MockDomainReliabilityService* mock_service_;
693 };
694
695 // Test Class ----------------------------------------------------------------
696
697 class BrowsingDataRemoverTest : public testing::Test,
698                                 public content::NotificationObserver {
699  public:
700   BrowsingDataRemoverTest()
701       : profile_(new TestingProfile()) {
702     registrar_.Add(this, chrome::NOTIFICATION_BROWSING_DATA_REMOVED,
703                    content::Source<Profile>(profile_.get()));
704   }
705
706   ~BrowsingDataRemoverTest() override {}
707
708   void TearDown() override {
709 #if defined(ENABLE_EXTENSIONS)
710     mock_policy_ = NULL;
711 #endif
712
713     // TestingProfile contains a DOMStorageContext.  BrowserContext's destructor
714     // posts a message to the WEBKIT thread to delete some of its member
715     // variables. We need to ensure that the profile is destroyed, and that
716     // the message loop is cleared out, before destroying the threads and loop.
717     // Otherwise we leak memory.
718     profile_.reset();
719     base::MessageLoop::current()->RunUntilIdle();
720   }
721
722   void BlockUntilBrowsingDataRemoved(BrowsingDataRemover::TimePeriod period,
723                                      int remove_mask,
724                                      bool include_protected_origins) {
725     BrowsingDataRemover* remover = BrowsingDataRemover::CreateForPeriod(
726         profile_.get(), period);
727
728     TestStoragePartition storage_partition;
729     remover->OverrideStoragePartitionForTesting(&storage_partition);
730
731     called_with_details_.reset(new BrowsingDataRemover::NotificationDetails());
732
733     // BrowsingDataRemover deletes itself when it completes.
734     int origin_set_mask = BrowsingDataHelper::UNPROTECTED_WEB;
735     if (include_protected_origins)
736       origin_set_mask |= BrowsingDataHelper::PROTECTED_WEB;
737
738     BrowsingDataRemoverCompletionObserver completion_observer(remover);
739     remover->Remove(remove_mask, origin_set_mask);
740     completion_observer.BlockUntilCompletion();
741
742     // Save so we can verify later.
743     storage_partition_removal_data_ =
744         storage_partition.GetStoragePartitionRemovalData();
745   }
746
747   void BlockUntilOriginDataRemoved(BrowsingDataRemover::TimePeriod period,
748                                    int remove_mask,
749                                    const GURL& remove_origin) {
750     BrowsingDataRemover* remover = BrowsingDataRemover::CreateForPeriod(
751         profile_.get(), period);
752     TestStoragePartition storage_partition;
753     remover->OverrideStoragePartitionForTesting(&storage_partition);
754
755     called_with_details_.reset(new BrowsingDataRemover::NotificationDetails());
756
757     // BrowsingDataRemover deletes itself when it completes.
758     BrowsingDataRemoverCompletionObserver completion_observer(remover);
759     remover->RemoveImpl(remove_mask, remove_origin,
760         BrowsingDataHelper::UNPROTECTED_WEB);
761     completion_observer.BlockUntilCompletion();
762
763     // Save so we can verify later.
764     storage_partition_removal_data_ =
765         storage_partition.GetStoragePartitionRemovalData();
766   }
767
768   TestingProfile* GetProfile() {
769     return profile_.get();
770   }
771
772   base::Time GetBeginTime() {
773     return called_with_details_->removal_begin;
774   }
775
776   int GetRemovalMask() {
777     return called_with_details_->removal_mask;
778   }
779
780   int GetOriginSetMask() {
781     return called_with_details_->origin_set_mask;
782   }
783
784   StoragePartitionRemovalData GetStoragePartitionRemovalData() {
785     return storage_partition_removal_data_;
786   }
787
788   // content::NotificationObserver implementation.
789   void Observe(int type,
790                const content::NotificationSource& source,
791                const content::NotificationDetails& details) override {
792     DCHECK_EQ(type, chrome::NOTIFICATION_BROWSING_DATA_REMOVED);
793
794     // We're not taking ownership of the details object, but storing a copy of
795     // it locally.
796     called_with_details_.reset(new BrowsingDataRemover::NotificationDetails(
797         *content::Details<BrowsingDataRemover::NotificationDetails>(
798             details).ptr()));
799
800     registrar_.RemoveAll();
801   }
802
803   MockExtensionSpecialStoragePolicy* CreateMockPolicy() {
804 #if defined(ENABLE_EXTENSIONS)
805     mock_policy_ = new MockExtensionSpecialStoragePolicy;
806     return mock_policy_.get();
807 #else
808     NOTREACHED();
809     return NULL;
810 #endif
811   }
812
813   storage::SpecialStoragePolicy* mock_policy() {
814 #if defined(ENABLE_EXTENSIONS)
815     return mock_policy_.get();
816 #else
817     return NULL;
818 #endif
819   }
820
821   // If |kOrigin1| is protected when extensions are enabled, the expected
822   // result for tests where the OriginMatcherFunction result is variable.
823   bool ShouldRemoveForProtectedOriginOne() const {
824 #if defined(ENABLE_EXTENSIONS)
825     return false;
826 #else
827     return true;
828 #endif
829   }
830
831  protected:
832   scoped_ptr<BrowsingDataRemover::NotificationDetails> called_with_details_;
833
834  private:
835   content::NotificationRegistrar registrar_;
836
837   content::TestBrowserThreadBundle thread_bundle_;
838   scoped_ptr<TestingProfile> profile_;
839
840   StoragePartitionRemovalData storage_partition_removal_data_;
841
842 #if defined(ENABLE_EXTENSIONS)
843   scoped_refptr<MockExtensionSpecialStoragePolicy> mock_policy_;
844 #endif
845
846   DISALLOW_COPY_AND_ASSIGN(BrowsingDataRemoverTest);
847 };
848
849 // Tests ---------------------------------------------------------------------
850
851 TEST_F(BrowsingDataRemoverTest, RemoveCookieForever) {
852   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
853                                 BrowsingDataRemover::REMOVE_COOKIES,
854                                 false);
855
856   EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
857   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
858
859   // Verify that storage partition was instructed to remove the cookies.
860   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
861   EXPECT_EQ(removal_data.remove_mask,
862             StoragePartition::REMOVE_DATA_MASK_COOKIES);
863   EXPECT_EQ(removal_data.quota_storage_remove_mask,
864             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
865   EXPECT_TRUE(removal_data.remove_origin.is_empty());
866   EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
867 }
868
869 TEST_F(BrowsingDataRemoverTest, RemoveCookieLastHour) {
870   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_HOUR,
871                                 BrowsingDataRemover::REMOVE_COOKIES,
872                                 false);
873
874   EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
875   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
876
877   // Verify that storage partition was instructed to remove the cookies.
878   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
879   EXPECT_EQ(removal_data.remove_mask,
880             StoragePartition::REMOVE_DATA_MASK_COOKIES);
881   // Removing with time period other than EVERYTHING should not clear
882   // persistent storage data.
883   EXPECT_EQ(removal_data.quota_storage_remove_mask,
884             ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT);
885   EXPECT_TRUE(removal_data.remove_origin.is_empty());
886   EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
887 }
888
889 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
890 TEST_F(BrowsingDataRemoverTest, RemoveSafeBrowsingCookieForever) {
891   RemoveSafeBrowsingCookieTester tester;
892
893   tester.AddCookie();
894   ASSERT_TRUE(tester.ContainsCookie());
895
896   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
897       BrowsingDataRemover::REMOVE_COOKIES, false);
898
899   EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
900   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
901   EXPECT_FALSE(tester.ContainsCookie());
902 }
903
904 TEST_F(BrowsingDataRemoverTest, RemoveSafeBrowsingCookieLastHour) {
905   RemoveSafeBrowsingCookieTester tester;
906
907   tester.AddCookie();
908   ASSERT_TRUE(tester.ContainsCookie());
909
910   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_HOUR,
911       BrowsingDataRemover::REMOVE_COOKIES, false);
912
913   EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
914   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
915   // Removing with time period other than EVERYTHING should not clear safe
916   // browsing cookies.
917   EXPECT_TRUE(tester.ContainsCookie());
918 }
919 #endif
920
921 TEST_F(BrowsingDataRemoverTest, RemoveChannelIDForever) {
922   RemoveChannelIDTester tester(GetProfile());
923
924   tester.AddChannelID(kTestOrigin1);
925   EXPECT_EQ(0, tester.ssl_config_changed_count());
926   EXPECT_EQ(1, tester.ChannelIDCount());
927
928   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
929       BrowsingDataRemover::REMOVE_CHANNEL_IDS, false);
930
931   EXPECT_EQ(BrowsingDataRemover::REMOVE_CHANNEL_IDS, GetRemovalMask());
932   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
933   EXPECT_EQ(1, tester.ssl_config_changed_count());
934   EXPECT_EQ(0, tester.ChannelIDCount());
935 }
936
937 TEST_F(BrowsingDataRemoverTest, RemoveChannelIDLastHour) {
938   RemoveChannelIDTester tester(GetProfile());
939
940   base::Time now = base::Time::Now();
941   tester.AddChannelID(kTestOrigin1);
942   tester.AddChannelIDWithTimes(kTestOrigin2,
943                                      now - base::TimeDelta::FromHours(2),
944                                      now);
945   EXPECT_EQ(0, tester.ssl_config_changed_count());
946   EXPECT_EQ(2, tester.ChannelIDCount());
947
948   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_HOUR,
949       BrowsingDataRemover::REMOVE_CHANNEL_IDS, false);
950
951   EXPECT_EQ(BrowsingDataRemover::REMOVE_CHANNEL_IDS, GetRemovalMask());
952   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
953   EXPECT_EQ(1, tester.ssl_config_changed_count());
954   ASSERT_EQ(1, tester.ChannelIDCount());
955   net::ChannelIDStore::ChannelIDList channel_ids;
956   tester.GetChannelIDList(&channel_ids);
957   ASSERT_EQ(1U, channel_ids.size());
958   EXPECT_EQ(kTestOrigin2, channel_ids.front().server_identifier());
959 }
960
961 TEST_F(BrowsingDataRemoverTest, RemoveUnprotectedLocalStorageForever) {
962 #if defined(ENABLE_EXTENSIONS)
963   MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
964   // Protect kOrigin1.
965   policy->AddProtected(kOrigin1.GetOrigin());
966 #endif
967
968   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
969                                 BrowsingDataRemover::REMOVE_LOCAL_STORAGE,
970                                 false);
971
972   EXPECT_EQ(BrowsingDataRemover::REMOVE_LOCAL_STORAGE, GetRemovalMask());
973   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
974
975   // Verify that storage partition was instructed to remove the data correctly.
976   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
977   EXPECT_EQ(removal_data.remove_mask,
978             StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE);
979   EXPECT_EQ(removal_data.quota_storage_remove_mask,
980             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
981   EXPECT_TRUE(removal_data.remove_origin.is_empty());
982   EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
983
984   // Check origin matcher.
985   EXPECT_EQ(ShouldRemoveForProtectedOriginOne(),
986             removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
987   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
988   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
989   EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
990 }
991
992 TEST_F(BrowsingDataRemoverTest, RemoveProtectedLocalStorageForever) {
993 #if defined(ENABLE_EXTENSIONS)
994   // Protect kOrigin1.
995   MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
996   policy->AddProtected(kOrigin1.GetOrigin());
997 #endif
998
999   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1000                                 BrowsingDataRemover::REMOVE_LOCAL_STORAGE,
1001                                 true);
1002
1003   EXPECT_EQ(BrowsingDataRemover::REMOVE_LOCAL_STORAGE, GetRemovalMask());
1004   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB |
1005             BrowsingDataHelper::PROTECTED_WEB, GetOriginSetMask());
1006
1007   // Verify that storage partition was instructed to remove the data correctly.
1008   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1009   EXPECT_EQ(removal_data.remove_mask,
1010             StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE);
1011   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1012             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1013   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1014   EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1015
1016   // Check origin matcher all http origin will match since we specified
1017   // both protected and unprotected.
1018   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1019   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1020   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1021   EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
1022 }
1023
1024 TEST_F(BrowsingDataRemoverTest, RemoveLocalStorageForLastWeek) {
1025 #if defined(ENABLE_EXTENSIONS)
1026   CreateMockPolicy();
1027 #endif
1028
1029   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_WEEK,
1030                                 BrowsingDataRemover::REMOVE_LOCAL_STORAGE,
1031                                 false);
1032
1033   EXPECT_EQ(BrowsingDataRemover::REMOVE_LOCAL_STORAGE, GetRemovalMask());
1034   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1035
1036   // Verify that storage partition was instructed to remove the data correctly.
1037   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1038   EXPECT_EQ(removal_data.remove_mask,
1039             StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE);
1040   // Persistent storage won't be deleted.
1041   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1042             ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT);
1043   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1044   EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1045
1046   // Check origin matcher.
1047   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1048   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1049   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1050   EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
1051 }
1052
1053 TEST_F(BrowsingDataRemoverTest, RemoveHistoryForever) {
1054   RemoveHistoryTester tester;
1055   ASSERT_TRUE(tester.Init(GetProfile()));
1056
1057   tester.AddHistory(kOrigin1, base::Time::Now());
1058   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1059
1060   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1061       BrowsingDataRemover::REMOVE_HISTORY, false);
1062
1063   EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1064   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1065   EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
1066 }
1067
1068 TEST_F(BrowsingDataRemoverTest, RemoveHistoryForLastHour) {
1069   RemoveHistoryTester tester;
1070   ASSERT_TRUE(tester.Init(GetProfile()));
1071
1072   base::Time two_hours_ago = base::Time::Now() - base::TimeDelta::FromHours(2);
1073
1074   tester.AddHistory(kOrigin1, base::Time::Now());
1075   tester.AddHistory(kOrigin2, two_hours_ago);
1076   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1077   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
1078
1079   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_HOUR,
1080       BrowsingDataRemover::REMOVE_HISTORY, false);
1081
1082   EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1083   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1084   EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
1085   EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
1086 }
1087
1088 // This should crash (DCHECK) in Debug, but death tests don't work properly
1089 // here.
1090 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
1091 TEST_F(BrowsingDataRemoverTest, RemoveHistoryProhibited) {
1092   RemoveHistoryTester tester;
1093   ASSERT_TRUE(tester.Init(GetProfile()));
1094   PrefService* prefs = GetProfile()->GetPrefs();
1095   prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
1096
1097   base::Time two_hours_ago = base::Time::Now() - base::TimeDelta::FromHours(2);
1098
1099   tester.AddHistory(kOrigin1, base::Time::Now());
1100   tester.AddHistory(kOrigin2, two_hours_ago);
1101   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1102   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
1103
1104   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_HOUR,
1105       BrowsingDataRemover::REMOVE_HISTORY, false);
1106   EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1107   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1108
1109   // Nothing should have been deleted.
1110   EXPECT_TRUE(tester.HistoryContainsURL(kOrigin1));
1111   EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
1112 }
1113 #endif
1114
1115 TEST_F(BrowsingDataRemoverTest, RemoveMultipleTypes) {
1116   // Add some history.
1117   RemoveHistoryTester history_tester;
1118   ASSERT_TRUE(history_tester.Init(GetProfile()));
1119   history_tester.AddHistory(kOrigin1, base::Time::Now());
1120   ASSERT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
1121
1122   int removal_mask = BrowsingDataRemover::REMOVE_HISTORY |
1123                      BrowsingDataRemover::REMOVE_COOKIES;
1124
1125   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1126       removal_mask, false);
1127
1128   EXPECT_EQ(removal_mask, GetRemovalMask());
1129   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1130   EXPECT_FALSE(history_tester.HistoryContainsURL(kOrigin1));
1131
1132   // The cookie would be deleted throught the StorageParition, check if the
1133   // partition was requested to remove cookie.
1134   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1135   EXPECT_EQ(removal_data.remove_mask,
1136             StoragePartition::REMOVE_DATA_MASK_COOKIES);
1137   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1138             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1139 }
1140
1141 // This should crash (DCHECK) in Debug, but death tests don't work properly
1142 // here.
1143 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
1144 TEST_F(BrowsingDataRemoverTest, RemoveMultipleTypesHistoryProhibited) {
1145   PrefService* prefs = GetProfile()->GetPrefs();
1146   prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
1147
1148   // Add some history.
1149   RemoveHistoryTester history_tester;
1150   ASSERT_TRUE(history_tester.Init(GetProfile()));
1151   history_tester.AddHistory(kOrigin1, base::Time::Now());
1152   ASSERT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
1153
1154   int removal_mask = BrowsingDataRemover::REMOVE_HISTORY |
1155                      BrowsingDataRemover::REMOVE_COOKIES;
1156
1157   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_HOUR,
1158                                 removal_mask, false);
1159   EXPECT_EQ(removal_mask, GetRemovalMask());
1160   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1161
1162   // 1/2. History should remain.
1163   EXPECT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
1164
1165   // 2/2. The cookie(s) would be deleted throught the StorageParition, check if
1166   // the partition was requested to remove cookie.
1167   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1168   EXPECT_EQ(removal_data.remove_mask,
1169             StoragePartition::REMOVE_DATA_MASK_COOKIES);
1170   // Persistent storage won't be deleted, since EVERYTHING was not specified.
1171   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1172             ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT);
1173 }
1174 #endif
1175
1176 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverBoth) {
1177   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1178                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1179                                 BrowsingDataRemover::REMOVE_WEBSQL |
1180                                 BrowsingDataRemover::REMOVE_APPCACHE |
1181                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1182                                 BrowsingDataRemover::REMOVE_INDEXEDDB,
1183                                 false);
1184
1185   EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1186       BrowsingDataRemover::REMOVE_WEBSQL |
1187       BrowsingDataRemover::REMOVE_APPCACHE |
1188       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1189       BrowsingDataRemover::REMOVE_INDEXEDDB, GetRemovalMask());
1190   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1191
1192   // Verify storage partition related stuffs.
1193   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1194   EXPECT_EQ(removal_data.remove_mask,
1195             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1196                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1197                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1198                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1199                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1200   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1201             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1202   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1203 }
1204
1205 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverOnlyTemporary) {
1206 #if defined(ENABLE_EXTENSIONS)
1207   CreateMockPolicy();
1208 #endif
1209
1210   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1211                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1212                                 BrowsingDataRemover::REMOVE_WEBSQL |
1213                                 BrowsingDataRemover::REMOVE_APPCACHE |
1214                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1215                                 BrowsingDataRemover::REMOVE_INDEXEDDB,
1216                                 false);
1217
1218   EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1219       BrowsingDataRemover::REMOVE_WEBSQL |
1220       BrowsingDataRemover::REMOVE_APPCACHE |
1221       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1222       BrowsingDataRemover::REMOVE_INDEXEDDB, GetRemovalMask());
1223   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1224
1225   // Verify storage partition related stuffs.
1226   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1227
1228   EXPECT_EQ(removal_data.remove_mask,
1229             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1230                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1231                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1232                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1233                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1234   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1235             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1236   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1237
1238   // Check that all related origin data would be removed, that is, origin
1239   // matcher would match these origin.
1240   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1241   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1242   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1243 }
1244
1245 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverOnlyPersistent) {
1246 #if defined(ENABLE_EXTENSIONS)
1247   CreateMockPolicy();
1248 #endif
1249
1250   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1251                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1252                                 BrowsingDataRemover::REMOVE_WEBSQL |
1253                                 BrowsingDataRemover::REMOVE_APPCACHE |
1254                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1255                                 BrowsingDataRemover::REMOVE_INDEXEDDB,
1256                                 false);
1257
1258   EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1259       BrowsingDataRemover::REMOVE_WEBSQL |
1260       BrowsingDataRemover::REMOVE_APPCACHE |
1261       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1262       BrowsingDataRemover::REMOVE_INDEXEDDB, GetRemovalMask());
1263   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1264
1265   // Verify storage partition related stuffs.
1266   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1267
1268   EXPECT_EQ(removal_data.remove_mask,
1269             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1270                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1271                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1272                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1273                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1274   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1275             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1276   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1277
1278   // Check that all related origin data would be removed, that is, origin
1279   // matcher would match these origin.
1280   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1281   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1282   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1283 }
1284
1285 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverNeither) {
1286 #if defined(ENABLE_EXTENSIONS)
1287   CreateMockPolicy();
1288 #endif
1289
1290
1291   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1292                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1293                                 BrowsingDataRemover::REMOVE_WEBSQL |
1294                                 BrowsingDataRemover::REMOVE_APPCACHE |
1295                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1296                                 BrowsingDataRemover::REMOVE_INDEXEDDB,
1297                                 false);
1298
1299   EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1300       BrowsingDataRemover::REMOVE_WEBSQL |
1301       BrowsingDataRemover::REMOVE_APPCACHE |
1302       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1303       BrowsingDataRemover::REMOVE_INDEXEDDB, GetRemovalMask());
1304   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1305
1306   // Verify storage partition related stuffs.
1307   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1308
1309   EXPECT_EQ(removal_data.remove_mask,
1310             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1311                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1312                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1313                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1314                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1315   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1316             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1317   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1318
1319   // Check that all related origin data would be removed, that is, origin
1320   // matcher would match these origin.
1321   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1322   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1323   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1324 }
1325
1326 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForeverSpecificOrigin) {
1327   // Remove Origin 1.
1328   BlockUntilOriginDataRemoved(BrowsingDataRemover::EVERYTHING,
1329                               BrowsingDataRemover::REMOVE_APPCACHE |
1330                               BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1331                               BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1332                               BrowsingDataRemover::REMOVE_INDEXEDDB |
1333                               BrowsingDataRemover::REMOVE_WEBSQL,
1334                               kOrigin1);
1335
1336   EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
1337       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1338       BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1339       BrowsingDataRemover::REMOVE_INDEXEDDB |
1340       BrowsingDataRemover::REMOVE_WEBSQL, GetRemovalMask());
1341   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1342
1343   // Verify storage partition related stuffs.
1344   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1345
1346   EXPECT_EQ(removal_data.remove_mask,
1347             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1348                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1349                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1350                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1351                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1352   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1353             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1354   EXPECT_EQ(removal_data.remove_origin, kOrigin1);
1355 }
1356
1357 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForLastHour) {
1358   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_HOUR,
1359                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1360                                 BrowsingDataRemover::REMOVE_WEBSQL |
1361                                 BrowsingDataRemover::REMOVE_APPCACHE |
1362                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1363                                 BrowsingDataRemover::REMOVE_INDEXEDDB,
1364                                 false);
1365
1366   EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1367       BrowsingDataRemover::REMOVE_WEBSQL |
1368       BrowsingDataRemover::REMOVE_APPCACHE |
1369       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1370       BrowsingDataRemover::REMOVE_INDEXEDDB, GetRemovalMask());
1371   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1372
1373   // Verify storage partition related stuffs.
1374   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1375
1376   EXPECT_EQ(removal_data.remove_mask,
1377             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1378                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1379                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1380                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1381                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1382
1383   // Persistent data would be left out since we are not removing from
1384   // beginning of time.
1385   uint32 expected_quota_mask =
1386       ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
1387   EXPECT_EQ(removal_data.quota_storage_remove_mask, expected_quota_mask);
1388   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1389   // Check removal begin time.
1390   EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1391 }
1392
1393 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedDataForLastWeek) {
1394   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::LAST_WEEK,
1395                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1396                                 BrowsingDataRemover::REMOVE_WEBSQL |
1397                                 BrowsingDataRemover::REMOVE_APPCACHE |
1398                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1399                                 BrowsingDataRemover::REMOVE_INDEXEDDB,
1400                                 false);
1401
1402   EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1403       BrowsingDataRemover::REMOVE_WEBSQL |
1404       BrowsingDataRemover::REMOVE_APPCACHE |
1405       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1406       BrowsingDataRemover::REMOVE_INDEXEDDB, GetRemovalMask());
1407   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1408
1409   // Verify storage partition related stuffs.
1410   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1411
1412   EXPECT_EQ(removal_data.remove_mask,
1413             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1414                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1415                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1416                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1417                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1418
1419   // Persistent data would be left out since we are not removing from
1420   // beginning of time.
1421   uint32 expected_quota_mask =
1422       ~StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
1423   EXPECT_EQ(removal_data.quota_storage_remove_mask, expected_quota_mask);
1424   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1425   // Check removal begin time.
1426   EXPECT_EQ(removal_data.remove_begin, GetBeginTime());
1427 }
1428
1429 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedUnprotectedOrigins) {
1430 #if defined(ENABLE_EXTENSIONS)
1431   MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
1432   // Protect kOrigin1.
1433   policy->AddProtected(kOrigin1.GetOrigin());
1434 #endif
1435
1436   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1437                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1438                                 BrowsingDataRemover::REMOVE_WEBSQL |
1439                                 BrowsingDataRemover::REMOVE_APPCACHE |
1440                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1441                                 BrowsingDataRemover::REMOVE_INDEXEDDB,
1442                                 false);
1443
1444   EXPECT_EQ(BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1445       BrowsingDataRemover::REMOVE_WEBSQL |
1446       BrowsingDataRemover::REMOVE_APPCACHE |
1447       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1448       BrowsingDataRemover::REMOVE_INDEXEDDB, GetRemovalMask());
1449   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1450
1451   // Verify storage partition related stuffs.
1452   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1453
1454   EXPECT_EQ(removal_data.remove_mask,
1455             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1456                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1457                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1458                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1459                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1460   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1461             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1462   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1463
1464   // Check OriginMatcherFunction.
1465   EXPECT_EQ(ShouldRemoveForProtectedOriginOne(),
1466             removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1467   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1468   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1469 }
1470
1471 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedProtectedSpecificOrigin) {
1472 #if defined(ENABLE_EXTENSIONS)
1473   MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
1474   // Protect kOrigin1.
1475   policy->AddProtected(kOrigin1.GetOrigin());
1476 #endif
1477
1478   // Try to remove kOrigin1. Expect failure.
1479   BlockUntilOriginDataRemoved(BrowsingDataRemover::EVERYTHING,
1480                               BrowsingDataRemover::REMOVE_APPCACHE |
1481                               BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1482                               BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1483                               BrowsingDataRemover::REMOVE_INDEXEDDB |
1484                               BrowsingDataRemover::REMOVE_WEBSQL,
1485                               kOrigin1);
1486
1487   EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
1488       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1489       BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1490       BrowsingDataRemover::REMOVE_INDEXEDDB |
1491       BrowsingDataRemover::REMOVE_WEBSQL, GetRemovalMask());
1492   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1493
1494   // Verify storage partition related stuffs.
1495   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1496
1497   EXPECT_EQ(removal_data.remove_mask,
1498             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1499                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1500                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1501                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1502                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1503   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1504             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1505   EXPECT_EQ(removal_data.remove_origin, kOrigin1);
1506
1507   // Check OriginMatcherFunction.
1508   EXPECT_EQ(ShouldRemoveForProtectedOriginOne(),
1509             removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1510   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1511   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1512 }
1513
1514 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedProtectedOrigins) {
1515 #if defined(ENABLE_EXTENSIONS)
1516   MockExtensionSpecialStoragePolicy* policy = CreateMockPolicy();
1517   // Protect kOrigin1.
1518   policy->AddProtected(kOrigin1.GetOrigin());
1519 #endif
1520
1521   // Try to remove kOrigin1. Expect success.
1522   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1523                                 BrowsingDataRemover::REMOVE_APPCACHE |
1524                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1525                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1526                                 BrowsingDataRemover::REMOVE_INDEXEDDB |
1527                                 BrowsingDataRemover::REMOVE_WEBSQL,
1528                                 true);
1529
1530   EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
1531       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1532       BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1533       BrowsingDataRemover::REMOVE_INDEXEDDB |
1534       BrowsingDataRemover::REMOVE_WEBSQL, GetRemovalMask());
1535   EXPECT_EQ(BrowsingDataHelper::PROTECTED_WEB |
1536       BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1537
1538   // Verify storage partition related stuffs.
1539   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1540
1541   EXPECT_EQ(removal_data.remove_mask,
1542             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1543                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1544                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1545                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1546                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1547   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1548             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1549   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1550
1551   // Check OriginMatcherFunction, |kOrigin1| would match mask since we
1552   // would have 'protected' specified in origin_set_mask.
1553   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin1, mock_policy()));
1554   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin2, mock_policy()));
1555   EXPECT_TRUE(removal_data.origin_matcher.Run(kOrigin3, mock_policy()));
1556 }
1557
1558 TEST_F(BrowsingDataRemoverTest, RemoveQuotaManagedIgnoreExtensionsAndDevTools) {
1559 #if defined(ENABLE_EXTENSIONS)
1560   CreateMockPolicy();
1561 #endif
1562
1563   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1564                                 BrowsingDataRemover::REMOVE_APPCACHE |
1565                                 BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1566                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1567                                 BrowsingDataRemover::REMOVE_INDEXEDDB |
1568                                 BrowsingDataRemover::REMOVE_WEBSQL,
1569                                 false);
1570
1571   EXPECT_EQ(BrowsingDataRemover::REMOVE_APPCACHE |
1572       BrowsingDataRemover::REMOVE_SERVICE_WORKERS |
1573       BrowsingDataRemover::REMOVE_FILE_SYSTEMS |
1574       BrowsingDataRemover::REMOVE_INDEXEDDB |
1575       BrowsingDataRemover::REMOVE_WEBSQL, GetRemovalMask());
1576   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1577
1578   // Verify storage partition related stuffs.
1579   StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData();
1580
1581   EXPECT_EQ(removal_data.remove_mask,
1582             StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS |
1583                 StoragePartition::REMOVE_DATA_MASK_WEBSQL |
1584                 StoragePartition::REMOVE_DATA_MASK_APPCACHE |
1585                 StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS |
1586                 StoragePartition::REMOVE_DATA_MASK_INDEXEDDB);
1587   EXPECT_EQ(removal_data.quota_storage_remove_mask,
1588             StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL);
1589   EXPECT_TRUE(removal_data.remove_origin.is_empty());
1590
1591   // Check that extension and devtools data wouldn't be removed, that is,
1592   // origin matcher would not match these origin.
1593   EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginExt, mock_policy()));
1594   EXPECT_FALSE(removal_data.origin_matcher.Run(kOriginDevTools, mock_policy()));
1595 }
1596
1597 TEST_F(BrowsingDataRemoverTest, OriginBasedHistoryRemoval) {
1598   RemoveHistoryTester tester;
1599   ASSERT_TRUE(tester.Init(GetProfile()));
1600
1601   base::Time two_hours_ago = base::Time::Now() - base::TimeDelta::FromHours(2);
1602
1603   tester.AddHistory(kOrigin1, base::Time::Now());
1604   tester.AddHistory(kOrigin2, two_hours_ago);
1605   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1606   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
1607
1608   BlockUntilOriginDataRemoved(BrowsingDataRemover::EVERYTHING,
1609       BrowsingDataRemover::REMOVE_HISTORY, kOrigin2);
1610
1611   EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1612   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1613
1614   // Nothing should have been deleted.
1615   EXPECT_TRUE(tester.HistoryContainsURL(kOrigin1));
1616   EXPECT_FALSE(tester.HistoryContainsURL(kOrigin2));
1617 }
1618
1619 TEST_F(BrowsingDataRemoverTest, OriginAndTimeBasedHistoryRemoval) {
1620   RemoveHistoryTester tester;
1621   ASSERT_TRUE(tester.Init(GetProfile()));
1622
1623   base::Time two_hours_ago = base::Time::Now() - base::TimeDelta::FromHours(2);
1624
1625   tester.AddHistory(kOrigin1, base::Time::Now());
1626   tester.AddHistory(kOrigin2, two_hours_ago);
1627   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
1628   ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
1629
1630   BlockUntilOriginDataRemoved(BrowsingDataRemover::LAST_HOUR,
1631       BrowsingDataRemover::REMOVE_HISTORY, kOrigin2);
1632
1633   EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1634   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1635   EXPECT_TRUE(tester.HistoryContainsURL(kOrigin1));
1636   EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
1637 }
1638
1639 // Verify that clearing autofill form data works.
1640 TEST_F(BrowsingDataRemoverTest, AutofillRemovalLastHour) {
1641   GetProfile()->CreateWebDataService();
1642   RemoveAutofillTester tester(GetProfile());
1643
1644   ASSERT_FALSE(tester.HasProfile());
1645   tester.AddProfilesAndCards();
1646   ASSERT_TRUE(tester.HasProfile());
1647
1648   BlockUntilBrowsingDataRemoved(
1649       BrowsingDataRemover::LAST_HOUR,
1650       BrowsingDataRemover::REMOVE_FORM_DATA, false);
1651
1652   EXPECT_EQ(BrowsingDataRemover::REMOVE_FORM_DATA, GetRemovalMask());
1653   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1654   ASSERT_FALSE(tester.HasProfile());
1655 }
1656
1657 TEST_F(BrowsingDataRemoverTest, AutofillRemovalEverything) {
1658   GetProfile()->CreateWebDataService();
1659   RemoveAutofillTester tester(GetProfile());
1660
1661   ASSERT_FALSE(tester.HasProfile());
1662   tester.AddProfilesAndCards();
1663   ASSERT_TRUE(tester.HasProfile());
1664
1665   BlockUntilBrowsingDataRemoved(
1666       BrowsingDataRemover::EVERYTHING,
1667       BrowsingDataRemover::REMOVE_FORM_DATA, false);
1668
1669   EXPECT_EQ(BrowsingDataRemover::REMOVE_FORM_DATA, GetRemovalMask());
1670   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1671   ASSERT_FALSE(tester.HasProfile());
1672 }
1673
1674 // Verify that clearing autofill form data works.
1675 TEST_F(BrowsingDataRemoverTest, AutofillOriginsRemovedWithHistory) {
1676   GetProfile()->CreateWebDataService();
1677   RemoveAutofillTester tester(GetProfile());
1678
1679   tester.AddProfilesAndCards();
1680   EXPECT_FALSE(tester.HasOrigin(std::string()));
1681   EXPECT_TRUE(tester.HasOrigin(kWebOrigin));
1682   EXPECT_TRUE(tester.HasOrigin(kChromeOrigin));
1683
1684   BlockUntilBrowsingDataRemoved(
1685       BrowsingDataRemover::LAST_HOUR,
1686       BrowsingDataRemover::REMOVE_HISTORY, false);
1687
1688   EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1689   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1690   EXPECT_TRUE(tester.HasOrigin(std::string()));
1691   EXPECT_FALSE(tester.HasOrigin(kWebOrigin));
1692   EXPECT_TRUE(tester.HasOrigin(kChromeOrigin));
1693 }
1694
1695 TEST_F(BrowsingDataRemoverTest, CompletionInhibition) {
1696   // The |completion_inhibitor| on the stack should prevent removal sessions
1697   // from completing until after ContinueToCompletion() is called.
1698   BrowsingDataRemoverCompletionInhibitor completion_inhibitor;
1699
1700   called_with_details_.reset(new BrowsingDataRemover::NotificationDetails());
1701
1702   // BrowsingDataRemover deletes itself when it completes.
1703   BrowsingDataRemover* remover = BrowsingDataRemover::CreateForPeriod(
1704       GetProfile(), BrowsingDataRemover::EVERYTHING);
1705   remover->Remove(BrowsingDataRemover::REMOVE_HISTORY,
1706                   BrowsingDataHelper::UNPROTECTED_WEB);
1707
1708   // Process messages until the inhibitor is notified, and then some, to make
1709   // sure we do not complete asynchronously before ContinueToCompletion() is
1710   // called.
1711   completion_inhibitor.BlockUntilNearCompletion();
1712   base::RunLoop().RunUntilIdle();
1713
1714   // Verify that the completion notification has not yet been broadcasted.
1715   EXPECT_EQ(-1, GetRemovalMask());
1716   EXPECT_EQ(-1, GetOriginSetMask());
1717
1718   // Now run the removal process until completion, and verify that observers are
1719   // now notified, and the notifications is sent out.
1720   BrowsingDataRemoverCompletionObserver completion_observer(remover);
1721   completion_inhibitor.ContinueToCompletion();
1722   completion_observer.BlockUntilCompletion();
1723
1724   EXPECT_EQ(BrowsingDataRemover::REMOVE_HISTORY, GetRemovalMask());
1725   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1726 }
1727
1728 TEST_F(BrowsingDataRemoverTest, ZeroSuggestCacheClear) {
1729   PrefService* prefs = GetProfile()->GetPrefs();
1730   prefs->SetString(prefs::kZeroSuggestCachedResults,
1731                    "[\"\", [\"foo\", \"bar\"]]");
1732   BlockUntilBrowsingDataRemoved(BrowsingDataRemover::EVERYTHING,
1733                                 BrowsingDataRemover::REMOVE_COOKIES,
1734                                 false);
1735
1736   // Expect the prefs to be cleared when cookies are removed.
1737   EXPECT_TRUE(prefs->GetString(prefs::kZeroSuggestCachedResults).empty());
1738   EXPECT_EQ(BrowsingDataRemover::REMOVE_COOKIES, GetRemovalMask());
1739   EXPECT_EQ(BrowsingDataHelper::UNPROTECTED_WEB, GetOriginSetMask());
1740 }
1741
1742 #if defined(OS_CHROMEOS)
1743 TEST_F(BrowsingDataRemoverTest, ContentProtectionPlatformKeysRemoval) {
1744   chromeos::ScopedTestDeviceSettingsService test_device_settings_service;
1745   chromeos::ScopedTestCrosSettings test_cros_settings;
1746   chromeos::MockUserManager* mock_user_manager =
1747       new testing::NiceMock<chromeos::MockUserManager>();
1748   mock_user_manager->SetActiveUser("test@example.com");
1749   chromeos::ScopedUserManagerEnabler user_manager_enabler(mock_user_manager);
1750
1751   scoped_ptr<chromeos::DBusThreadManagerSetter> dbus_setter =
1752       chromeos::DBusThreadManager::GetSetterForTesting();
1753   chromeos::MockCryptohomeClient* cryptohome_client =
1754       new chromeos::MockCryptohomeClient;
1755   dbus_setter->SetCryptohomeClient(
1756       scoped_ptr<chromeos::CryptohomeClient>(cryptohome_client));
1757
1758   // Expect exactly one call.  No calls means no attempt to delete keys and more
1759   // than one call means a significant performance problem.
1760   EXPECT_CALL(*cryptohome_client, TpmAttestationDeleteKeys(_, _, _, _))
1761       .WillOnce(WithArgs<3>(Invoke(FakeDBusCall)));
1762
1763   BlockUntilBrowsingDataRemoved(
1764       BrowsingDataRemover::EVERYTHING,
1765       BrowsingDataRemover::REMOVE_CONTENT_LICENSES, false);
1766
1767   chromeos::DBusThreadManager::Shutdown();
1768 }
1769 #endif
1770
1771 TEST_F(BrowsingDataRemoverTest, DomainReliability_Null) {
1772   ClearDomainReliabilityTester tester(GetProfile());
1773
1774   EXPECT_EQ(0u, tester.clear_count());
1775 }
1776
1777 TEST_F(BrowsingDataRemoverTest, DomainReliability_Beacons) {
1778   ClearDomainReliabilityTester tester(GetProfile());
1779
1780   BlockUntilBrowsingDataRemoved(
1781       BrowsingDataRemover::EVERYTHING,
1782       BrowsingDataRemover::REMOVE_HISTORY, false);
1783   EXPECT_EQ(1u, tester.clear_count());
1784   EXPECT_EQ(CLEAR_BEACONS, tester.last_clear_mode());
1785 }
1786
1787 TEST_F(BrowsingDataRemoverTest, DomainReliability_Contexts) {
1788   ClearDomainReliabilityTester tester(GetProfile());
1789
1790   BlockUntilBrowsingDataRemoved(
1791       BrowsingDataRemover::EVERYTHING,
1792       BrowsingDataRemover::REMOVE_COOKIES, false);
1793   EXPECT_EQ(1u, tester.clear_count());
1794   EXPECT_EQ(CLEAR_CONTEXTS, tester.last_clear_mode());
1795 }
1796
1797 TEST_F(BrowsingDataRemoverTest, DomainReliability_ContextsWin) {
1798   ClearDomainReliabilityTester tester(GetProfile());
1799
1800   BlockUntilBrowsingDataRemoved(
1801       BrowsingDataRemover::EVERYTHING,
1802       BrowsingDataRemover::REMOVE_HISTORY |
1803       BrowsingDataRemover::REMOVE_COOKIES, false);
1804   EXPECT_EQ(1u, tester.clear_count());
1805   EXPECT_EQ(CLEAR_CONTEXTS, tester.last_clear_mode());
1806 }
1807
1808 TEST_F(BrowsingDataRemoverTest, DomainReliability_ProtectedOrigins) {
1809   ClearDomainReliabilityTester tester(GetProfile());
1810
1811   BlockUntilBrowsingDataRemoved(
1812       BrowsingDataRemover::EVERYTHING,
1813       BrowsingDataRemover::REMOVE_COOKIES, true);
1814   EXPECT_EQ(1u, tester.clear_count());
1815   EXPECT_EQ(CLEAR_CONTEXTS, tester.last_clear_mode());
1816 }
1817
1818 TEST_F(BrowsingDataRemoverTest, DomainReliability_NoMonitor) {
1819   BlockUntilBrowsingDataRemoved(
1820       BrowsingDataRemover::EVERYTHING,
1821       BrowsingDataRemover::REMOVE_HISTORY |
1822       BrowsingDataRemover::REMOVE_COOKIES, false);
1823 }