Add domain request detection to incident reporting service.
[chromium-blink-merge.git] / chrome / browser / safe_browsing / safe_browsing_service_browsertest.cc
blob8923d648b91923b756b47593eb533d45c397f06b
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.
9 #include <algorithm>
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"
50 #if defined(OS_CHROMEOS)
51 #include "chrome/browser/chromeos/profiles/profile_helper.h"
52 #include "chromeos/chromeos_switches.h"
53 #endif
55 using content::BrowserThread;
56 using content::InterstitialPage;
57 using content::WebContents;
58 using ::testing::_;
59 using ::testing::Mock;
60 using ::testing::StrictMock;
62 namespace {
64 void InvokeFullHashCallback(
65 SafeBrowsingProtocolManager::FullHashCallback callback,
66 const std::vector<SBFullHashResult>& result) {
67 callback.Run(result, base::TimeDelta::FromMinutes(45));
70 class FakeSafeBrowsingService : public SafeBrowsingService {
71 public:
72 explicit FakeSafeBrowsingService(const std::string& url_prefix)
73 : url_prefix_(url_prefix) {}
75 SafeBrowsingProtocolConfig GetProtocolConfig() const override {
76 SafeBrowsingProtocolConfig config;
77 config.url_prefix = url_prefix_;
78 // Makes sure the auto update is not triggered. The tests will force the
79 // update when needed.
80 config.disable_auto_update = true;
81 #if defined(OS_ANDROID)
82 config.disable_connection_check = true;
83 #endif
84 config.client_name = "browser_tests";
85 return config;
88 private:
89 ~FakeSafeBrowsingService() override {}
91 std::string url_prefix_;
93 DISALLOW_COPY_AND_ASSIGN(FakeSafeBrowsingService);
96 // Factory that creates FakeSafeBrowsingService instances.
97 class TestSafeBrowsingServiceFactory : public SafeBrowsingServiceFactory {
98 public:
99 explicit TestSafeBrowsingServiceFactory(const std::string& url_prefix)
100 : url_prefix_(url_prefix) {}
102 SafeBrowsingService* CreateSafeBrowsingService() override {
103 return new FakeSafeBrowsingService(url_prefix_);
106 private:
107 std::string url_prefix_;
110 // A SafeBrowingDatabase class that allows us to inject the malicious URLs.
111 class TestSafeBrowsingDatabase : public SafeBrowsingDatabase {
112 public:
113 TestSafeBrowsingDatabase() {}
115 ~TestSafeBrowsingDatabase() override {}
117 // Initializes the database with the given filename.
118 void Init(const base::FilePath& filename) override {}
120 // Deletes the current database and creates a new one.
121 bool ResetDatabase() override {
122 badurls_.clear();
123 return true;
126 // Called on the IO thread to check if the given URL is safe or not. If we
127 // can synchronously determine that the URL is safe, CheckUrl returns true,
128 // otherwise it returns false.
129 bool ContainsBrowseUrl(const GURL& url,
130 std::vector<SBPrefix>* prefix_hits,
131 std::vector<SBFullHashResult>* cache_hits) override {
132 cache_hits->clear();
133 return ContainsUrl(safe_browsing_util::MALWARE,
134 safe_browsing_util::PHISH,
135 std::vector<GURL>(1, url),
136 prefix_hits);
138 bool ContainsUnwantedSoftwareUrl(
139 const GURL& url,
140 std::vector<SBPrefix>* prefix_hits,
141 std::vector<SBFullHashResult>* cache_hits) override {
142 cache_hits->clear();
143 return ContainsUrl(safe_browsing_util::UNWANTEDURL,
144 safe_browsing_util::UNWANTEDURL,
145 std::vector<GURL>(1, url),
146 prefix_hits);
148 bool ContainsDownloadUrlPrefixes(
149 const std::vector<SBPrefix>& prefixes,
150 std::vector<SBPrefix>* prefix_hits) override {
151 bool found =
152 ContainsUrlPrefixes(safe_browsing_util::BINURL,
153 safe_browsing_util::BINURL, prefixes, prefix_hits);
154 if (!found)
155 return false;
156 DCHECK_LE(1U, prefix_hits->size());
157 return true;
159 bool ContainsCsdWhitelistedUrl(const GURL& url) override { return true; }
160 bool ContainsDownloadWhitelistedString(const std::string& str) override {
161 return true;
163 bool ContainsDownloadWhitelistedUrl(const GURL& url) override { return true; }
164 bool ContainsInclusionWhitelistedUrl(const GURL& url) override {
165 return true;
167 bool ContainsExtensionPrefixes(const std::vector<SBPrefix>& prefixes,
168 std::vector<SBPrefix>* prefix_hits) override {
169 return false;
171 bool ContainsSideEffectFreeWhitelistUrl(const GURL& url) override {
172 return true;
174 bool ContainsMalwareIP(const std::string& ip_address) override {
175 return true;
177 bool UpdateStarted(std::vector<SBListChunkRanges>* lists) override {
178 ADD_FAILURE() << "Not implemented.";
179 return false;
181 void InsertChunks(const std::string& list_name,
182 const std::vector<SBChunkData*>& chunks) override {
183 ADD_FAILURE() << "Not implemented.";
185 void DeleteChunks(const std::vector<SBChunkDelete>& chunk_deletes) override {
186 ADD_FAILURE() << "Not implemented.";
188 void UpdateFinished(bool update_succeeded) override {
189 ADD_FAILURE() << "Not implemented.";
191 void CacheHashResults(const std::vector<SBPrefix>& prefixes,
192 const std::vector<SBFullHashResult>& cache_hits,
193 const base::TimeDelta& cache_lifetime) override {
194 // Do nothing for the cache.
196 bool IsMalwareIPMatchKillSwitchOn() override { return false; }
197 bool IsCsdWhitelistKillSwitchOn() override { return false; }
199 // Fill up the database with test URL.
200 void AddUrl(const GURL& url,
201 const SBFullHashResult& full_hash,
202 const std::vector<SBPrefix>& prefix_hits) {
203 Hits* hits_for_url = &badurls_[url.spec()];
204 hits_for_url->list_ids.push_back(full_hash.list_id);
205 hits_for_url->prefix_hits.insert(hits_for_url->prefix_hits.end(),
206 prefix_hits.begin(),
207 prefix_hits.end());
208 bad_prefixes_.insert(
209 std::make_pair(full_hash.list_id, full_hash.hash.prefix));
212 private:
213 // Stores |list_ids| of safe browsing lists that match some |prefix_hits|.
214 struct Hits {
215 std::vector<int> list_ids;
216 std::vector<SBPrefix> prefix_hits;
219 bool ContainsUrl(int list_id0,
220 int list_id1,
221 const std::vector<GURL>& urls,
222 std::vector<SBPrefix>* prefix_hits) {
223 bool hit = false;
224 for (const GURL& url : urls) {
225 base::hash_map<std::string, Hits>::const_iterator
226 badurls_it = badurls_.find(url.spec());
228 if (badurls_it == badurls_.end())
229 continue;
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;
242 return hit;
245 bool ContainsUrlPrefixes(int list_id0,
246 int list_id1,
247 const std::vector<SBPrefix>& prefixes,
248 std::vector<SBPrefix>* prefix_hits) {
249 bool hit = false;
250 for (const SBPrefix& prefix : prefixes) {
251 for (const std::pair<int, SBPrefix>& entry : bad_prefixes_) {
252 if (entry.second == prefix &&
253 (entry.first == list_id0 || entry.first == list_id1)) {
254 prefix_hits->push_back(prefix);
255 hit = true;
259 return hit;
262 base::hash_map<std::string, Hits> badurls_;
263 base::hash_set<std::pair<int, SBPrefix>> bad_prefixes_;
265 DISALLOW_COPY_AND_ASSIGN(TestSafeBrowsingDatabase);
268 // Factory that creates TestSafeBrowsingDatabase instances.
269 class TestSafeBrowsingDatabaseFactory : public SafeBrowsingDatabaseFactory {
270 public:
271 TestSafeBrowsingDatabaseFactory() : db_(NULL) {}
272 ~TestSafeBrowsingDatabaseFactory() override {}
274 SafeBrowsingDatabase* CreateSafeBrowsingDatabase(
275 const scoped_refptr<base::SequencedTaskRunner>& db_task_runner,
276 bool enable_download_protection,
277 bool enable_client_side_whitelist,
278 bool enable_download_whitelist,
279 bool enable_extension_blacklist,
280 bool enable_side_effect_free_whitelist,
281 bool enable_ip_blacklist,
282 bool enabled_unwanted_software_list) override {
283 db_ = new TestSafeBrowsingDatabase();
284 return db_;
286 TestSafeBrowsingDatabase* GetDb() {
287 return db_;
289 private:
290 // Owned by the SafebrowsingService.
291 TestSafeBrowsingDatabase* db_;
294 // A TestProtocolManager that could return fixed responses from
295 // safebrowsing server for testing purpose.
296 class TestProtocolManager : public SafeBrowsingProtocolManager {
297 public:
298 TestProtocolManager(SafeBrowsingProtocolManagerDelegate* delegate,
299 net::URLRequestContextGetter* request_context_getter,
300 const SafeBrowsingProtocolConfig& config)
301 : SafeBrowsingProtocolManager(delegate, request_context_getter, config) {
302 create_count_++;
305 ~TestProtocolManager() override { delete_count_++; }
307 // This function is called when there is a prefix hit in local safebrowsing
308 // database and safebrowsing service issues a get hash request to backends.
309 // We return a result from the prefilled full_hashes_ hash_map to simulate
310 // server's response. At the same time, latency is added to simulate real
311 // life network issues.
312 void GetFullHash(const std::vector<SBPrefix>& prefixes,
313 SafeBrowsingProtocolManager::FullHashCallback callback,
314 bool is_download) override {
315 BrowserThread::PostDelayedTask(
316 BrowserThread::IO, FROM_HERE,
317 base::Bind(InvokeFullHashCallback, callback, full_hashes_),
318 delay_);
321 // Prepare the GetFullHash results for the next request.
322 void AddGetFullHashResponse(const SBFullHashResult& full_hash_result) {
323 full_hashes_.push_back(full_hash_result);
326 void IntroduceDelay(const base::TimeDelta& delay) {
327 delay_ = delay;
330 static int create_count() {
331 return create_count_;
334 static int delete_count() {
335 return delete_count_;
338 private:
339 std::vector<SBFullHashResult> full_hashes_;
340 base::TimeDelta delay_;
341 static int create_count_;
342 static int delete_count_;
345 // static
346 int TestProtocolManager::create_count_ = 0;
347 // static
348 int TestProtocolManager::delete_count_ = 0;
350 // Factory that creates TestProtocolManager instances.
351 class TestSBProtocolManagerFactory : public SBProtocolManagerFactory {
352 public:
353 TestSBProtocolManagerFactory() : pm_(NULL) {}
354 ~TestSBProtocolManagerFactory() override {}
356 SafeBrowsingProtocolManager* CreateProtocolManager(
357 SafeBrowsingProtocolManagerDelegate* delegate,
358 net::URLRequestContextGetter* request_context_getter,
359 const SafeBrowsingProtocolConfig& config) override {
360 pm_ = new TestProtocolManager(delegate, request_context_getter, config);
361 return pm_;
364 TestProtocolManager* GetProtocolManager() {
365 return pm_;
368 private:
369 // Owned by the SafebrowsingService.
370 TestProtocolManager* pm_;
373 class MockObserver : public SafeBrowsingUIManager::Observer {
374 public:
375 MockObserver() {}
376 virtual ~MockObserver() {}
377 MOCK_METHOD1(OnSafeBrowsingHit,
378 void(const SafeBrowsingUIManager::UnsafeResource&));
379 MOCK_METHOD1(OnSafeBrowsingMatch,
380 void(const SafeBrowsingUIManager::UnsafeResource&));
383 MATCHER_P(IsUnsafeResourceFor, url, "") {
384 return (arg.url.spec() == url.spec() &&
385 arg.threat_type != SB_THREAT_TYPE_SAFE);
388 } // namespace
390 // Tests the safe browsing blocking page in a browser.
391 class SafeBrowsingServiceTest : public InProcessBrowserTest {
392 public:
393 SafeBrowsingServiceTest() {
396 static void GenUrlFullhashResult(const GURL& url,
397 int list_id,
398 SBFullHashResult* full_hash) {
399 std::string host;
400 std::string path;
401 safe_browsing_util::CanonicalizeUrl(url, &host, &path, NULL);
402 full_hash->hash = SBFullHashForString(host + path);
403 full_hash->list_id = list_id;
406 virtual void SetUp() {
407 // InProcessBrowserTest::SetUp() instantiates SafebrowsingService and
408 // RegisterFactory has to be called before SafeBrowsingService is created.
409 sb_factory_.reset(new TestSafeBrowsingServiceFactory(
410 "https://definatelynotarealdomain/safebrowsing"));
411 SafeBrowsingService::RegisterFactory(sb_factory_.get());
412 SafeBrowsingDatabase::RegisterFactory(&db_factory_);
413 SafeBrowsingProtocolManager::RegisterFactory(&pm_factory_);
414 InProcessBrowserTest::SetUp();
417 virtual void TearDown() {
418 InProcessBrowserTest::TearDown();
420 // Unregister test factories after InProcessBrowserTest::TearDown
421 // (which destructs SafeBrowsingService).
422 SafeBrowsingDatabase::RegisterFactory(NULL);
423 SafeBrowsingProtocolManager::RegisterFactory(NULL);
424 SafeBrowsingService::RegisterFactory(NULL);
427 virtual void SetUpCommandLine(base::CommandLine* command_line) override {
428 // Makes sure the auto update is not triggered during the test.
429 // This test will fill up the database using testing prefixes
430 // and urls.
431 command_line->AppendSwitch(switches::kSbDisableAutoUpdate);
432 #if defined(OS_CHROMEOS)
433 command_line->AppendSwitch(
434 chromeos::switches::kIgnoreUserProfileMappingForTests);
435 #endif
438 void SetUpOnMainThread() override {
439 InProcessBrowserTest::SetUpOnMainThread();
440 g_browser_process->safe_browsing_service()->ui_manager()->AddObserver(
441 &observer_);
444 void TearDownOnMainThread() override {
445 g_browser_process->safe_browsing_service()->ui_manager()->RemoveObserver(
446 &observer_);
447 InProcessBrowserTest::TearDownOnMainThread();
450 virtual void SetUpInProcessBrowserTestFixture() {
451 ASSERT_TRUE(test_server()->Start());
454 // This will setup the "url" prefix in database and prepare protocol manager
455 // to respond with |full_hash|, as well as other |full_hash|es previously set
456 // via this call, on GetFullHash requests.
457 void SetupResponseForUrl(const GURL& url, const SBFullHashResult& full_hash) {
458 std::vector<SBPrefix> prefix_hits;
459 prefix_hits.push_back(full_hash.hash.prefix);
461 // Make sure the full hits is empty unless we need to test the
462 // full hash is hit in database's local cache.
463 TestSafeBrowsingDatabase* db = db_factory_.GetDb();
464 db->AddUrl(url, full_hash, prefix_hits);
466 TestProtocolManager* pm = pm_factory_.GetProtocolManager();
467 pm->AddGetFullHashResponse(full_hash);
470 bool ShowingInterstitialPage() {
471 WebContents* contents =
472 browser()->tab_strip_model()->GetActiveWebContents();
473 InterstitialPage* interstitial_page = contents->GetInterstitialPage();
474 return interstitial_page != NULL;
477 void IntroduceGetHashDelay(const base::TimeDelta& delay) {
478 pm_factory_.GetProtocolManager()->IntroduceDelay(delay);
481 base::TimeDelta GetCheckTimeout(SafeBrowsingService* sb_service) {
482 return sb_service->database_manager()->check_timeout_;
485 void SetCheckTimeout(SafeBrowsingService* sb_service,
486 const base::TimeDelta& delay) {
487 sb_service->database_manager()->check_timeout_ = delay;
490 void CreateCSDService() {
491 safe_browsing::ClientSideDetectionService* csd_service =
492 safe_browsing::ClientSideDetectionService::Create(NULL);
493 SafeBrowsingService* sb_service =
494 g_browser_process->safe_browsing_service();
495 sb_service->csd_service_.reset(csd_service);
496 sb_service->RefreshState();
499 void ProceedAndWhitelist(
500 const SafeBrowsingUIManager::UnsafeResource& resource) {
501 std::vector<SafeBrowsingUIManager::UnsafeResource> resources;
502 resources.push_back(resource);
503 BrowserThread::PostTask(
504 BrowserThread::IO, FROM_HERE,
505 base::Bind(&SafeBrowsingUIManager::OnBlockingPageDone,
506 g_browser_process->safe_browsing_service()->ui_manager(),
507 resources, true));
508 WaitForIOThread();
511 protected:
512 StrictMock<MockObserver> observer_;
514 // Temporary profile dir for test cases that create a second profile. This is
515 // owned by the SafeBrowsingServiceTest object so that it will not get
516 // destructed until after the test Browser has been torn down, since the
517 // ImportantFileWriter may still be modifying it after the Profile object has
518 // been destroyed.
519 base::ScopedTempDir temp_profile_dir_;
521 // Waits for pending tasks on the IO thread to complete. This is useful
522 // to wait for the SafeBrowsingService to finish loading/stopping.
523 void WaitForIOThread() {
524 scoped_refptr<base::ThreadTestHelper> io_helper(new base::ThreadTestHelper(
525 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get()));
526 ASSERT_TRUE(io_helper->Run());
529 private:
530 scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
531 TestSafeBrowsingDatabaseFactory db_factory_;
532 TestSBProtocolManagerFactory pm_factory_;
534 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTest);
537 enum MalwareMetadataTestType {
538 METADATA_NONE,
539 METADATA_LANDING,
540 METADATA_DISTRIBUTION,
543 class SafeBrowsingServiceMetadataTest
544 : public SafeBrowsingServiceTest,
545 public ::testing::WithParamInterface<MalwareMetadataTestType> {
546 public:
547 SafeBrowsingServiceMetadataTest() {}
549 void GenUrlFullhashResultWithMetadata(const GURL& url,
550 SBFullHashResult* full_hash) {
551 GenUrlFullhashResult(url, safe_browsing_util::MALWARE, full_hash);
553 safe_browsing::MalwarePatternType proto;
554 switch (GetParam()) {
555 case METADATA_NONE:
556 full_hash->metadata = std::string();
557 break;
558 case METADATA_LANDING:
559 proto.set_pattern_type(safe_browsing::MalwarePatternType::LANDING);
560 full_hash->metadata = proto.SerializeAsString();
561 break;
562 case METADATA_DISTRIBUTION:
563 proto.set_pattern_type(safe_browsing::MalwarePatternType::DISTRIBUTION);
564 full_hash->metadata = proto.SerializeAsString();
565 break;
569 private:
570 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceMetadataTest);
573 namespace {
575 const char kEmptyPage[] = "files/empty.html";
576 const char kMalwareFile[] = "files/downloads/dangerous/dangerous.exe";
577 const char kMalwarePage[] = "files/safe_browsing/malware.html";
578 const char kMalwareIFrame[] = "files/safe_browsing/malware_iframe.html";
579 const char kMalwareImg[] = "files/safe_browsing/malware_image.png";
581 // This test goes through DownloadResourceHandler.
582 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareMainFrame) {
583 GURL url = test_server()->GetURL(kEmptyPage);
585 // After adding the url to safebrowsing database and getfullhash result,
586 // we should see the interstitial page.
587 SBFullHashResult malware_full_hash;
588 GenUrlFullhashResultWithMetadata(url, &malware_full_hash);
589 EXPECT_CALL(observer_,
590 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
591 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1);
592 SetupResponseForUrl(url, malware_full_hash);
593 ui_test_utils::NavigateToURL(browser(), url);
594 // All types should show the interstitial.
595 EXPECT_TRUE(ShowingInterstitialPage());
598 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareIFrame) {
599 GURL main_url = test_server()->GetURL(kMalwarePage);
600 GURL iframe_url = test_server()->GetURL(kMalwareIFrame);
602 // Add the iframe url as malware and then load the parent page.
603 SBFullHashResult malware_full_hash;
604 GenUrlFullhashResultWithMetadata(iframe_url, &malware_full_hash);
605 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(iframe_url)))
606 .Times(1);
607 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(iframe_url)))
608 .Times(1);
609 SetupResponseForUrl(iframe_url, malware_full_hash);
610 ui_test_utils::NavigateToURL(browser(), main_url);
611 // All types should show the interstitial.
612 EXPECT_TRUE(ShowingInterstitialPage());
615 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareImg) {
616 GURL main_url = test_server()->GetURL(kMalwarePage);
617 GURL img_url = test_server()->GetURL(kMalwareImg);
619 // Add the img url as malware and then load the parent page.
620 SBFullHashResult malware_full_hash;
621 GenUrlFullhashResultWithMetadata(img_url, &malware_full_hash);
622 switch (GetParam()) {
623 case METADATA_NONE: // Falls through.
624 case METADATA_DISTRIBUTION:
625 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(img_url)))
626 .Times(1);
627 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(img_url)))
628 .Times(1);
629 break;
630 case METADATA_LANDING:
631 // No interstitial shown, so no notifications expected.
632 break;
634 SetupResponseForUrl(img_url, malware_full_hash);
635 ui_test_utils::NavigateToURL(browser(), main_url);
636 // Subresource which is tagged as a landing page should not show an
637 // interstitial, the other types should.
638 switch (GetParam()) {
639 case METADATA_NONE:
640 case METADATA_DISTRIBUTION:
641 EXPECT_TRUE(ShowingInterstitialPage());
642 break;
643 case METADATA_LANDING:
644 EXPECT_FALSE(ShowingInterstitialPage());
645 break;
649 INSTANTIATE_TEST_CASE_P(MaybeSetMetadata,
650 SafeBrowsingServiceMetadataTest,
651 testing::Values(METADATA_NONE,
652 METADATA_LANDING,
653 METADATA_DISTRIBUTION));
655 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, UnwantedImgIgnored) {
656 GURL main_url = test_server()->GetURL(kMalwarePage);
657 GURL img_url = test_server()->GetURL(kMalwareImg);
659 // Add the img url as coming from a site serving UwS and then load the parent
660 // page.
661 SBFullHashResult uws_full_hash;
662 GenUrlFullhashResult(img_url, safe_browsing_util::UNWANTEDURL,
663 &uws_full_hash);
664 SetupResponseForUrl(img_url, uws_full_hash);
666 ui_test_utils::NavigateToURL(browser(), main_url);
668 EXPECT_FALSE(ShowingInterstitialPage());
671 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, DISABLED_MalwareWithWhitelist) {
672 GURL url = test_server()->GetURL(kEmptyPage);
674 // After adding the url to safebrowsing database and getfullhash result,
675 // we should see the interstitial page.
676 SBFullHashResult malware_full_hash;
677 GenUrlFullhashResult(url, safe_browsing_util::MALWARE, &malware_full_hash);
678 EXPECT_CALL(observer_,
679 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
680 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1)
681 .WillOnce(testing::Invoke(
682 this, &SafeBrowsingServiceTest::ProceedAndWhitelist));
683 SetupResponseForUrl(url, malware_full_hash);
685 ui_test_utils::NavigateToURL(browser(), url);
686 // Mock calls OnBlockingPageDone set to proceed, so the interstitial
687 // is removed.
688 EXPECT_FALSE(ShowingInterstitialPage());
689 Mock::VerifyAndClearExpectations(&observer_);
691 // Navigate back to kEmptyPage -- should hit the whitelist, and send a match
692 // call, but no hit call.
693 EXPECT_CALL(observer_,
694 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
695 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(0);
696 ui_test_utils::NavigateToURL(browser(), url);
697 EXPECT_FALSE(ShowingInterstitialPage());
700 const char kPrefetchMalwarePage[] = "files/safe_browsing/prefetch_malware.html";
702 // This test confirms that prefetches don't themselves get the
703 // interstitial treatment.
704 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, Prefetch) {
705 GURL url = test_server()->GetURL(kPrefetchMalwarePage);
706 GURL malware_url = test_server()->GetURL(kMalwarePage);
708 class SetPrefetchForTest {
709 public:
710 explicit SetPrefetchForTest(bool prefetch)
711 : old_prerender_mode_(prerender::PrerenderManager::GetMode()) {
712 std::string exp_group = prefetch ? "ExperimentYes" : "ExperimentNo";
713 base::FieldTrialList::CreateFieldTrial("Prefetch", exp_group);
715 prerender::PrerenderManager::SetMode(
716 prerender::PrerenderManager::PRERENDER_MODE_DISABLED);
719 ~SetPrefetchForTest() {
720 prerender::PrerenderManager::SetMode(old_prerender_mode_);
723 private:
724 prerender::PrerenderManager::PrerenderManagerMode old_prerender_mode_;
725 } set_prefetch_for_test(true);
727 // Even though we have added this uri to the safebrowsing database and
728 // getfullhash result, we should not see the interstitial page since the
729 // only malware was a prefetch target.
730 SBFullHashResult malware_full_hash;
731 GenUrlFullhashResult(malware_url, safe_browsing_util::MALWARE,
732 &malware_full_hash);
733 SetupResponseForUrl(malware_url, malware_full_hash);
734 ui_test_utils::NavigateToURL(browser(), url);
735 EXPECT_FALSE(ShowingInterstitialPage());
736 Mock::VerifyAndClear(&observer_);
738 // However, when we navigate to the malware page, we should still get
739 // the interstitial.
740 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(malware_url)))
741 .Times(1);
742 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(malware_url)))
743 .Times(1);
744 ui_test_utils::NavigateToURL(browser(), malware_url);
745 EXPECT_TRUE(ShowingInterstitialPage());
746 Mock::VerifyAndClear(&observer_);
749 } // namespace
751 class TestSBClient
752 : public base::RefCountedThreadSafe<TestSBClient>,
753 public SafeBrowsingDatabaseManager::Client {
754 public:
755 TestSBClient()
756 : threat_type_(SB_THREAT_TYPE_SAFE),
757 safe_browsing_service_(g_browser_process->safe_browsing_service()) {
760 SBThreatType GetThreatType() const {
761 return threat_type_;
764 void CheckDownloadUrl(const std::vector<GURL>& url_chain) {
765 BrowserThread::PostTask(
766 BrowserThread::IO, FROM_HERE,
767 base::Bind(&TestSBClient::CheckDownloadUrlOnIOThread,
768 this, url_chain));
769 content::RunMessageLoop(); // Will stop in OnCheckDownloadUrlResult.
772 void CheckBrowseUrl(const GURL& url) {
773 BrowserThread::PostTask(
774 BrowserThread::IO, FROM_HERE,
775 base::Bind(&TestSBClient::CheckBrowseUrlOnIOThread, this, url));
776 content::RunMessageLoop(); // Will stop in OnCheckBrowseUrlResult.
779 private:
780 friend class base::RefCountedThreadSafe<TestSBClient>;
781 ~TestSBClient() override {}
783 void CheckDownloadUrlOnIOThread(const std::vector<GURL>& url_chain) {
784 bool synchronous_safe_signal =
785 safe_browsing_service_->database_manager()->CheckDownloadUrl(url_chain,
786 this);
787 if (synchronous_safe_signal) {
788 threat_type_ = SB_THREAT_TYPE_SAFE;
789 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
790 base::Bind(&TestSBClient::CheckDone, this));
794 void CheckBrowseUrlOnIOThread(const GURL& url) {
795 // The async CheckDone() hook will not be called when we have a synchronous
796 // safe signal, handle it right away.
797 bool synchronous_safe_signal =
798 safe_browsing_service_->database_manager()->CheckBrowseUrl(url, this);
799 if (synchronous_safe_signal) {
800 threat_type_ = SB_THREAT_TYPE_SAFE;
801 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
802 base::Bind(&TestSBClient::CheckDone, this));
806 // Called when the result of checking a download URL is known.
807 void OnCheckDownloadUrlResult(const std::vector<GURL>& /* url_chain */,
808 SBThreatType threat_type) override {
809 threat_type_ = threat_type;
810 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
811 base::Bind(&TestSBClient::CheckDone, this));
814 // Called when the result of checking a browse URL is known.
815 void OnCheckBrowseUrlResult(const GURL& /* url */,
816 SBThreatType threat_type,
817 const std::string& /* metadata */) override {
818 threat_type_ = threat_type;
819 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
820 base::Bind(&TestSBClient::CheckDone, this));
823 void CheckDone() {
824 base::MessageLoopForUI::current()->Quit();
827 SBThreatType threat_type_;
828 SafeBrowsingService* safe_browsing_service_;
830 DISALLOW_COPY_AND_ASSIGN(TestSBClient);
833 // These tests use SafeBrowsingService::Client to directly interact with
834 // SafeBrowsingService.
835 namespace {
837 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrl) {
838 GURL badbin_url = test_server()->GetURL(kMalwareFile);
839 std::vector<GURL> badbin_urls(1, badbin_url);
841 scoped_refptr<TestSBClient> client(new TestSBClient);
842 client->CheckDownloadUrl(badbin_urls);
844 // Since badbin_url is not in database, it is considered to be safe.
845 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
847 SBFullHashResult full_hash_result;
848 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
849 &full_hash_result);
850 SetupResponseForUrl(badbin_url, full_hash_result);
852 client->CheckDownloadUrl(badbin_urls);
854 // Now, the badbin_url is not safe since it is added to download database.
855 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
858 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckUnwantedSoftwareUrl) {
859 const GURL bad_url = test_server()->GetURL(kMalwareFile);
861 scoped_refptr<TestSBClient> client(new TestSBClient);
863 // Since bad_url is not in database, it is considered to be
864 // safe.
865 client->CheckBrowseUrl(bad_url);
866 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
868 SBFullHashResult full_hash_result;
869 GenUrlFullhashResult(
870 bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
871 SetupResponseForUrl(bad_url, full_hash_result);
873 // Now, the bad_url is not safe since it is added to download
874 // database.
875 client->CheckBrowseUrl(bad_url);
876 EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
879 // The unwantedness should survive across multiple clients.
881 scoped_refptr<TestSBClient> client(new TestSBClient);
882 client->CheckBrowseUrl(bad_url);
883 EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
886 // An unwanted URL also marked as malware should be flagged as malware.
888 scoped_refptr<TestSBClient> client(new TestSBClient);
890 SBFullHashResult full_hash_result;
891 GenUrlFullhashResult(
892 bad_url, safe_browsing_util::MALWARE, &full_hash_result);
893 SetupResponseForUrl(bad_url, full_hash_result);
895 client->CheckBrowseUrl(bad_url);
896 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
900 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckBrowseUrl) {
901 const GURL bad_url = test_server()->GetURL(kMalwareFile);
903 scoped_refptr<TestSBClient> client(new TestSBClient);
905 // Since bad_url is not in database, it is considered to be
906 // safe.
907 client->CheckBrowseUrl(bad_url);
908 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
910 SBFullHashResult full_hash_result;
911 GenUrlFullhashResult(
912 bad_url, safe_browsing_util::MALWARE, &full_hash_result);
913 SetupResponseForUrl(bad_url, full_hash_result);
915 // Now, the bad_url is not safe since it is added to download
916 // database.
917 client->CheckBrowseUrl(bad_url);
918 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
921 // The unwantedness should survive across multiple clients.
923 scoped_refptr<TestSBClient> client(new TestSBClient);
924 client->CheckBrowseUrl(bad_url);
925 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
928 // Adding the unwanted state to an existing malware URL should have no impact
929 // (i.e. a malware hit should still prevail).
931 scoped_refptr<TestSBClient> client(new TestSBClient);
933 SBFullHashResult full_hash_result;
934 GenUrlFullhashResult(
935 bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
936 SetupResponseForUrl(bad_url, full_hash_result);
938 client->CheckBrowseUrl(bad_url);
939 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
943 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrlRedirects) {
944 GURL original_url = test_server()->GetURL(kEmptyPage);
945 GURL badbin_url = test_server()->GetURL(kMalwareFile);
946 GURL final_url = test_server()->GetURL(kEmptyPage);
947 std::vector<GURL> badbin_urls;
948 badbin_urls.push_back(original_url);
949 badbin_urls.push_back(badbin_url);
950 badbin_urls.push_back(final_url);
952 scoped_refptr<TestSBClient> client(new TestSBClient);
953 client->CheckDownloadUrl(badbin_urls);
955 // Since badbin_url is not in database, it is considered to be safe.
956 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
958 SBFullHashResult full_hash_result;
959 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
960 &full_hash_result);
961 SetupResponseForUrl(badbin_url, full_hash_result);
963 client->CheckDownloadUrl(badbin_urls);
965 // Now, the badbin_url is not safe since it is added to download database.
966 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
969 #if defined(OS_WIN)
970 // http://crbug.com/396409
971 #define MAYBE_CheckDownloadUrlTimedOut DISABLED_CheckDownloadUrlTimedOut
972 #else
973 #define MAYBE_CheckDownloadUrlTimedOut CheckDownloadUrlTimedOut
974 #endif
975 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest,
976 MAYBE_CheckDownloadUrlTimedOut) {
977 GURL badbin_url = test_server()->GetURL(kMalwareFile);
978 std::vector<GURL> badbin_urls(1, badbin_url);
980 scoped_refptr<TestSBClient> client(new TestSBClient);
981 SBFullHashResult full_hash_result;
982 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
983 &full_hash_result);
984 SetupResponseForUrl(badbin_url, full_hash_result);
985 client->CheckDownloadUrl(badbin_urls);
987 // badbin_url is not safe since it is added to download database.
988 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
991 // Now introducing delays and we should hit timeout.
993 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
994 base::TimeDelta default_urlcheck_timeout = GetCheckTimeout(sb_service);
995 IntroduceGetHashDelay(base::TimeDelta::FromSeconds(1));
996 SetCheckTimeout(sb_service, base::TimeDelta::FromMilliseconds(1));
997 client->CheckDownloadUrl(badbin_urls);
999 // There should be a timeout and the hash would be considered as safe.
1000 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
1002 // Need to set the timeout back to the default value.
1003 SetCheckTimeout(sb_service, default_urlcheck_timeout);
1006 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, StartAndStop) {
1007 CreateCSDService();
1008 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
1009 safe_browsing::ClientSideDetectionService* csd_service =
1010 sb_service->safe_browsing_detection_service();
1011 PrefService* pref_service = browser()->profile()->GetPrefs();
1013 ASSERT_TRUE(sb_service != NULL);
1014 ASSERT_TRUE(csd_service != NULL);
1015 ASSERT_TRUE(pref_service != NULL);
1017 EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
1019 // SBS might still be starting, make sure this doesn't flake.
1020 WaitForIOThread();
1021 EXPECT_TRUE(sb_service->enabled());
1022 EXPECT_TRUE(csd_service->enabled());
1024 // Add a new Profile. SBS should keep running.
1025 ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
1026 scoped_ptr<Profile> profile2(Profile::CreateProfile(
1027 temp_profile_dir_.path(), NULL, Profile::CREATE_MODE_SYNCHRONOUS));
1028 ASSERT_TRUE(profile2.get() != NULL);
1029 StartupTaskRunnerServiceFactory::GetForProfile(profile2.get())->
1030 StartDeferredTaskRunners();
1031 PrefService* pref_service2 = profile2->GetPrefs();
1032 EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1033 // We don't expect the state to have changed, but if it did, wait for it.
1034 WaitForIOThread();
1035 EXPECT_TRUE(sb_service->enabled());
1036 EXPECT_TRUE(csd_service->enabled());
1038 // Change one of the prefs. SBS should keep running.
1039 pref_service->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1040 WaitForIOThread();
1041 EXPECT_TRUE(sb_service->enabled());
1042 EXPECT_TRUE(csd_service->enabled());
1044 // Change the other pref. SBS should stop now.
1045 pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1046 WaitForIOThread();
1048 // TODO(mattm): Remove this when crbug.com/461493 is fixed.
1049 #if defined(OS_CHROMEOS)
1050 // On Chrome OS we should disable safe browsing for signin profile.
1051 EXPECT_TRUE(sb_service->enabled());
1052 EXPECT_TRUE(csd_service->enabled());
1053 chromeos::ProfileHelper::GetSigninProfile()
1054 ->GetOriginalProfile()
1055 ->GetPrefs()
1056 ->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1057 WaitForIOThread();
1058 #endif
1059 EXPECT_FALSE(sb_service->enabled());
1060 EXPECT_FALSE(csd_service->enabled());
1062 // Turn it back on. SBS comes back.
1063 pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, true);
1064 WaitForIOThread();
1065 EXPECT_TRUE(sb_service->enabled());
1066 EXPECT_TRUE(csd_service->enabled());
1068 // Delete the Profile. SBS stops again.
1069 pref_service2 = NULL;
1070 profile2.reset();
1071 WaitForIOThread();
1072 EXPECT_FALSE(sb_service->enabled());
1073 EXPECT_FALSE(csd_service->enabled());
1076 } // namespace
1078 class SafeBrowsingServiceShutdownTest : public SafeBrowsingServiceTest {
1079 public:
1080 void TearDown() override {
1081 // Browser should be fully torn down by now, so we can safely check these
1082 // counters.
1083 EXPECT_EQ(1, TestProtocolManager::create_count());
1084 EXPECT_EQ(1, TestProtocolManager::delete_count());
1086 SafeBrowsingServiceTest::TearDown();
1089 // An observer that returns back to test code after a new profile is
1090 // initialized.
1091 void OnUnblockOnProfileCreation(Profile* profile,
1092 Profile::CreateStatus status) {
1093 if (status == Profile::CREATE_STATUS_INITIALIZED) {
1094 profile2_ = profile;
1095 base::MessageLoop::current()->Quit();
1099 protected:
1100 Profile* profile2_;
1103 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceShutdownTest,
1104 DontStartAfterShutdown) {
1105 CreateCSDService();
1106 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
1107 safe_browsing::ClientSideDetectionService* csd_service =
1108 sb_service->safe_browsing_detection_service();
1109 PrefService* pref_service = browser()->profile()->GetPrefs();
1111 ASSERT_TRUE(sb_service != NULL);
1112 ASSERT_TRUE(csd_service != NULL);
1113 ASSERT_TRUE(pref_service != NULL);
1115 EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
1117 // SBS might still be starting, make sure this doesn't flake.
1118 WaitForIOThread();
1119 EXPECT_EQ(1, TestProtocolManager::create_count());
1120 EXPECT_EQ(0, TestProtocolManager::delete_count());
1122 // Create an additional profile. We need to use the ProfileManager so that
1123 // the profile will get destroyed in the normal browser shutdown process.
1124 ProfileManager* profile_manager = g_browser_process->profile_manager();
1125 ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
1126 profile_manager->CreateProfileAsync(
1127 temp_profile_dir_.path(),
1128 base::Bind(&SafeBrowsingServiceShutdownTest::OnUnblockOnProfileCreation,
1129 this),
1130 base::string16(), base::string16(), std::string());
1132 // Spin to allow profile creation to take place, loop is terminated
1133 // by OnUnblockOnProfileCreation when the profile is created.
1134 content::RunMessageLoop();
1136 PrefService* pref_service2 = profile2_->GetPrefs();
1137 EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1139 // We don't expect the state to have changed, but if it did, wait for it.
1140 WaitForIOThread();
1141 EXPECT_EQ(1, TestProtocolManager::create_count());
1142 EXPECT_EQ(0, TestProtocolManager::delete_count());
1144 // End the test, shutting down the browser.
1145 // SafeBrowsingServiceShutdownTest::TearDown will check the create_count and
1146 // delete_count again.
1149 class SafeBrowsingDatabaseManagerCookieTest : public InProcessBrowserTest {
1150 public:
1151 SafeBrowsingDatabaseManagerCookieTest() {}
1153 void SetUp() override {
1154 // We need to start the test server to get the host&port in the url.
1155 ASSERT_TRUE(test_server()->Start());
1157 // Point to the testing server for all SafeBrowsing requests.
1158 GURL url_prefix = test_server()->GetURL(
1159 "expect-and-set-cookie?expect=a%3db"
1160 "&set=c%3dd%3b%20Expires=Fri,%2001%20Jan%202038%2001:01:01%20GMT"
1161 "&data=foo#");
1162 sb_factory_.reset(new TestSafeBrowsingServiceFactory(url_prefix.spec()));
1163 SafeBrowsingService::RegisterFactory(sb_factory_.get());
1165 InProcessBrowserTest::SetUp();
1168 void TearDown() override {
1169 InProcessBrowserTest::TearDown();
1171 SafeBrowsingService::RegisterFactory(NULL);
1174 bool SetUpUserDataDirectory() override {
1175 base::FilePath cookie_path(
1176 SafeBrowsingService::GetCookieFilePathForTesting());
1177 EXPECT_FALSE(base::PathExists(cookie_path));
1179 base::FilePath test_dir;
1180 if (!PathService::Get(chrome::DIR_TEST_DATA, &test_dir)) {
1181 EXPECT_TRUE(false);
1182 return false;
1185 // Initialize the SafeBrowsing cookies with a pre-created cookie store. It
1186 // contains a single cookie, for domain 127.0.0.1, with value a=b, and
1187 // expires in 2038.
1188 base::FilePath initial_cookies = test_dir.AppendASCII("safe_browsing")
1189 .AppendASCII("Safe Browsing Cookies");
1190 if (!base::CopyFile(initial_cookies, cookie_path)) {
1191 EXPECT_TRUE(false);
1192 return false;
1195 sql::Connection db;
1196 if (!db.Open(cookie_path)) {
1197 EXPECT_TRUE(false);
1198 return false;
1200 // Ensure the host value in the cookie file matches the test server we will
1201 // be connecting to.
1202 sql::Statement smt(db.GetUniqueStatement(
1203 "UPDATE cookies SET host_key = ?"));
1204 if (!smt.is_valid()) {
1205 EXPECT_TRUE(false);
1206 return false;
1208 if (!smt.BindString(0, test_server()->host_port_pair().host())) {
1209 EXPECT_TRUE(false);
1210 return false;
1212 if (!smt.Run()) {
1213 EXPECT_TRUE(false);
1214 return false;
1217 return InProcessBrowserTest::SetUpUserDataDirectory();
1220 void TearDownInProcessBrowserTestFixture() override {
1221 InProcessBrowserTest::TearDownInProcessBrowserTestFixture();
1223 sql::Connection db;
1224 base::FilePath cookie_path(
1225 SafeBrowsingService::GetCookieFilePathForTesting());
1226 ASSERT_TRUE(db.Open(cookie_path));
1228 sql::Statement smt(db.GetUniqueStatement(
1229 "SELECT name, value FROM cookies ORDER BY name"));
1230 ASSERT_TRUE(smt.is_valid());
1232 ASSERT_TRUE(smt.Step());
1233 ASSERT_EQ("a", smt.ColumnString(0));
1234 ASSERT_EQ("b", smt.ColumnString(1));
1235 ASSERT_TRUE(smt.Step());
1236 ASSERT_EQ("c", smt.ColumnString(0));
1237 ASSERT_EQ("d", smt.ColumnString(1));
1238 EXPECT_FALSE(smt.Step());
1241 void SetUpOnMainThread() override {
1242 sb_service_ = g_browser_process->safe_browsing_service();
1243 ASSERT_TRUE(sb_service_.get() != NULL);
1246 void TearDownOnMainThread() override { sb_service_ = NULL; }
1248 void ForceUpdate() {
1249 sb_service_->protocol_manager()->ForceScheduleNextUpdate(
1250 base::TimeDelta::FromSeconds(0));
1253 scoped_refptr<SafeBrowsingService> sb_service_;
1255 private:
1256 scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
1258 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingDatabaseManagerCookieTest);
1261 // Test that a Safe Browsing database update request both sends cookies and can
1262 // save cookies.
1263 IN_PROC_BROWSER_TEST_F(SafeBrowsingDatabaseManagerCookieTest,
1264 TestSBUpdateCookies) {
1265 content::WindowedNotificationObserver observer(
1266 chrome::NOTIFICATION_SAFE_BROWSING_UPDATE_COMPLETE,
1267 content::Source<SafeBrowsingDatabaseManager>(
1268 sb_service_->database_manager().get()));
1269 BrowserThread::PostTask(
1270 BrowserThread::IO,
1271 FROM_HERE,
1272 base::Bind(&SafeBrowsingDatabaseManagerCookieTest::ForceUpdate, this));
1273 observer.Wait();