Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / safe_browsing / safe_browsing_service_browsertest.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 // This test creates a safebrowsing service using test safebrowsing database
6 // and a test protocol manager. It is used to test logics in safebrowsing
7 // service.
8
9 #include <algorithm>
10
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/files/file_path.h"
14 #include "base/files/scoped_temp_dir.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/metrics/field_trial.h"
17 #include "base/path_service.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/strings/string_split.h"
20 #include "base/test/thread_test_helper.h"
21 #include "base/time/time.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/prerender/prerender_manager.h"
25 #include "chrome/browser/profiles/profile.h"
26 #include "chrome/browser/profiles/profile_manager.h"
27 #include "chrome/browser/profiles/startup_task_runner_service.h"
28 #include "chrome/browser/profiles/startup_task_runner_service_factory.h"
29 #include "chrome/browser/safe_browsing/client_side_detection_service.h"
30 #include "chrome/browser/safe_browsing/database_manager.h"
31 #include "chrome/browser/safe_browsing/metadata.pb.h"
32 #include "chrome/browser/safe_browsing/protocol_manager.h"
33 #include "chrome/browser/safe_browsing/safe_browsing_database.h"
34 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
35 #include "chrome/browser/safe_browsing/safe_browsing_util.h"
36 #include "chrome/browser/safe_browsing/ui_manager.h"
37 #include "chrome/browser/ui/browser.h"
38 #include "chrome/browser/ui/tabs/tab_strip_model.h"
39 #include "chrome/common/chrome_paths.h"
40 #include "chrome/common/chrome_switches.h"
41 #include "chrome/common/pref_names.h"
42 #include "chrome/test/base/in_process_browser_test.h"
43 #include "chrome/test/base/ui_test_utils.h"
44 #include "content/public/browser/web_contents.h"
45 #include "net/cookies/cookie_store.h"
46 #include "sql/connection.h"
47 #include "sql/statement.h"
48 #include "testing/gmock/include/gmock/gmock.h"
49
50 #if defined(OS_CHROMEOS)
51 #include "chromeos/chromeos_switches.h"
52 #endif
53
54 using content::BrowserThread;
55 using content::InterstitialPage;
56 using content::WebContents;
57 using ::testing::_;
58 using ::testing::Mock;
59 using ::testing::StrictMock;
60
61 namespace {
62
63 void InvokeFullHashCallback(
64     SafeBrowsingProtocolManager::FullHashCallback callback,
65     const std::vector<SBFullHashResult>& result) {
66   callback.Run(result, base::TimeDelta::FromMinutes(45));
67 }
68
69 class FakeSafeBrowsingService : public SafeBrowsingService {
70  public:
71   explicit FakeSafeBrowsingService(const std::string& url_prefix)
72       : url_prefix_(url_prefix) {}
73
74   SafeBrowsingProtocolConfig GetProtocolConfig() const override {
75     SafeBrowsingProtocolConfig config;
76     config.url_prefix = url_prefix_;
77     // Makes sure the auto update is not triggered. The tests will force the
78     // update when needed.
79     config.disable_auto_update = true;
80 #if defined(OS_ANDROID)
81     config.disable_connection_check = true;
82 #endif
83     config.client_name = "browser_tests";
84     return config;
85   }
86
87  private:
88   ~FakeSafeBrowsingService() override {}
89
90   std::string url_prefix_;
91
92   DISALLOW_COPY_AND_ASSIGN(FakeSafeBrowsingService);
93 };
94
95 // Factory that creates FakeSafeBrowsingService instances.
96 class TestSafeBrowsingServiceFactory : public SafeBrowsingServiceFactory {
97  public:
98   explicit TestSafeBrowsingServiceFactory(const std::string& url_prefix)
99       : url_prefix_(url_prefix) {}
100
101   SafeBrowsingService* CreateSafeBrowsingService() override {
102     return new FakeSafeBrowsingService(url_prefix_);
103   }
104
105  private:
106   std::string url_prefix_;
107 };
108
109 // A SafeBrowingDatabase class that allows us to inject the malicious URLs.
110 class TestSafeBrowsingDatabase :  public SafeBrowsingDatabase {
111  public:
112   TestSafeBrowsingDatabase() {}
113
114   ~TestSafeBrowsingDatabase() override {}
115
116   // Initializes the database with the given filename.
117   void Init(const base::FilePath& filename) override {}
118
119   // Deletes the current database and creates a new one.
120   bool ResetDatabase() override {
121     badurls_.clear();
122     return true;
123   }
124
125   // Called on the IO thread to check if the given URL is safe or not.  If we
126   // can synchronously determine that the URL is safe, CheckUrl returns true,
127   // otherwise it returns false.
128   bool ContainsBrowseUrl(const GURL& url,
129                          std::vector<SBPrefix>* prefix_hits,
130                          std::vector<SBFullHashResult>* cache_hits) override {
131     cache_hits->clear();
132     return ContainsUrl(safe_browsing_util::MALWARE,
133                        safe_browsing_util::PHISH,
134                        std::vector<GURL>(1, url),
135                        prefix_hits);
136   }
137   bool ContainsUnwantedSoftwareUrl(
138       const GURL& url,
139       std::vector<SBPrefix>* prefix_hits,
140       std::vector<SBFullHashResult>* cache_hits) override {
141     cache_hits->clear();
142     return ContainsUrl(safe_browsing_util::UNWANTEDURL,
143                        safe_browsing_util::UNWANTEDURL,
144                        std::vector<GURL>(1, url),
145                        prefix_hits);
146   }
147   bool ContainsDownloadUrl(const std::vector<GURL>& urls,
148                            std::vector<SBPrefix>* prefix_hits) override {
149     bool found = ContainsUrl(safe_browsing_util::BINURL,
150                              safe_browsing_util::BINURL,
151                              urls,
152                              prefix_hits);
153     if (!found)
154       return false;
155     DCHECK_LE(1U, prefix_hits->size());
156     return true;
157   }
158   bool ContainsCsdWhitelistedUrl(const GURL& url) override { return true; }
159   bool ContainsDownloadWhitelistedString(const std::string& str) override {
160     return true;
161   }
162   bool ContainsDownloadWhitelistedUrl(const GURL& url) override { return true; }
163   bool ContainsExtensionPrefixes(const std::vector<SBPrefix>& prefixes,
164                                  std::vector<SBPrefix>* prefix_hits) override {
165     return true;
166   }
167   bool ContainsSideEffectFreeWhitelistUrl(const GURL& url) override {
168     return true;
169   }
170   bool ContainsMalwareIP(const std::string& ip_address) override {
171     return true;
172   }
173   bool UpdateStarted(std::vector<SBListChunkRanges>* lists) override {
174     ADD_FAILURE() << "Not implemented.";
175     return false;
176   }
177   void InsertChunks(const std::string& list_name,
178                     const std::vector<SBChunkData*>& chunks) override {
179     ADD_FAILURE() << "Not implemented.";
180   }
181   void DeleteChunks(const std::vector<SBChunkDelete>& chunk_deletes) override {
182     ADD_FAILURE() << "Not implemented.";
183   }
184   void UpdateFinished(bool update_succeeded) override {
185     ADD_FAILURE() << "Not implemented.";
186   }
187   void CacheHashResults(const std::vector<SBPrefix>& prefixes,
188                         const std::vector<SBFullHashResult>& cache_hits,
189                         const base::TimeDelta& cache_lifetime) override {
190     // Do nothing for the cache.
191   }
192   bool IsMalwareIPMatchKillSwitchOn() override { return false; }
193   bool IsCsdWhitelistKillSwitchOn() override { return false; }
194
195   // Fill up the database with test URL.
196   void AddUrl(const GURL& url,
197               int list_id,
198               const std::vector<SBPrefix>& prefix_hits) {
199     Hits* hits_for_url = &badurls_[url.spec()];
200     hits_for_url->list_ids.push_back(list_id);
201     hits_for_url->prefix_hits.insert(hits_for_url->prefix_hits.end(),
202                                      prefix_hits.begin(),
203                                      prefix_hits.end());
204   }
205
206   // Fill up the database with test hash digest.
207   void AddDownloadPrefix(SBPrefix prefix) {
208     download_digest_prefix_.insert(prefix);
209   }
210
211  private:
212   // Stores |list_ids| of safe browsing lists that match some |prefix_hits|.
213   struct Hits {
214     std::vector<int> list_ids;
215     std::vector<SBPrefix> prefix_hits;
216   };
217
218   bool ContainsUrl(int list_id0,
219                    int list_id1,
220                    const std::vector<GURL>& urls,
221                    std::vector<SBPrefix>* prefix_hits) {
222     bool hit = false;
223     for (size_t i = 0; i < urls.size(); ++i) {
224       const GURL& url = urls[i];
225       base::hash_map<std::string, Hits>::const_iterator
226           badurls_it = badurls_.find(url.spec());
227
228       if (badurls_it == badurls_.end())
229         continue;
230
231       std::vector<int> list_ids_for_url = badurls_it->second.list_ids;
232       if (std::find(list_ids_for_url.begin(), list_ids_for_url.end(), list_id0)
233               != list_ids_for_url.end() ||
234           std::find(list_ids_for_url.begin(), list_ids_for_url.end(), list_id1)
235               != list_ids_for_url.end()) {
236         prefix_hits->insert(prefix_hits->end(),
237                             badurls_it->second.prefix_hits.begin(),
238                             badurls_it->second.prefix_hits.end());
239         hit = true;
240       }
241     }
242     return hit;
243   }
244
245   base::hash_map<std::string, Hits> badurls_;
246   base::hash_set<SBPrefix> download_digest_prefix_;
247 };
248
249 // Factory that creates TestSafeBrowsingDatabase instances.
250 class TestSafeBrowsingDatabaseFactory : public SafeBrowsingDatabaseFactory {
251  public:
252   TestSafeBrowsingDatabaseFactory() : db_(NULL) {}
253   ~TestSafeBrowsingDatabaseFactory() override {}
254
255   SafeBrowsingDatabase* CreateSafeBrowsingDatabase(
256       bool enable_download_protection,
257       bool enable_client_side_whitelist,
258       bool enable_download_whitelist,
259       bool enable_extension_blacklist,
260       bool enable_side_effect_free_whitelist,
261       bool enable_ip_blacklist,
262       bool enabled_unwanted_software_list) override {
263     db_ = new TestSafeBrowsingDatabase();
264     return db_;
265   }
266   TestSafeBrowsingDatabase* GetDb() {
267     return db_;
268   }
269  private:
270   // Owned by the SafebrowsingService.
271   TestSafeBrowsingDatabase* db_;
272 };
273
274 // A TestProtocolManager that could return fixed responses from
275 // safebrowsing server for testing purpose.
276 class TestProtocolManager :  public SafeBrowsingProtocolManager {
277  public:
278   TestProtocolManager(SafeBrowsingProtocolManagerDelegate* delegate,
279                       net::URLRequestContextGetter* request_context_getter,
280                       const SafeBrowsingProtocolConfig& config)
281       : SafeBrowsingProtocolManager(delegate, request_context_getter, config) {
282     create_count_++;
283   }
284
285   ~TestProtocolManager() override { delete_count_++; }
286
287   // This function is called when there is a prefix hit in local safebrowsing
288   // database and safebrowsing service issues a get hash request to backends.
289   // We return a result from the prefilled full_hashes_ hash_map to simulate
290   // server's response. At the same time, latency is added to simulate real
291   // life network issues.
292   void GetFullHash(const std::vector<SBPrefix>& prefixes,
293                    SafeBrowsingProtocolManager::FullHashCallback callback,
294                    bool is_download) override {
295     BrowserThread::PostDelayedTask(
296         BrowserThread::IO, FROM_HERE,
297         base::Bind(InvokeFullHashCallback, callback, full_hashes_),
298         delay_);
299   }
300
301   // Prepare the GetFullHash results for the next request.
302   void AddGetFullHashResponse(const SBFullHashResult& full_hash_result) {
303     full_hashes_.push_back(full_hash_result);
304   }
305
306   void IntroduceDelay(const base::TimeDelta& delay) {
307     delay_ = delay;
308   }
309
310   static int create_count() {
311     return create_count_;
312   }
313
314   static int delete_count() {
315     return delete_count_;
316   }
317
318  private:
319   std::vector<SBFullHashResult> full_hashes_;
320   base::TimeDelta delay_;
321   static int create_count_;
322   static int delete_count_;
323 };
324
325 // static
326 int TestProtocolManager::create_count_ = 0;
327 // static
328 int TestProtocolManager::delete_count_ = 0;
329
330 // Factory that creates TestProtocolManager instances.
331 class TestSBProtocolManagerFactory : public SBProtocolManagerFactory {
332  public:
333   TestSBProtocolManagerFactory() : pm_(NULL) {}
334   ~TestSBProtocolManagerFactory() override {}
335
336   SafeBrowsingProtocolManager* CreateProtocolManager(
337       SafeBrowsingProtocolManagerDelegate* delegate,
338       net::URLRequestContextGetter* request_context_getter,
339       const SafeBrowsingProtocolConfig& config) override {
340     pm_ = new TestProtocolManager(delegate, request_context_getter, config);
341     return pm_;
342   }
343
344   TestProtocolManager* GetProtocolManager() {
345     return pm_;
346   }
347
348  private:
349   // Owned by the SafebrowsingService.
350   TestProtocolManager* pm_;
351 };
352
353 class MockObserver : public SafeBrowsingUIManager::Observer {
354  public:
355   MockObserver() {}
356   virtual ~MockObserver() {}
357   MOCK_METHOD1(OnSafeBrowsingHit,
358                void(const SafeBrowsingUIManager::UnsafeResource&));
359   MOCK_METHOD1(OnSafeBrowsingMatch,
360                void(const SafeBrowsingUIManager::UnsafeResource&));
361 };
362
363 MATCHER_P(IsUnsafeResourceFor, url, "") {
364   return (arg.url.spec() == url.spec() &&
365           arg.threat_type != SB_THREAT_TYPE_SAFE);
366 }
367
368 }  // namespace
369
370 // Tests the safe browsing blocking page in a browser.
371 class SafeBrowsingServiceTest : public InProcessBrowserTest {
372  public:
373   SafeBrowsingServiceTest() {
374   }
375
376   static void GenUrlFullhashResult(const GURL& url,
377                                    int list_id,
378                                    SBFullHashResult* full_hash) {
379     std::string host;
380     std::string path;
381     safe_browsing_util::CanonicalizeUrl(url, &host, &path, NULL);
382     full_hash->hash = SBFullHashForString(host + path);
383     full_hash->list_id = list_id;
384   }
385
386   virtual void SetUp() {
387     // InProcessBrowserTest::SetUp() instantiates SafebrowsingService and
388     // RegisterFactory has to be called before SafeBrowsingService is created.
389     sb_factory_.reset(new TestSafeBrowsingServiceFactory(
390         "https://definatelynotarealdomain/safebrowsing"));
391     SafeBrowsingService::RegisterFactory(sb_factory_.get());
392     SafeBrowsingDatabase::RegisterFactory(&db_factory_);
393     SafeBrowsingProtocolManager::RegisterFactory(&pm_factory_);
394     InProcessBrowserTest::SetUp();
395   }
396
397   virtual void TearDown() {
398     InProcessBrowserTest::TearDown();
399
400     // Unregister test factories after InProcessBrowserTest::TearDown
401     // (which destructs SafeBrowsingService).
402     SafeBrowsingDatabase::RegisterFactory(NULL);
403     SafeBrowsingProtocolManager::RegisterFactory(NULL);
404     SafeBrowsingService::RegisterFactory(NULL);
405   }
406
407   virtual void SetUpCommandLine(CommandLine* command_line) override {
408     // Makes sure the auto update is not triggered during the test.
409     // This test will fill up the database using testing prefixes
410     // and urls.
411     command_line->AppendSwitch(switches::kSbDisableAutoUpdate);
412 #if defined(OS_CHROMEOS)
413     command_line->AppendSwitch(
414         chromeos::switches::kIgnoreUserProfileMappingForTests);
415 #endif
416   }
417
418   virtual void SetUpInProcessBrowserTestFixture() {
419     ASSERT_TRUE(test_server()->Start());
420   }
421
422   // This will setup the "url" prefix in database and prepare protocol manager
423   // to respond with |full_hash|, as well as other |full_hash|es previously set
424   // via this call, on GetFullHash requests.
425   void SetupResponseForUrl(const GURL& url, const SBFullHashResult& full_hash) {
426     std::vector<SBPrefix> prefix_hits;
427     prefix_hits.push_back(full_hash.hash.prefix);
428
429     // Make sure the full hits is empty unless we need to test the
430     // full hash is hit in database's local cache.
431     TestSafeBrowsingDatabase* db = db_factory_.GetDb();
432     db->AddUrl(url, full_hash.list_id, prefix_hits);
433
434     TestProtocolManager* pm = pm_factory_.GetProtocolManager();
435     pm->AddGetFullHashResponse(full_hash);
436   }
437
438   bool ShowingInterstitialPage() {
439     WebContents* contents =
440         browser()->tab_strip_model()->GetActiveWebContents();
441     InterstitialPage* interstitial_page = contents->GetInterstitialPage();
442     return interstitial_page != NULL;
443   }
444
445   void IntroduceGetHashDelay(const base::TimeDelta& delay) {
446     pm_factory_.GetProtocolManager()->IntroduceDelay(delay);
447   }
448
449   base::TimeDelta GetCheckTimeout(SafeBrowsingService* sb_service) {
450     return sb_service->database_manager()->check_timeout_;
451   }
452
453   void SetCheckTimeout(SafeBrowsingService* sb_service,
454                        const base::TimeDelta& delay) {
455     sb_service->database_manager()->check_timeout_ = delay;
456   }
457
458   void CreateCSDService() {
459     safe_browsing::ClientSideDetectionService* csd_service =
460         safe_browsing::ClientSideDetectionService::Create(NULL);
461     SafeBrowsingService* sb_service =
462         g_browser_process->safe_browsing_service();
463     sb_service->csd_service_.reset(csd_service);
464     sb_service->RefreshState();
465   }
466
467   void ProceedAndWhitelist(
468       const SafeBrowsingUIManager::UnsafeResource& resource) {
469     std::vector<SafeBrowsingUIManager::UnsafeResource> resources;
470     resources.push_back(resource);
471     BrowserThread::PostTask(
472         BrowserThread::IO, FROM_HERE,
473         base::Bind(&SafeBrowsingUIManager::OnBlockingPageDone,
474                    g_browser_process->safe_browsing_service()->ui_manager(),
475                    resources, true));
476     WaitForIOThread();
477   }
478
479  protected:
480   StrictMock<MockObserver> observer_;
481
482   // Temporary profile dir for test cases that create a second profile.  This is
483   // owned by the SafeBrowsingServiceTest object so that it will not get
484   // destructed until after the test Browser has been torn down, since the
485   // ImportantFileWriter may still be modifying it after the Profile object has
486   // been destroyed.
487   base::ScopedTempDir temp_profile_dir_;
488
489   // Waits for pending tasks on the IO thread to complete. This is useful
490   // to wait for the SafeBrowsingService to finish loading/stopping.
491   void WaitForIOThread() {
492     scoped_refptr<base::ThreadTestHelper> io_helper(new base::ThreadTestHelper(
493         BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get()));
494     ASSERT_TRUE(io_helper->Run());
495   }
496
497  private:
498   scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
499   TestSafeBrowsingDatabaseFactory db_factory_;
500   TestSBProtocolManagerFactory pm_factory_;
501
502   DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTest);
503 };
504
505 enum MalwareMetadataTestType {
506   METADATA_NONE,
507   METADATA_LANDING,
508   METADATA_DISTRIBUTION,
509 };
510
511 class SafeBrowsingServiceMetadataTest
512     : public SafeBrowsingServiceTest,
513       public ::testing::WithParamInterface<MalwareMetadataTestType> {
514  public:
515   SafeBrowsingServiceMetadataTest() {}
516
517   void SetUpOnMainThread() override {
518     SafeBrowsingServiceTest::SetUpOnMainThread();
519     g_browser_process->safe_browsing_service()->ui_manager()->AddObserver(
520         &observer_);
521   }
522
523   void TearDownOnMainThread() override {
524     g_browser_process->safe_browsing_service()->ui_manager()->RemoveObserver(
525         &observer_);
526     SafeBrowsingServiceTest::TearDownOnMainThread();
527   }
528
529   void GenUrlFullhashResultWithMetadata(const GURL& url,
530                                         SBFullHashResult* full_hash) {
531     GenUrlFullhashResult(url, safe_browsing_util::MALWARE, full_hash);
532
533     safe_browsing::MalwarePatternType proto;
534     switch (GetParam()) {
535       case METADATA_NONE:
536         full_hash->metadata = std::string();
537         break;
538       case METADATA_LANDING:
539         proto.set_pattern_type(safe_browsing::MalwarePatternType::LANDING);
540         full_hash->metadata = proto.SerializeAsString();
541         break;
542       case METADATA_DISTRIBUTION:
543         proto.set_pattern_type(safe_browsing::MalwarePatternType::DISTRIBUTION);
544         full_hash->metadata = proto.SerializeAsString();
545         break;
546     }
547   }
548
549  private:
550   DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceMetadataTest);
551 };
552
553 namespace {
554
555 const char kEmptyPage[] = "files/empty.html";
556 const char kMalwareFile[] = "files/downloads/dangerous/dangerous.exe";
557 const char kMalwarePage[] = "files/safe_browsing/malware.html";
558 const char kMalwareIFrame[] = "files/safe_browsing/malware_iframe.html";
559 const char kMalwareImg[] = "files/safe_browsing/malware_image.png";
560
561 // This test goes through DownloadResourceHandler.
562 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareMainFrame) {
563   GURL url = test_server()->GetURL(kEmptyPage);
564
565   // After adding the url to safebrowsing database and getfullhash result,
566   // we should see the interstitial page.
567   SBFullHashResult malware_full_hash;
568   GenUrlFullhashResultWithMetadata(url, &malware_full_hash);
569   EXPECT_CALL(observer_,
570               OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
571   EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1);
572   SetupResponseForUrl(url, malware_full_hash);
573   ui_test_utils::NavigateToURL(browser(), url);
574   // All types should show the interstitial.
575   EXPECT_TRUE(ShowingInterstitialPage());
576 }
577
578 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareIFrame) {
579   GURL main_url = test_server()->GetURL(kMalwarePage);
580   GURL iframe_url = test_server()->GetURL(kMalwareIFrame);
581
582   // Add the iframe url as malware and then load the parent page.
583   SBFullHashResult malware_full_hash;
584   GenUrlFullhashResultWithMetadata(iframe_url, &malware_full_hash);
585   EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(iframe_url)))
586       .Times(1);
587   EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(iframe_url)))
588       .Times(1);
589   SetupResponseForUrl(iframe_url, malware_full_hash);
590   ui_test_utils::NavigateToURL(browser(), main_url);
591   // All types should show the interstitial.
592   EXPECT_TRUE(ShowingInterstitialPage());
593 }
594
595 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareImg) {
596   GURL main_url = test_server()->GetURL(kMalwarePage);
597   GURL img_url = test_server()->GetURL(kMalwareImg);
598
599   // Add the img url as malware and then load the parent page.
600   SBFullHashResult malware_full_hash;
601   GenUrlFullhashResultWithMetadata(img_url, &malware_full_hash);
602   switch (GetParam()) {
603     case METADATA_NONE:
604     case METADATA_DISTRIBUTION:
605       EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(img_url)))
606           .Times(1);
607       EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(img_url)))
608           .Times(1);
609       break;
610     case METADATA_LANDING:
611       // No interstitial shown, so no notifications expected.
612       break;
613   }
614   SetupResponseForUrl(img_url, malware_full_hash);
615   ui_test_utils::NavigateToURL(browser(), main_url);
616   // Subresource which is tagged as a landing page should not show an
617   // interstitial, the other types should.
618   switch (GetParam()) {
619     case METADATA_NONE:
620     case METADATA_DISTRIBUTION:
621       EXPECT_TRUE(ShowingInterstitialPage());
622       break;
623     case METADATA_LANDING:
624       EXPECT_FALSE(ShowingInterstitialPage());
625       break;
626   }
627 }
628
629 INSTANTIATE_TEST_CASE_P(MaybeSetMetadata,
630                         SafeBrowsingServiceMetadataTest,
631                         testing::Values(METADATA_NONE,
632                                         METADATA_LANDING,
633                                         METADATA_DISTRIBUTION));
634
635 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, DISABLED_MalwareWithWhitelist) {
636   GURL url = test_server()->GetURL(kEmptyPage);
637   g_browser_process->safe_browsing_service()->
638       ui_manager()->AddObserver(&observer_);
639
640   // After adding the url to safebrowsing database and getfullhash result,
641   // we should see the interstitial page.
642   SBFullHashResult malware_full_hash;
643   GenUrlFullhashResult(url, safe_browsing_util::MALWARE, &malware_full_hash);
644   EXPECT_CALL(observer_,
645               OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
646   EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1)
647       .WillOnce(testing::Invoke(
648           this, &SafeBrowsingServiceTest::ProceedAndWhitelist));
649   SetupResponseForUrl(url, malware_full_hash);
650
651   ui_test_utils::NavigateToURL(browser(), url);
652   // Mock calls OnBlockingPageDone set to proceed, so the interstitial
653   // is removed.
654   EXPECT_FALSE(ShowingInterstitialPage());
655   Mock::VerifyAndClearExpectations(&observer_);
656
657   // Navigate back to kEmptyPage -- should hit the whitelist, and send a match
658   // call, but no hit call.
659   EXPECT_CALL(observer_,
660               OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
661   EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(0);
662   ui_test_utils::NavigateToURL(browser(), url);
663   EXPECT_FALSE(ShowingInterstitialPage());
664
665   g_browser_process->safe_browsing_service()->
666       ui_manager()->RemoveObserver(&observer_);
667 }
668
669 const char kPrefetchMalwarePage[] = "files/safe_browsing/prefetch_malware.html";
670
671 // This test confirms that prefetches don't themselves get the
672 // interstitial treatment.
673 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, Prefetch) {
674   GURL url = test_server()->GetURL(kPrefetchMalwarePage);
675   GURL malware_url = test_server()->GetURL(kMalwarePage);
676   g_browser_process->safe_browsing_service()->
677       ui_manager()->AddObserver(&observer_);
678
679   class SetPrefetchForTest {
680    public:
681     explicit SetPrefetchForTest(bool prefetch)
682         : old_prerender_mode_(prerender::PrerenderManager::GetMode()) {
683       std::string exp_group = prefetch ? "ExperimentYes" : "ExperimentNo";
684       base::FieldTrialList::CreateFieldTrial("Prefetch", exp_group);
685
686       prerender::PrerenderManager::SetMode(
687           prerender::PrerenderManager::PRERENDER_MODE_DISABLED);
688     }
689
690     ~SetPrefetchForTest() {
691       prerender::PrerenderManager::SetMode(old_prerender_mode_);
692     }
693
694    private:
695     prerender::PrerenderManager::PrerenderManagerMode old_prerender_mode_;
696   } set_prefetch_for_test(true);
697
698   // Even though we have added this uri to the safebrowsing database and
699   // getfullhash result, we should not see the interstitial page since the
700   // only malware was a prefetch target.
701   SBFullHashResult malware_full_hash;
702   GenUrlFullhashResult(malware_url, safe_browsing_util::MALWARE,
703                        &malware_full_hash);
704   SetupResponseForUrl(malware_url, malware_full_hash);
705   ui_test_utils::NavigateToURL(browser(), url);
706   EXPECT_FALSE(ShowingInterstitialPage());
707   Mock::VerifyAndClear(&observer_);
708
709   // However, when we navigate to the malware page, we should still get
710   // the interstitial.
711   EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(malware_url)))
712       .Times(1);
713   EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(malware_url)))
714       .Times(1);
715   ui_test_utils::NavigateToURL(browser(), malware_url);
716   EXPECT_TRUE(ShowingInterstitialPage());
717   Mock::VerifyAndClear(&observer_);
718   g_browser_process->safe_browsing_service()->
719       ui_manager()->RemoveObserver(&observer_);
720 }
721
722 }  // namespace
723
724 class TestSBClient
725     : public base::RefCountedThreadSafe<TestSBClient>,
726       public SafeBrowsingDatabaseManager::Client {
727  public:
728   TestSBClient()
729     : threat_type_(SB_THREAT_TYPE_SAFE),
730       safe_browsing_service_(g_browser_process->safe_browsing_service()) {
731   }
732
733   SBThreatType GetThreatType() const {
734     return threat_type_;
735   }
736
737   void CheckDownloadUrl(const std::vector<GURL>& url_chain) {
738     BrowserThread::PostTask(
739         BrowserThread::IO, FROM_HERE,
740         base::Bind(&TestSBClient::CheckDownloadUrlOnIOThread,
741                    this, url_chain));
742     content::RunMessageLoop();  // Will stop in OnCheckDownloadUrlResult.
743   }
744
745   void CheckBrowseUrl(const GURL& url) {
746     BrowserThread::PostTask(
747         BrowserThread::IO, FROM_HERE,
748         base::Bind(&TestSBClient::CheckBrowseUrlOnIOThread, this, url));
749     content::RunMessageLoop();  // Will stop in OnCheckBrowseUrlResult.
750   }
751
752  private:
753   friend class base::RefCountedThreadSafe<TestSBClient>;
754   ~TestSBClient() override {}
755
756   void CheckDownloadUrlOnIOThread(const std::vector<GURL>& url_chain) {
757     bool synchronous_safe_signal =
758         safe_browsing_service_->database_manager()->CheckDownloadUrl(url_chain,
759                                                                      this);
760     if (synchronous_safe_signal) {
761       threat_type_ = SB_THREAT_TYPE_SAFE;
762       BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
763                               base::Bind(&TestSBClient::CheckDone, this));
764     }
765   }
766
767   void CheckBrowseUrlOnIOThread(const GURL& url) {
768     // The async CheckDone() hook will not be called when we have a synchronous
769     // safe signal, handle it right away.
770     bool synchronous_safe_signal =
771         safe_browsing_service_->database_manager()->CheckBrowseUrl(url, this);
772     if (synchronous_safe_signal) {
773       threat_type_ = SB_THREAT_TYPE_SAFE;
774       BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
775                               base::Bind(&TestSBClient::CheckDone, this));
776     }
777   }
778
779   // Called when the result of checking a download URL is known.
780   void OnCheckDownloadUrlResult(const std::vector<GURL>& /* url_chain */,
781                                 SBThreatType threat_type) override {
782     threat_type_ = threat_type;
783     BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
784                             base::Bind(&TestSBClient::CheckDone, this));
785   }
786
787   // Called when the result of checking a browse URL is known.
788   void OnCheckBrowseUrlResult(const GURL& /* url */,
789                               SBThreatType threat_type,
790                               const std::string& /* metadata */) override {
791     threat_type_ = threat_type;
792     BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
793                             base::Bind(&TestSBClient::CheckDone, this));
794   }
795
796   void CheckDone() {
797     base::MessageLoopForUI::current()->Quit();
798   }
799
800   SBThreatType threat_type_;
801   SafeBrowsingService* safe_browsing_service_;
802
803   DISALLOW_COPY_AND_ASSIGN(TestSBClient);
804 };
805
806 // These tests use SafeBrowsingService::Client to directly interact with
807 // SafeBrowsingService.
808 namespace {
809
810 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrl) {
811   GURL badbin_url = test_server()->GetURL(kMalwareFile);
812   std::vector<GURL> badbin_urls(1, badbin_url);
813
814   scoped_refptr<TestSBClient> client(new TestSBClient);
815   client->CheckDownloadUrl(badbin_urls);
816
817   // Since badbin_url is not in database, it is considered to be safe.
818   EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
819
820   SBFullHashResult full_hash_result;
821   GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
822                        &full_hash_result);
823   SetupResponseForUrl(badbin_url, full_hash_result);
824
825   client->CheckDownloadUrl(badbin_urls);
826
827   // Now, the badbin_url is not safe since it is added to download database.
828   EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
829 }
830
831 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckUnwantedSoftwareUrl) {
832   const GURL bad_url = test_server()->GetURL(kMalwareFile);
833   {
834     scoped_refptr<TestSBClient> client(new TestSBClient);
835
836     // Since bad_url is not in database, it is considered to be
837     // safe.
838     client->CheckBrowseUrl(bad_url);
839     EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
840
841     SBFullHashResult full_hash_result;
842     GenUrlFullhashResult(
843         bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
844     SetupResponseForUrl(bad_url, full_hash_result);
845
846     // Now, the bad_url is not safe since it is added to download
847     // database.
848     client->CheckBrowseUrl(bad_url);
849     EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
850   }
851
852   // The unwantedness should survive across multiple clients.
853   {
854     scoped_refptr<TestSBClient> client(new TestSBClient);
855     client->CheckBrowseUrl(bad_url);
856     EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
857   }
858
859   // An unwanted URL also marked as malware should be flagged as malware.
860   {
861     scoped_refptr<TestSBClient> client(new TestSBClient);
862
863     SBFullHashResult full_hash_result;
864     GenUrlFullhashResult(
865         bad_url, safe_browsing_util::MALWARE, &full_hash_result);
866     SetupResponseForUrl(bad_url, full_hash_result);
867
868     client->CheckBrowseUrl(bad_url);
869     EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
870   }
871 }
872
873 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckBrowseUrl) {
874   const GURL bad_url = test_server()->GetURL(kMalwareFile);
875   {
876     scoped_refptr<TestSBClient> client(new TestSBClient);
877
878     // Since bad_url is not in database, it is considered to be
879     // safe.
880     client->CheckBrowseUrl(bad_url);
881     EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
882
883     SBFullHashResult full_hash_result;
884     GenUrlFullhashResult(
885         bad_url, safe_browsing_util::MALWARE, &full_hash_result);
886     SetupResponseForUrl(bad_url, full_hash_result);
887
888     // Now, the bad_url is not safe since it is added to download
889     // database.
890     client->CheckBrowseUrl(bad_url);
891     EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
892   }
893
894   // The unwantedness should survive across multiple clients.
895   {
896     scoped_refptr<TestSBClient> client(new TestSBClient);
897     client->CheckBrowseUrl(bad_url);
898     EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
899   }
900
901   // Adding the unwanted state to an existing malware URL should have no impact
902   // (i.e. a malware hit should still prevail).
903   {
904     scoped_refptr<TestSBClient> client(new TestSBClient);
905
906     SBFullHashResult full_hash_result;
907     GenUrlFullhashResult(
908         bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
909     SetupResponseForUrl(bad_url, full_hash_result);
910
911     client->CheckBrowseUrl(bad_url);
912     EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
913   }
914 }
915
916 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrlRedirects) {
917   GURL original_url = test_server()->GetURL(kEmptyPage);
918   GURL badbin_url = test_server()->GetURL(kMalwareFile);
919   GURL final_url = test_server()->GetURL(kEmptyPage);
920   std::vector<GURL> badbin_urls;
921   badbin_urls.push_back(original_url);
922   badbin_urls.push_back(badbin_url);
923   badbin_urls.push_back(final_url);
924
925   scoped_refptr<TestSBClient> client(new TestSBClient);
926   client->CheckDownloadUrl(badbin_urls);
927
928   // Since badbin_url is not in database, it is considered to be safe.
929   EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
930
931   SBFullHashResult full_hash_result;
932   GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
933                        &full_hash_result);
934   SetupResponseForUrl(badbin_url, full_hash_result);
935
936   client->CheckDownloadUrl(badbin_urls);
937
938   // Now, the badbin_url is not safe since it is added to download database.
939   EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
940 }
941
942 #if defined(OS_WIN)
943 // http://crbug.com/396409
944 #define MAYBE_CheckDownloadUrlTimedOut DISABLED_CheckDownloadUrlTimedOut
945 #else
946 #define MAYBE_CheckDownloadUrlTimedOut CheckDownloadUrlTimedOut
947 #endif
948 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest,
949                        MAYBE_CheckDownloadUrlTimedOut) {
950   GURL badbin_url = test_server()->GetURL(kMalwareFile);
951   std::vector<GURL> badbin_urls(1, badbin_url);
952
953   scoped_refptr<TestSBClient> client(new TestSBClient);
954   SBFullHashResult full_hash_result;
955   GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
956                        &full_hash_result);
957   SetupResponseForUrl(badbin_url, full_hash_result);
958   client->CheckDownloadUrl(badbin_urls);
959
960   // badbin_url is not safe since it is added to download database.
961   EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
962
963   //
964   // Now introducing delays and we should hit timeout.
965   //
966   SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
967   base::TimeDelta default_urlcheck_timeout = GetCheckTimeout(sb_service);
968   IntroduceGetHashDelay(base::TimeDelta::FromSeconds(1));
969   SetCheckTimeout(sb_service, base::TimeDelta::FromMilliseconds(1));
970   client->CheckDownloadUrl(badbin_urls);
971
972   // There should be a timeout and the hash would be considered as safe.
973   EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
974
975   // Need to set the timeout back to the default value.
976   SetCheckTimeout(sb_service, default_urlcheck_timeout);
977 }
978
979 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, StartAndStop) {
980   CreateCSDService();
981   SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
982   safe_browsing::ClientSideDetectionService* csd_service =
983       sb_service->safe_browsing_detection_service();
984   PrefService* pref_service = browser()->profile()->GetPrefs();
985
986   ASSERT_TRUE(sb_service != NULL);
987   ASSERT_TRUE(csd_service != NULL);
988   ASSERT_TRUE(pref_service != NULL);
989
990   EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
991
992   // SBS might still be starting, make sure this doesn't flake.
993   WaitForIOThread();
994   EXPECT_TRUE(sb_service->enabled());
995   EXPECT_TRUE(csd_service->enabled());
996
997   // Add a new Profile. SBS should keep running.
998   ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
999   scoped_ptr<Profile> profile2(Profile::CreateProfile(
1000       temp_profile_dir_.path(), NULL, Profile::CREATE_MODE_SYNCHRONOUS));
1001   ASSERT_TRUE(profile2.get() != NULL);
1002   StartupTaskRunnerServiceFactory::GetForProfile(profile2.get())->
1003               StartDeferredTaskRunners();
1004   PrefService* pref_service2 = profile2->GetPrefs();
1005   EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1006   // We don't expect the state to have changed, but if it did, wait for it.
1007   WaitForIOThread();
1008   EXPECT_TRUE(sb_service->enabled());
1009   EXPECT_TRUE(csd_service->enabled());
1010
1011   // Change one of the prefs. SBS should keep running.
1012   pref_service->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1013   WaitForIOThread();
1014   EXPECT_TRUE(sb_service->enabled());
1015   EXPECT_TRUE(csd_service->enabled());
1016
1017   // Change the other pref. SBS should stop now.
1018   pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1019   WaitForIOThread();
1020   EXPECT_FALSE(sb_service->enabled());
1021   EXPECT_FALSE(csd_service->enabled());
1022
1023   // Turn it back on. SBS comes back.
1024   pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, true);
1025   WaitForIOThread();
1026   EXPECT_TRUE(sb_service->enabled());
1027   EXPECT_TRUE(csd_service->enabled());
1028
1029   // Delete the Profile. SBS stops again.
1030   pref_service2 = NULL;
1031   profile2.reset();
1032   WaitForIOThread();
1033   EXPECT_FALSE(sb_service->enabled());
1034   EXPECT_FALSE(csd_service->enabled());
1035 }
1036
1037 }  // namespace
1038
1039 class SafeBrowsingServiceShutdownTest : public SafeBrowsingServiceTest {
1040  public:
1041   void TearDown() override {
1042     // Browser should be fully torn down by now, so we can safely check these
1043     // counters.
1044     EXPECT_EQ(1, TestProtocolManager::create_count());
1045     EXPECT_EQ(1, TestProtocolManager::delete_count());
1046
1047     SafeBrowsingServiceTest::TearDown();
1048   }
1049
1050   // An observer that returns back to test code after a new profile is
1051   // initialized.
1052   void OnUnblockOnProfileCreation(Profile* profile,
1053                                   Profile::CreateStatus status) {
1054     if (status == Profile::CREATE_STATUS_INITIALIZED) {
1055       profile2_ = profile;
1056       base::MessageLoop::current()->Quit();
1057     }
1058   }
1059
1060  protected:
1061   Profile* profile2_;
1062 };
1063
1064 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceShutdownTest,
1065                        DontStartAfterShutdown) {
1066   CreateCSDService();
1067   SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
1068   safe_browsing::ClientSideDetectionService* csd_service =
1069       sb_service->safe_browsing_detection_service();
1070   PrefService* pref_service = browser()->profile()->GetPrefs();
1071
1072   ASSERT_TRUE(sb_service != NULL);
1073   ASSERT_TRUE(csd_service != NULL);
1074   ASSERT_TRUE(pref_service != NULL);
1075
1076   EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
1077
1078   // SBS might still be starting, make sure this doesn't flake.
1079   WaitForIOThread();
1080   EXPECT_EQ(1, TestProtocolManager::create_count());
1081   EXPECT_EQ(0, TestProtocolManager::delete_count());
1082
1083   // Create an additional profile.  We need to use the ProfileManager so that
1084   // the profile will get destroyed in the normal browser shutdown process.
1085   ProfileManager* profile_manager = g_browser_process->profile_manager();
1086   ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
1087   profile_manager->CreateProfileAsync(
1088       temp_profile_dir_.path(),
1089       base::Bind(&SafeBrowsingServiceShutdownTest::OnUnblockOnProfileCreation,
1090                  this),
1091       base::string16(), base::string16(), std::string());
1092
1093   // Spin to allow profile creation to take place, loop is terminated
1094   // by OnUnblockOnProfileCreation when the profile is created.
1095   content::RunMessageLoop();
1096
1097   PrefService* pref_service2 = profile2_->GetPrefs();
1098   EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1099
1100   // We don't expect the state to have changed, but if it did, wait for it.
1101   WaitForIOThread();
1102   EXPECT_EQ(1, TestProtocolManager::create_count());
1103   EXPECT_EQ(0, TestProtocolManager::delete_count());
1104
1105   // End the test, shutting down the browser.
1106   // SafeBrowsingServiceShutdownTest::TearDown will check the create_count and
1107   // delete_count again.
1108 }
1109
1110 class SafeBrowsingDatabaseManagerCookieTest : public InProcessBrowserTest {
1111  public:
1112   SafeBrowsingDatabaseManagerCookieTest() {}
1113
1114   void SetUp() override {
1115     // We need to start the test server to get the host&port in the url.
1116     ASSERT_TRUE(test_server()->Start());
1117
1118     // Point to the testing server for all SafeBrowsing requests.
1119     GURL url_prefix = test_server()->GetURL(
1120         "expect-and-set-cookie?expect=a%3db"
1121         "&set=c%3dd%3b%20Expires=Fri,%2001%20Jan%202038%2001:01:01%20GMT"
1122         "&data=foo#");
1123     sb_factory_.reset(new TestSafeBrowsingServiceFactory(url_prefix.spec()));
1124     SafeBrowsingService::RegisterFactory(sb_factory_.get());
1125
1126     InProcessBrowserTest::SetUp();
1127   }
1128
1129   void TearDown() override {
1130     InProcessBrowserTest::TearDown();
1131
1132     SafeBrowsingService::RegisterFactory(NULL);
1133   }
1134
1135   bool SetUpUserDataDirectory() override {
1136     base::FilePath cookie_path(
1137         SafeBrowsingService::GetCookieFilePathForTesting());
1138     EXPECT_FALSE(base::PathExists(cookie_path));
1139
1140     base::FilePath test_dir;
1141     if (!PathService::Get(chrome::DIR_TEST_DATA, &test_dir)) {
1142       EXPECT_TRUE(false);
1143       return false;
1144     }
1145
1146     // Initialize the SafeBrowsing cookies with a pre-created cookie store.  It
1147     // contains a single cookie, for domain 127.0.0.1, with value a=b, and
1148     // expires in 2038.
1149     base::FilePath initial_cookies = test_dir.AppendASCII("safe_browsing")
1150         .AppendASCII("Safe Browsing Cookies");
1151     if (!base::CopyFile(initial_cookies, cookie_path)) {
1152       EXPECT_TRUE(false);
1153       return false;
1154     }
1155
1156     sql::Connection db;
1157     if (!db.Open(cookie_path)) {
1158       EXPECT_TRUE(false);
1159       return false;
1160     }
1161     // Ensure the host value in the cookie file matches the test server we will
1162     // be connecting to.
1163     sql::Statement smt(db.GetUniqueStatement(
1164         "UPDATE cookies SET host_key = ?"));
1165     if (!smt.is_valid()) {
1166       EXPECT_TRUE(false);
1167       return false;
1168     }
1169     if (!smt.BindString(0, test_server()->host_port_pair().host())) {
1170       EXPECT_TRUE(false);
1171       return false;
1172     }
1173     if (!smt.Run()) {
1174       EXPECT_TRUE(false);
1175       return false;
1176     }
1177
1178     return InProcessBrowserTest::SetUpUserDataDirectory();
1179   }
1180
1181   void TearDownInProcessBrowserTestFixture() override {
1182     InProcessBrowserTest::TearDownInProcessBrowserTestFixture();
1183
1184     sql::Connection db;
1185     base::FilePath cookie_path(
1186         SafeBrowsingService::GetCookieFilePathForTesting());
1187     ASSERT_TRUE(db.Open(cookie_path));
1188
1189     sql::Statement smt(db.GetUniqueStatement(
1190         "SELECT name, value FROM cookies ORDER BY name"));
1191     ASSERT_TRUE(smt.is_valid());
1192
1193     ASSERT_TRUE(smt.Step());
1194     ASSERT_EQ("a", smt.ColumnString(0));
1195     ASSERT_EQ("b", smt.ColumnString(1));
1196     ASSERT_TRUE(smt.Step());
1197     ASSERT_EQ("c", smt.ColumnString(0));
1198     ASSERT_EQ("d", smt.ColumnString(1));
1199     EXPECT_FALSE(smt.Step());
1200   }
1201
1202   void SetUpOnMainThread() override {
1203     sb_service_ = g_browser_process->safe_browsing_service();
1204     ASSERT_TRUE(sb_service_.get() != NULL);
1205   }
1206
1207   void TearDownOnMainThread() override { sb_service_ = NULL; }
1208
1209   void ForceUpdate() {
1210     sb_service_->protocol_manager()->ForceScheduleNextUpdate(
1211         base::TimeDelta::FromSeconds(0));
1212   }
1213
1214   scoped_refptr<SafeBrowsingService> sb_service_;
1215
1216  private:
1217   scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
1218
1219   DISALLOW_COPY_AND_ASSIGN(SafeBrowsingDatabaseManagerCookieTest);
1220 };
1221
1222 // Test that a Safe Browsing database update request both sends cookies and can
1223 // save cookies.
1224 IN_PROC_BROWSER_TEST_F(SafeBrowsingDatabaseManagerCookieTest,
1225                        TestSBUpdateCookies) {
1226   content::WindowedNotificationObserver observer(
1227       chrome::NOTIFICATION_SAFE_BROWSING_UPDATE_COMPLETE,
1228       content::Source<SafeBrowsingDatabaseManager>(
1229           sb_service_->database_manager().get()));
1230   BrowserThread::PostTask(
1231       BrowserThread::IO,
1232       FROM_HERE,
1233       base::Bind(&SafeBrowsingDatabaseManagerCookieTest::ForceUpdate, this));
1234   observer.Wait();
1235 }