ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / safe_browsing / safe_browsing_service_browsertest.cc
bloba9cb01607343ae623ccd711e68c6f7bd01fb3551
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 ContainsDownloadUrl(const std::vector<GURL>& urls,
149 std::vector<SBPrefix>* prefix_hits) override {
150 bool found = ContainsUrl(safe_browsing_util::BINURL,
151 safe_browsing_util::BINURL,
152 urls,
153 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 true;
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 int list_id,
202 const std::vector<SBPrefix>& prefix_hits) {
203 Hits* hits_for_url = &badurls_[url.spec()];
204 hits_for_url->list_ids.push_back(list_id);
205 hits_for_url->prefix_hits.insert(hits_for_url->prefix_hits.end(),
206 prefix_hits.begin(),
207 prefix_hits.end());
210 // Fill up the database with test hash digest.
211 void AddDownloadPrefix(SBPrefix prefix) {
212 download_digest_prefix_.insert(prefix);
215 private:
216 // Stores |list_ids| of safe browsing lists that match some |prefix_hits|.
217 struct Hits {
218 std::vector<int> list_ids;
219 std::vector<SBPrefix> prefix_hits;
222 bool ContainsUrl(int list_id0,
223 int list_id1,
224 const std::vector<GURL>& urls,
225 std::vector<SBPrefix>* prefix_hits) {
226 bool hit = false;
227 for (size_t i = 0; i < urls.size(); ++i) {
228 const GURL& url = urls[i];
229 base::hash_map<std::string, Hits>::const_iterator
230 badurls_it = badurls_.find(url.spec());
232 if (badurls_it == badurls_.end())
233 continue;
235 std::vector<int> list_ids_for_url = badurls_it->second.list_ids;
236 if (std::find(list_ids_for_url.begin(), list_ids_for_url.end(), list_id0)
237 != list_ids_for_url.end() ||
238 std::find(list_ids_for_url.begin(), list_ids_for_url.end(), list_id1)
239 != list_ids_for_url.end()) {
240 prefix_hits->insert(prefix_hits->end(),
241 badurls_it->second.prefix_hits.begin(),
242 badurls_it->second.prefix_hits.end());
243 hit = true;
246 return hit;
249 base::hash_map<std::string, Hits> badurls_;
250 base::hash_set<SBPrefix> download_digest_prefix_;
253 // Factory that creates TestSafeBrowsingDatabase instances.
254 class TestSafeBrowsingDatabaseFactory : public SafeBrowsingDatabaseFactory {
255 public:
256 TestSafeBrowsingDatabaseFactory() : db_(NULL) {}
257 ~TestSafeBrowsingDatabaseFactory() override {}
259 SafeBrowsingDatabase* CreateSafeBrowsingDatabase(
260 const scoped_refptr<base::SequencedTaskRunner>& db_task_runner,
261 bool enable_download_protection,
262 bool enable_client_side_whitelist,
263 bool enable_download_whitelist,
264 bool enable_extension_blacklist,
265 bool enable_side_effect_free_whitelist,
266 bool enable_ip_blacklist,
267 bool enabled_unwanted_software_list) override {
268 db_ = new TestSafeBrowsingDatabase();
269 return db_;
271 TestSafeBrowsingDatabase* GetDb() {
272 return db_;
274 private:
275 // Owned by the SafebrowsingService.
276 TestSafeBrowsingDatabase* db_;
279 // A TestProtocolManager that could return fixed responses from
280 // safebrowsing server for testing purpose.
281 class TestProtocolManager : public SafeBrowsingProtocolManager {
282 public:
283 TestProtocolManager(SafeBrowsingProtocolManagerDelegate* delegate,
284 net::URLRequestContextGetter* request_context_getter,
285 const SafeBrowsingProtocolConfig& config)
286 : SafeBrowsingProtocolManager(delegate, request_context_getter, config) {
287 create_count_++;
290 ~TestProtocolManager() override { delete_count_++; }
292 // This function is called when there is a prefix hit in local safebrowsing
293 // database and safebrowsing service issues a get hash request to backends.
294 // We return a result from the prefilled full_hashes_ hash_map to simulate
295 // server's response. At the same time, latency is added to simulate real
296 // life network issues.
297 void GetFullHash(const std::vector<SBPrefix>& prefixes,
298 SafeBrowsingProtocolManager::FullHashCallback callback,
299 bool is_download) override {
300 BrowserThread::PostDelayedTask(
301 BrowserThread::IO, FROM_HERE,
302 base::Bind(InvokeFullHashCallback, callback, full_hashes_),
303 delay_);
306 // Prepare the GetFullHash results for the next request.
307 void AddGetFullHashResponse(const SBFullHashResult& full_hash_result) {
308 full_hashes_.push_back(full_hash_result);
311 void IntroduceDelay(const base::TimeDelta& delay) {
312 delay_ = delay;
315 static int create_count() {
316 return create_count_;
319 static int delete_count() {
320 return delete_count_;
323 private:
324 std::vector<SBFullHashResult> full_hashes_;
325 base::TimeDelta delay_;
326 static int create_count_;
327 static int delete_count_;
330 // static
331 int TestProtocolManager::create_count_ = 0;
332 // static
333 int TestProtocolManager::delete_count_ = 0;
335 // Factory that creates TestProtocolManager instances.
336 class TestSBProtocolManagerFactory : public SBProtocolManagerFactory {
337 public:
338 TestSBProtocolManagerFactory() : pm_(NULL) {}
339 ~TestSBProtocolManagerFactory() override {}
341 SafeBrowsingProtocolManager* CreateProtocolManager(
342 SafeBrowsingProtocolManagerDelegate* delegate,
343 net::URLRequestContextGetter* request_context_getter,
344 const SafeBrowsingProtocolConfig& config) override {
345 pm_ = new TestProtocolManager(delegate, request_context_getter, config);
346 return pm_;
349 TestProtocolManager* GetProtocolManager() {
350 return pm_;
353 private:
354 // Owned by the SafebrowsingService.
355 TestProtocolManager* pm_;
358 class MockObserver : public SafeBrowsingUIManager::Observer {
359 public:
360 MockObserver() {}
361 virtual ~MockObserver() {}
362 MOCK_METHOD1(OnSafeBrowsingHit,
363 void(const SafeBrowsingUIManager::UnsafeResource&));
364 MOCK_METHOD1(OnSafeBrowsingMatch,
365 void(const SafeBrowsingUIManager::UnsafeResource&));
368 MATCHER_P(IsUnsafeResourceFor, url, "") {
369 return (arg.url.spec() == url.spec() &&
370 arg.threat_type != SB_THREAT_TYPE_SAFE);
373 } // namespace
375 // Tests the safe browsing blocking page in a browser.
376 class SafeBrowsingServiceTest : public InProcessBrowserTest {
377 public:
378 SafeBrowsingServiceTest() {
381 static void GenUrlFullhashResult(const GURL& url,
382 int list_id,
383 SBFullHashResult* full_hash) {
384 std::string host;
385 std::string path;
386 safe_browsing_util::CanonicalizeUrl(url, &host, &path, NULL);
387 full_hash->hash = SBFullHashForString(host + path);
388 full_hash->list_id = list_id;
391 virtual void SetUp() {
392 // InProcessBrowserTest::SetUp() instantiates SafebrowsingService and
393 // RegisterFactory has to be called before SafeBrowsingService is created.
394 sb_factory_.reset(new TestSafeBrowsingServiceFactory(
395 "https://definatelynotarealdomain/safebrowsing"));
396 SafeBrowsingService::RegisterFactory(sb_factory_.get());
397 SafeBrowsingDatabase::RegisterFactory(&db_factory_);
398 SafeBrowsingProtocolManager::RegisterFactory(&pm_factory_);
399 InProcessBrowserTest::SetUp();
402 virtual void TearDown() {
403 InProcessBrowserTest::TearDown();
405 // Unregister test factories after InProcessBrowserTest::TearDown
406 // (which destructs SafeBrowsingService).
407 SafeBrowsingDatabase::RegisterFactory(NULL);
408 SafeBrowsingProtocolManager::RegisterFactory(NULL);
409 SafeBrowsingService::RegisterFactory(NULL);
412 virtual void SetUpCommandLine(base::CommandLine* command_line) override {
413 // Makes sure the auto update is not triggered during the test.
414 // This test will fill up the database using testing prefixes
415 // and urls.
416 command_line->AppendSwitch(switches::kSbDisableAutoUpdate);
417 #if defined(OS_CHROMEOS)
418 command_line->AppendSwitch(
419 chromeos::switches::kIgnoreUserProfileMappingForTests);
420 #endif
423 void SetUpOnMainThread() override {
424 InProcessBrowserTest::SetUpOnMainThread();
425 g_browser_process->safe_browsing_service()->ui_manager()->AddObserver(
426 &observer_);
429 void TearDownOnMainThread() override {
430 g_browser_process->safe_browsing_service()->ui_manager()->RemoveObserver(
431 &observer_);
432 InProcessBrowserTest::TearDownOnMainThread();
435 virtual void SetUpInProcessBrowserTestFixture() {
436 ASSERT_TRUE(test_server()->Start());
439 // This will setup the "url" prefix in database and prepare protocol manager
440 // to respond with |full_hash|, as well as other |full_hash|es previously set
441 // via this call, on GetFullHash requests.
442 void SetupResponseForUrl(const GURL& url, const SBFullHashResult& full_hash) {
443 std::vector<SBPrefix> prefix_hits;
444 prefix_hits.push_back(full_hash.hash.prefix);
446 // Make sure the full hits is empty unless we need to test the
447 // full hash is hit in database's local cache.
448 TestSafeBrowsingDatabase* db = db_factory_.GetDb();
449 db->AddUrl(url, full_hash.list_id, prefix_hits);
451 TestProtocolManager* pm = pm_factory_.GetProtocolManager();
452 pm->AddGetFullHashResponse(full_hash);
455 bool ShowingInterstitialPage() {
456 WebContents* contents =
457 browser()->tab_strip_model()->GetActiveWebContents();
458 InterstitialPage* interstitial_page = contents->GetInterstitialPage();
459 return interstitial_page != NULL;
462 void IntroduceGetHashDelay(const base::TimeDelta& delay) {
463 pm_factory_.GetProtocolManager()->IntroduceDelay(delay);
466 base::TimeDelta GetCheckTimeout(SafeBrowsingService* sb_service) {
467 return sb_service->database_manager()->check_timeout_;
470 void SetCheckTimeout(SafeBrowsingService* sb_service,
471 const base::TimeDelta& delay) {
472 sb_service->database_manager()->check_timeout_ = delay;
475 void CreateCSDService() {
476 safe_browsing::ClientSideDetectionService* csd_service =
477 safe_browsing::ClientSideDetectionService::Create(NULL);
478 SafeBrowsingService* sb_service =
479 g_browser_process->safe_browsing_service();
480 sb_service->csd_service_.reset(csd_service);
481 sb_service->RefreshState();
484 void ProceedAndWhitelist(
485 const SafeBrowsingUIManager::UnsafeResource& resource) {
486 std::vector<SafeBrowsingUIManager::UnsafeResource> resources;
487 resources.push_back(resource);
488 BrowserThread::PostTask(
489 BrowserThread::IO, FROM_HERE,
490 base::Bind(&SafeBrowsingUIManager::OnBlockingPageDone,
491 g_browser_process->safe_browsing_service()->ui_manager(),
492 resources, true));
493 WaitForIOThread();
496 protected:
497 StrictMock<MockObserver> observer_;
499 // Temporary profile dir for test cases that create a second profile. This is
500 // owned by the SafeBrowsingServiceTest object so that it will not get
501 // destructed until after the test Browser has been torn down, since the
502 // ImportantFileWriter may still be modifying it after the Profile object has
503 // been destroyed.
504 base::ScopedTempDir temp_profile_dir_;
506 // Waits for pending tasks on the IO thread to complete. This is useful
507 // to wait for the SafeBrowsingService to finish loading/stopping.
508 void WaitForIOThread() {
509 scoped_refptr<base::ThreadTestHelper> io_helper(new base::ThreadTestHelper(
510 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get()));
511 ASSERT_TRUE(io_helper->Run());
514 private:
515 scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
516 TestSafeBrowsingDatabaseFactory db_factory_;
517 TestSBProtocolManagerFactory pm_factory_;
519 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTest);
522 enum MalwareMetadataTestType {
523 METADATA_NONE,
524 METADATA_LANDING,
525 METADATA_DISTRIBUTION,
528 class SafeBrowsingServiceMetadataTest
529 : public SafeBrowsingServiceTest,
530 public ::testing::WithParamInterface<MalwareMetadataTestType> {
531 public:
532 SafeBrowsingServiceMetadataTest() {}
534 void GenUrlFullhashResultWithMetadata(const GURL& url,
535 SBFullHashResult* full_hash) {
536 GenUrlFullhashResult(url, safe_browsing_util::MALWARE, full_hash);
538 safe_browsing::MalwarePatternType proto;
539 switch (GetParam()) {
540 case METADATA_NONE:
541 full_hash->metadata = std::string();
542 break;
543 case METADATA_LANDING:
544 proto.set_pattern_type(safe_browsing::MalwarePatternType::LANDING);
545 full_hash->metadata = proto.SerializeAsString();
546 break;
547 case METADATA_DISTRIBUTION:
548 proto.set_pattern_type(safe_browsing::MalwarePatternType::DISTRIBUTION);
549 full_hash->metadata = proto.SerializeAsString();
550 break;
554 private:
555 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceMetadataTest);
558 namespace {
560 const char kEmptyPage[] = "files/empty.html";
561 const char kMalwareFile[] = "files/downloads/dangerous/dangerous.exe";
562 const char kMalwarePage[] = "files/safe_browsing/malware.html";
563 const char kMalwareIFrame[] = "files/safe_browsing/malware_iframe.html";
564 const char kMalwareImg[] = "files/safe_browsing/malware_image.png";
566 // This test goes through DownloadResourceHandler.
567 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareMainFrame) {
568 GURL url = test_server()->GetURL(kEmptyPage);
570 // After adding the url to safebrowsing database and getfullhash result,
571 // we should see the interstitial page.
572 SBFullHashResult malware_full_hash;
573 GenUrlFullhashResultWithMetadata(url, &malware_full_hash);
574 EXPECT_CALL(observer_,
575 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
576 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1);
577 SetupResponseForUrl(url, malware_full_hash);
578 ui_test_utils::NavigateToURL(browser(), url);
579 // All types should show the interstitial.
580 EXPECT_TRUE(ShowingInterstitialPage());
583 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareIFrame) {
584 GURL main_url = test_server()->GetURL(kMalwarePage);
585 GURL iframe_url = test_server()->GetURL(kMalwareIFrame);
587 // Add the iframe url as malware and then load the parent page.
588 SBFullHashResult malware_full_hash;
589 GenUrlFullhashResultWithMetadata(iframe_url, &malware_full_hash);
590 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(iframe_url)))
591 .Times(1);
592 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(iframe_url)))
593 .Times(1);
594 SetupResponseForUrl(iframe_url, malware_full_hash);
595 ui_test_utils::NavigateToURL(browser(), main_url);
596 // All types should show the interstitial.
597 EXPECT_TRUE(ShowingInterstitialPage());
600 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareImg) {
601 GURL main_url = test_server()->GetURL(kMalwarePage);
602 GURL img_url = test_server()->GetURL(kMalwareImg);
604 // Add the img url as malware and then load the parent page.
605 SBFullHashResult malware_full_hash;
606 GenUrlFullhashResultWithMetadata(img_url, &malware_full_hash);
607 switch (GetParam()) {
608 case METADATA_NONE: // Falls through.
609 case METADATA_DISTRIBUTION:
610 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(img_url)))
611 .Times(1);
612 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(img_url)))
613 .Times(1);
614 break;
615 case METADATA_LANDING:
616 // No interstitial shown, so no notifications expected.
617 break;
619 SetupResponseForUrl(img_url, malware_full_hash);
620 ui_test_utils::NavigateToURL(browser(), main_url);
621 // Subresource which is tagged as a landing page should not show an
622 // interstitial, the other types should.
623 switch (GetParam()) {
624 case METADATA_NONE:
625 case METADATA_DISTRIBUTION:
626 EXPECT_TRUE(ShowingInterstitialPage());
627 break;
628 case METADATA_LANDING:
629 EXPECT_FALSE(ShowingInterstitialPage());
630 break;
634 INSTANTIATE_TEST_CASE_P(MaybeSetMetadata,
635 SafeBrowsingServiceMetadataTest,
636 testing::Values(METADATA_NONE,
637 METADATA_LANDING,
638 METADATA_DISTRIBUTION));
640 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, UnwantedImgIgnored) {
641 GURL main_url = test_server()->GetURL(kMalwarePage);
642 GURL img_url = test_server()->GetURL(kMalwareImg);
644 // Add the img url as coming from a site serving UwS and then load the parent
645 // page.
646 SBFullHashResult uws_full_hash;
647 GenUrlFullhashResult(img_url, safe_browsing_util::UNWANTEDURL,
648 &uws_full_hash);
649 SetupResponseForUrl(img_url, uws_full_hash);
651 ui_test_utils::NavigateToURL(browser(), main_url);
653 EXPECT_FALSE(ShowingInterstitialPage());
656 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, DISABLED_MalwareWithWhitelist) {
657 GURL url = test_server()->GetURL(kEmptyPage);
659 // After adding the url to safebrowsing database and getfullhash result,
660 // we should see the interstitial page.
661 SBFullHashResult malware_full_hash;
662 GenUrlFullhashResult(url, safe_browsing_util::MALWARE, &malware_full_hash);
663 EXPECT_CALL(observer_,
664 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
665 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1)
666 .WillOnce(testing::Invoke(
667 this, &SafeBrowsingServiceTest::ProceedAndWhitelist));
668 SetupResponseForUrl(url, malware_full_hash);
670 ui_test_utils::NavigateToURL(browser(), url);
671 // Mock calls OnBlockingPageDone set to proceed, so the interstitial
672 // is removed.
673 EXPECT_FALSE(ShowingInterstitialPage());
674 Mock::VerifyAndClearExpectations(&observer_);
676 // Navigate back to kEmptyPage -- should hit the whitelist, and send a match
677 // call, but no hit call.
678 EXPECT_CALL(observer_,
679 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
680 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(0);
681 ui_test_utils::NavigateToURL(browser(), url);
682 EXPECT_FALSE(ShowingInterstitialPage());
685 const char kPrefetchMalwarePage[] = "files/safe_browsing/prefetch_malware.html";
687 // This test confirms that prefetches don't themselves get the
688 // interstitial treatment.
689 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, Prefetch) {
690 GURL url = test_server()->GetURL(kPrefetchMalwarePage);
691 GURL malware_url = test_server()->GetURL(kMalwarePage);
693 class SetPrefetchForTest {
694 public:
695 explicit SetPrefetchForTest(bool prefetch)
696 : old_prerender_mode_(prerender::PrerenderManager::GetMode()) {
697 std::string exp_group = prefetch ? "ExperimentYes" : "ExperimentNo";
698 base::FieldTrialList::CreateFieldTrial("Prefetch", exp_group);
700 prerender::PrerenderManager::SetMode(
701 prerender::PrerenderManager::PRERENDER_MODE_DISABLED);
704 ~SetPrefetchForTest() {
705 prerender::PrerenderManager::SetMode(old_prerender_mode_);
708 private:
709 prerender::PrerenderManager::PrerenderManagerMode old_prerender_mode_;
710 } set_prefetch_for_test(true);
712 // Even though we have added this uri to the safebrowsing database and
713 // getfullhash result, we should not see the interstitial page since the
714 // only malware was a prefetch target.
715 SBFullHashResult malware_full_hash;
716 GenUrlFullhashResult(malware_url, safe_browsing_util::MALWARE,
717 &malware_full_hash);
718 SetupResponseForUrl(malware_url, malware_full_hash);
719 ui_test_utils::NavigateToURL(browser(), url);
720 EXPECT_FALSE(ShowingInterstitialPage());
721 Mock::VerifyAndClear(&observer_);
723 // However, when we navigate to the malware page, we should still get
724 // the interstitial.
725 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(malware_url)))
726 .Times(1);
727 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(malware_url)))
728 .Times(1);
729 ui_test_utils::NavigateToURL(browser(), malware_url);
730 EXPECT_TRUE(ShowingInterstitialPage());
731 Mock::VerifyAndClear(&observer_);
734 } // namespace
736 class TestSBClient
737 : public base::RefCountedThreadSafe<TestSBClient>,
738 public SafeBrowsingDatabaseManager::Client {
739 public:
740 TestSBClient()
741 : threat_type_(SB_THREAT_TYPE_SAFE),
742 safe_browsing_service_(g_browser_process->safe_browsing_service()) {
745 SBThreatType GetThreatType() const {
746 return threat_type_;
749 void CheckDownloadUrl(const std::vector<GURL>& url_chain) {
750 BrowserThread::PostTask(
751 BrowserThread::IO, FROM_HERE,
752 base::Bind(&TestSBClient::CheckDownloadUrlOnIOThread,
753 this, url_chain));
754 content::RunMessageLoop(); // Will stop in OnCheckDownloadUrlResult.
757 void CheckBrowseUrl(const GURL& url) {
758 BrowserThread::PostTask(
759 BrowserThread::IO, FROM_HERE,
760 base::Bind(&TestSBClient::CheckBrowseUrlOnIOThread, this, url));
761 content::RunMessageLoop(); // Will stop in OnCheckBrowseUrlResult.
764 private:
765 friend class base::RefCountedThreadSafe<TestSBClient>;
766 ~TestSBClient() override {}
768 void CheckDownloadUrlOnIOThread(const std::vector<GURL>& url_chain) {
769 bool synchronous_safe_signal =
770 safe_browsing_service_->database_manager()->CheckDownloadUrl(url_chain,
771 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));
779 void CheckBrowseUrlOnIOThread(const GURL& url) {
780 // The async CheckDone() hook will not be called when we have a synchronous
781 // safe signal, handle it right away.
782 bool synchronous_safe_signal =
783 safe_browsing_service_->database_manager()->CheckBrowseUrl(url, this);
784 if (synchronous_safe_signal) {
785 threat_type_ = SB_THREAT_TYPE_SAFE;
786 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
787 base::Bind(&TestSBClient::CheckDone, this));
791 // Called when the result of checking a download URL is known.
792 void OnCheckDownloadUrlResult(const std::vector<GURL>& /* url_chain */,
793 SBThreatType threat_type) override {
794 threat_type_ = threat_type;
795 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
796 base::Bind(&TestSBClient::CheckDone, this));
799 // Called when the result of checking a browse URL is known.
800 void OnCheckBrowseUrlResult(const GURL& /* url */,
801 SBThreatType threat_type,
802 const std::string& /* metadata */) override {
803 threat_type_ = threat_type;
804 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
805 base::Bind(&TestSBClient::CheckDone, this));
808 void CheckDone() {
809 base::MessageLoopForUI::current()->Quit();
812 SBThreatType threat_type_;
813 SafeBrowsingService* safe_browsing_service_;
815 DISALLOW_COPY_AND_ASSIGN(TestSBClient);
818 // These tests use SafeBrowsingService::Client to directly interact with
819 // SafeBrowsingService.
820 namespace {
822 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrl) {
823 GURL badbin_url = test_server()->GetURL(kMalwareFile);
824 std::vector<GURL> badbin_urls(1, badbin_url);
826 scoped_refptr<TestSBClient> client(new TestSBClient);
827 client->CheckDownloadUrl(badbin_urls);
829 // Since badbin_url is not in database, it is considered to be safe.
830 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
832 SBFullHashResult full_hash_result;
833 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
834 &full_hash_result);
835 SetupResponseForUrl(badbin_url, full_hash_result);
837 client->CheckDownloadUrl(badbin_urls);
839 // Now, the badbin_url is not safe since it is added to download database.
840 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
843 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckUnwantedSoftwareUrl) {
844 const GURL bad_url = test_server()->GetURL(kMalwareFile);
846 scoped_refptr<TestSBClient> client(new TestSBClient);
848 // Since bad_url is not in database, it is considered to be
849 // safe.
850 client->CheckBrowseUrl(bad_url);
851 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
853 SBFullHashResult full_hash_result;
854 GenUrlFullhashResult(
855 bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
856 SetupResponseForUrl(bad_url, full_hash_result);
858 // Now, the bad_url is not safe since it is added to download
859 // database.
860 client->CheckBrowseUrl(bad_url);
861 EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
864 // The unwantedness should survive across multiple clients.
866 scoped_refptr<TestSBClient> client(new TestSBClient);
867 client->CheckBrowseUrl(bad_url);
868 EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
871 // An unwanted URL also marked as malware should be flagged as malware.
873 scoped_refptr<TestSBClient> client(new TestSBClient);
875 SBFullHashResult full_hash_result;
876 GenUrlFullhashResult(
877 bad_url, safe_browsing_util::MALWARE, &full_hash_result);
878 SetupResponseForUrl(bad_url, full_hash_result);
880 client->CheckBrowseUrl(bad_url);
881 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
885 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckBrowseUrl) {
886 const GURL bad_url = test_server()->GetURL(kMalwareFile);
888 scoped_refptr<TestSBClient> client(new TestSBClient);
890 // Since bad_url is not in database, it is considered to be
891 // safe.
892 client->CheckBrowseUrl(bad_url);
893 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
895 SBFullHashResult full_hash_result;
896 GenUrlFullhashResult(
897 bad_url, safe_browsing_util::MALWARE, &full_hash_result);
898 SetupResponseForUrl(bad_url, full_hash_result);
900 // Now, the bad_url is not safe since it is added to download
901 // database.
902 client->CheckBrowseUrl(bad_url);
903 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
906 // The unwantedness should survive across multiple clients.
908 scoped_refptr<TestSBClient> client(new TestSBClient);
909 client->CheckBrowseUrl(bad_url);
910 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
913 // Adding the unwanted state to an existing malware URL should have no impact
914 // (i.e. a malware hit should still prevail).
916 scoped_refptr<TestSBClient> client(new TestSBClient);
918 SBFullHashResult full_hash_result;
919 GenUrlFullhashResult(
920 bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
921 SetupResponseForUrl(bad_url, full_hash_result);
923 client->CheckBrowseUrl(bad_url);
924 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
928 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrlRedirects) {
929 GURL original_url = test_server()->GetURL(kEmptyPage);
930 GURL badbin_url = test_server()->GetURL(kMalwareFile);
931 GURL final_url = test_server()->GetURL(kEmptyPage);
932 std::vector<GURL> badbin_urls;
933 badbin_urls.push_back(original_url);
934 badbin_urls.push_back(badbin_url);
935 badbin_urls.push_back(final_url);
937 scoped_refptr<TestSBClient> client(new TestSBClient);
938 client->CheckDownloadUrl(badbin_urls);
940 // Since badbin_url is not in database, it is considered to be safe.
941 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
943 SBFullHashResult full_hash_result;
944 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
945 &full_hash_result);
946 SetupResponseForUrl(badbin_url, full_hash_result);
948 client->CheckDownloadUrl(badbin_urls);
950 // Now, the badbin_url is not safe since it is added to download database.
951 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
954 #if defined(OS_WIN)
955 // http://crbug.com/396409
956 #define MAYBE_CheckDownloadUrlTimedOut DISABLED_CheckDownloadUrlTimedOut
957 #else
958 #define MAYBE_CheckDownloadUrlTimedOut CheckDownloadUrlTimedOut
959 #endif
960 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest,
961 MAYBE_CheckDownloadUrlTimedOut) {
962 GURL badbin_url = test_server()->GetURL(kMalwareFile);
963 std::vector<GURL> badbin_urls(1, badbin_url);
965 scoped_refptr<TestSBClient> client(new TestSBClient);
966 SBFullHashResult full_hash_result;
967 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
968 &full_hash_result);
969 SetupResponseForUrl(badbin_url, full_hash_result);
970 client->CheckDownloadUrl(badbin_urls);
972 // badbin_url is not safe since it is added to download database.
973 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
976 // Now introducing delays and we should hit timeout.
978 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
979 base::TimeDelta default_urlcheck_timeout = GetCheckTimeout(sb_service);
980 IntroduceGetHashDelay(base::TimeDelta::FromSeconds(1));
981 SetCheckTimeout(sb_service, base::TimeDelta::FromMilliseconds(1));
982 client->CheckDownloadUrl(badbin_urls);
984 // There should be a timeout and the hash would be considered as safe.
985 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
987 // Need to set the timeout back to the default value.
988 SetCheckTimeout(sb_service, default_urlcheck_timeout);
991 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, StartAndStop) {
992 CreateCSDService();
993 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
994 safe_browsing::ClientSideDetectionService* csd_service =
995 sb_service->safe_browsing_detection_service();
996 PrefService* pref_service = browser()->profile()->GetPrefs();
998 ASSERT_TRUE(sb_service != NULL);
999 ASSERT_TRUE(csd_service != NULL);
1000 ASSERT_TRUE(pref_service != NULL);
1002 EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
1004 // SBS might still be starting, make sure this doesn't flake.
1005 WaitForIOThread();
1006 EXPECT_TRUE(sb_service->enabled());
1007 EXPECT_TRUE(csd_service->enabled());
1009 // Add a new Profile. SBS should keep running.
1010 ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
1011 scoped_ptr<Profile> profile2(Profile::CreateProfile(
1012 temp_profile_dir_.path(), NULL, Profile::CREATE_MODE_SYNCHRONOUS));
1013 ASSERT_TRUE(profile2.get() != NULL);
1014 StartupTaskRunnerServiceFactory::GetForProfile(profile2.get())->
1015 StartDeferredTaskRunners();
1016 PrefService* pref_service2 = profile2->GetPrefs();
1017 EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1018 // We don't expect the state to have changed, but if it did, wait for it.
1019 WaitForIOThread();
1020 EXPECT_TRUE(sb_service->enabled());
1021 EXPECT_TRUE(csd_service->enabled());
1023 // Change one of the prefs. SBS should keep running.
1024 pref_service->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1025 WaitForIOThread();
1026 EXPECT_TRUE(sb_service->enabled());
1027 EXPECT_TRUE(csd_service->enabled());
1029 // Change the other pref. SBS should stop now.
1030 pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1031 WaitForIOThread();
1033 // TODO(mattm): Remove this when crbug.com/461493 is fixed.
1034 #if defined(OS_CHROMEOS)
1035 // On Chrome OS we should disable safe browsing for signin profile.
1036 EXPECT_TRUE(sb_service->enabled());
1037 EXPECT_TRUE(csd_service->enabled());
1038 chromeos::ProfileHelper::GetSigninProfile()
1039 ->GetOriginalProfile()
1040 ->GetPrefs()
1041 ->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1042 WaitForIOThread();
1043 #endif
1044 EXPECT_FALSE(sb_service->enabled());
1045 EXPECT_FALSE(csd_service->enabled());
1047 // Turn it back on. SBS comes back.
1048 pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, true);
1049 WaitForIOThread();
1050 EXPECT_TRUE(sb_service->enabled());
1051 EXPECT_TRUE(csd_service->enabled());
1053 // Delete the Profile. SBS stops again.
1054 pref_service2 = NULL;
1055 profile2.reset();
1056 WaitForIOThread();
1057 EXPECT_FALSE(sb_service->enabled());
1058 EXPECT_FALSE(csd_service->enabled());
1061 } // namespace
1063 class SafeBrowsingServiceShutdownTest : public SafeBrowsingServiceTest {
1064 public:
1065 void TearDown() override {
1066 // Browser should be fully torn down by now, so we can safely check these
1067 // counters.
1068 EXPECT_EQ(1, TestProtocolManager::create_count());
1069 EXPECT_EQ(1, TestProtocolManager::delete_count());
1071 SafeBrowsingServiceTest::TearDown();
1074 // An observer that returns back to test code after a new profile is
1075 // initialized.
1076 void OnUnblockOnProfileCreation(Profile* profile,
1077 Profile::CreateStatus status) {
1078 if (status == Profile::CREATE_STATUS_INITIALIZED) {
1079 profile2_ = profile;
1080 base::MessageLoop::current()->Quit();
1084 protected:
1085 Profile* profile2_;
1088 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceShutdownTest,
1089 DontStartAfterShutdown) {
1090 CreateCSDService();
1091 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
1092 safe_browsing::ClientSideDetectionService* csd_service =
1093 sb_service->safe_browsing_detection_service();
1094 PrefService* pref_service = browser()->profile()->GetPrefs();
1096 ASSERT_TRUE(sb_service != NULL);
1097 ASSERT_TRUE(csd_service != NULL);
1098 ASSERT_TRUE(pref_service != NULL);
1100 EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
1102 // SBS might still be starting, make sure this doesn't flake.
1103 WaitForIOThread();
1104 EXPECT_EQ(1, TestProtocolManager::create_count());
1105 EXPECT_EQ(0, TestProtocolManager::delete_count());
1107 // Create an additional profile. We need to use the ProfileManager so that
1108 // the profile will get destroyed in the normal browser shutdown process.
1109 ProfileManager* profile_manager = g_browser_process->profile_manager();
1110 ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
1111 profile_manager->CreateProfileAsync(
1112 temp_profile_dir_.path(),
1113 base::Bind(&SafeBrowsingServiceShutdownTest::OnUnblockOnProfileCreation,
1114 this),
1115 base::string16(), base::string16(), std::string());
1117 // Spin to allow profile creation to take place, loop is terminated
1118 // by OnUnblockOnProfileCreation when the profile is created.
1119 content::RunMessageLoop();
1121 PrefService* pref_service2 = profile2_->GetPrefs();
1122 EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1124 // We don't expect the state to have changed, but if it did, wait for it.
1125 WaitForIOThread();
1126 EXPECT_EQ(1, TestProtocolManager::create_count());
1127 EXPECT_EQ(0, TestProtocolManager::delete_count());
1129 // End the test, shutting down the browser.
1130 // SafeBrowsingServiceShutdownTest::TearDown will check the create_count and
1131 // delete_count again.
1134 class SafeBrowsingDatabaseManagerCookieTest : public InProcessBrowserTest {
1135 public:
1136 SafeBrowsingDatabaseManagerCookieTest() {}
1138 void SetUp() override {
1139 // We need to start the test server to get the host&port in the url.
1140 ASSERT_TRUE(test_server()->Start());
1142 // Point to the testing server for all SafeBrowsing requests.
1143 GURL url_prefix = test_server()->GetURL(
1144 "expect-and-set-cookie?expect=a%3db"
1145 "&set=c%3dd%3b%20Expires=Fri,%2001%20Jan%202038%2001:01:01%20GMT"
1146 "&data=foo#");
1147 sb_factory_.reset(new TestSafeBrowsingServiceFactory(url_prefix.spec()));
1148 SafeBrowsingService::RegisterFactory(sb_factory_.get());
1150 InProcessBrowserTest::SetUp();
1153 void TearDown() override {
1154 InProcessBrowserTest::TearDown();
1156 SafeBrowsingService::RegisterFactory(NULL);
1159 bool SetUpUserDataDirectory() override {
1160 base::FilePath cookie_path(
1161 SafeBrowsingService::GetCookieFilePathForTesting());
1162 EXPECT_FALSE(base::PathExists(cookie_path));
1164 base::FilePath test_dir;
1165 if (!PathService::Get(chrome::DIR_TEST_DATA, &test_dir)) {
1166 EXPECT_TRUE(false);
1167 return false;
1170 // Initialize the SafeBrowsing cookies with a pre-created cookie store. It
1171 // contains a single cookie, for domain 127.0.0.1, with value a=b, and
1172 // expires in 2038.
1173 base::FilePath initial_cookies = test_dir.AppendASCII("safe_browsing")
1174 .AppendASCII("Safe Browsing Cookies");
1175 if (!base::CopyFile(initial_cookies, cookie_path)) {
1176 EXPECT_TRUE(false);
1177 return false;
1180 sql::Connection db;
1181 if (!db.Open(cookie_path)) {
1182 EXPECT_TRUE(false);
1183 return false;
1185 // Ensure the host value in the cookie file matches the test server we will
1186 // be connecting to.
1187 sql::Statement smt(db.GetUniqueStatement(
1188 "UPDATE cookies SET host_key = ?"));
1189 if (!smt.is_valid()) {
1190 EXPECT_TRUE(false);
1191 return false;
1193 if (!smt.BindString(0, test_server()->host_port_pair().host())) {
1194 EXPECT_TRUE(false);
1195 return false;
1197 if (!smt.Run()) {
1198 EXPECT_TRUE(false);
1199 return false;
1202 return InProcessBrowserTest::SetUpUserDataDirectory();
1205 void TearDownInProcessBrowserTestFixture() override {
1206 InProcessBrowserTest::TearDownInProcessBrowserTestFixture();
1208 sql::Connection db;
1209 base::FilePath cookie_path(
1210 SafeBrowsingService::GetCookieFilePathForTesting());
1211 ASSERT_TRUE(db.Open(cookie_path));
1213 sql::Statement smt(db.GetUniqueStatement(
1214 "SELECT name, value FROM cookies ORDER BY name"));
1215 ASSERT_TRUE(smt.is_valid());
1217 ASSERT_TRUE(smt.Step());
1218 ASSERT_EQ("a", smt.ColumnString(0));
1219 ASSERT_EQ("b", smt.ColumnString(1));
1220 ASSERT_TRUE(smt.Step());
1221 ASSERT_EQ("c", smt.ColumnString(0));
1222 ASSERT_EQ("d", smt.ColumnString(1));
1223 EXPECT_FALSE(smt.Step());
1226 void SetUpOnMainThread() override {
1227 sb_service_ = g_browser_process->safe_browsing_service();
1228 ASSERT_TRUE(sb_service_.get() != NULL);
1231 void TearDownOnMainThread() override { sb_service_ = NULL; }
1233 void ForceUpdate() {
1234 sb_service_->protocol_manager()->ForceScheduleNextUpdate(
1235 base::TimeDelta::FromSeconds(0));
1238 scoped_refptr<SafeBrowsingService> sb_service_;
1240 private:
1241 scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
1243 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingDatabaseManagerCookieTest);
1246 // Test that a Safe Browsing database update request both sends cookies and can
1247 // save cookies.
1248 IN_PROC_BROWSER_TEST_F(SafeBrowsingDatabaseManagerCookieTest,
1249 TestSBUpdateCookies) {
1250 content::WindowedNotificationObserver observer(
1251 chrome::NOTIFICATION_SAFE_BROWSING_UPDATE_COMPLETE,
1252 content::Source<SafeBrowsingDatabaseManager>(
1253 sb_service_->database_manager().get()));
1254 BrowserThread::PostTask(
1255 BrowserThread::IO,
1256 FROM_HERE,
1257 base::Bind(&SafeBrowsingDatabaseManagerCookieTest::ForceUpdate, this));
1258 observer.Wait();