base::Time multiplicative operator overloading
[chromium-blink-merge.git] / chrome / browser / safe_browsing / safe_browsing_service_browsertest.cc
blob2ac78f3592ad2db7aec9d437f66dfe09abe54753
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 "chromeos/chromeos_switches.h"
52 #endif
54 using content::BrowserThread;
55 using content::InterstitialPage;
56 using content::WebContents;
57 using ::testing::_;
58 using ::testing::Mock;
59 using ::testing::StrictMock;
61 namespace {
63 void InvokeFullHashCallback(
64 SafeBrowsingProtocolManager::FullHashCallback callback,
65 const std::vector<SBFullHashResult>& result) {
66 callback.Run(result, base::TimeDelta::FromMinutes(45));
69 class FakeSafeBrowsingService : public SafeBrowsingService {
70 public:
71 explicit FakeSafeBrowsingService(const std::string& url_prefix)
72 : url_prefix_(url_prefix) {}
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;
87 private:
88 ~FakeSafeBrowsingService() override {}
90 std::string url_prefix_;
92 DISALLOW_COPY_AND_ASSIGN(FakeSafeBrowsingService);
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) {}
101 SafeBrowsingService* CreateSafeBrowsingService() override {
102 return new FakeSafeBrowsingService(url_prefix_);
105 private:
106 std::string url_prefix_;
109 // A SafeBrowingDatabase class that allows us to inject the malicious URLs.
110 class TestSafeBrowsingDatabase : public SafeBrowsingDatabase {
111 public:
112 TestSafeBrowsingDatabase() {}
114 ~TestSafeBrowsingDatabase() override {}
116 // Initializes the database with the given filename.
117 void Init(const base::FilePath& filename) override {}
119 // Deletes the current database and creates a new one.
120 bool ResetDatabase() override {
121 badurls_.clear();
122 return true;
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);
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);
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;
158 bool ContainsCsdWhitelistedUrl(const GURL& url) override { return true; }
159 bool ContainsDownloadWhitelistedString(const std::string& str) override {
160 return true;
162 bool ContainsDownloadWhitelistedUrl(const GURL& url) override { return true; }
163 bool ContainsInclusionWhitelistedUrl(const GURL& url) override {
164 return true;
166 bool ContainsExtensionPrefixes(const std::vector<SBPrefix>& prefixes,
167 std::vector<SBPrefix>* prefix_hits) override {
168 return true;
170 bool ContainsSideEffectFreeWhitelistUrl(const GURL& url) override {
171 return true;
173 bool ContainsMalwareIP(const std::string& ip_address) override {
174 return true;
176 bool UpdateStarted(std::vector<SBListChunkRanges>* lists) override {
177 ADD_FAILURE() << "Not implemented.";
178 return false;
180 void InsertChunks(const std::string& list_name,
181 const std::vector<SBChunkData*>& chunks) override {
182 ADD_FAILURE() << "Not implemented.";
184 void DeleteChunks(const std::vector<SBChunkDelete>& chunk_deletes) override {
185 ADD_FAILURE() << "Not implemented.";
187 void UpdateFinished(bool update_succeeded) override {
188 ADD_FAILURE() << "Not implemented.";
190 void CacheHashResults(const std::vector<SBPrefix>& prefixes,
191 const std::vector<SBFullHashResult>& cache_hits,
192 const base::TimeDelta& cache_lifetime) override {
193 // Do nothing for the cache.
195 bool IsMalwareIPMatchKillSwitchOn() override { return false; }
196 bool IsCsdWhitelistKillSwitchOn() override { return false; }
198 // Fill up the database with test URL.
199 void AddUrl(const GURL& url,
200 int list_id,
201 const std::vector<SBPrefix>& prefix_hits) {
202 Hits* hits_for_url = &badurls_[url.spec()];
203 hits_for_url->list_ids.push_back(list_id);
204 hits_for_url->prefix_hits.insert(hits_for_url->prefix_hits.end(),
205 prefix_hits.begin(),
206 prefix_hits.end());
209 // Fill up the database with test hash digest.
210 void AddDownloadPrefix(SBPrefix prefix) {
211 download_digest_prefix_.insert(prefix);
214 private:
215 // Stores |list_ids| of safe browsing lists that match some |prefix_hits|.
216 struct Hits {
217 std::vector<int> list_ids;
218 std::vector<SBPrefix> prefix_hits;
221 bool ContainsUrl(int list_id0,
222 int list_id1,
223 const std::vector<GURL>& urls,
224 std::vector<SBPrefix>* prefix_hits) {
225 bool hit = false;
226 for (size_t i = 0; i < urls.size(); ++i) {
227 const GURL& url = urls[i];
228 base::hash_map<std::string, Hits>::const_iterator
229 badurls_it = badurls_.find(url.spec());
231 if (badurls_it == badurls_.end())
232 continue;
234 std::vector<int> list_ids_for_url = badurls_it->second.list_ids;
235 if (std::find(list_ids_for_url.begin(), list_ids_for_url.end(), list_id0)
236 != list_ids_for_url.end() ||
237 std::find(list_ids_for_url.begin(), list_ids_for_url.end(), list_id1)
238 != list_ids_for_url.end()) {
239 prefix_hits->insert(prefix_hits->end(),
240 badurls_it->second.prefix_hits.begin(),
241 badurls_it->second.prefix_hits.end());
242 hit = true;
245 return hit;
248 base::hash_map<std::string, Hits> badurls_;
249 base::hash_set<SBPrefix> download_digest_prefix_;
252 // Factory that creates TestSafeBrowsingDatabase instances.
253 class TestSafeBrowsingDatabaseFactory : public SafeBrowsingDatabaseFactory {
254 public:
255 TestSafeBrowsingDatabaseFactory() : db_(NULL) {}
256 ~TestSafeBrowsingDatabaseFactory() override {}
258 SafeBrowsingDatabase* CreateSafeBrowsingDatabase(
259 bool enable_download_protection,
260 bool enable_client_side_whitelist,
261 bool enable_download_whitelist,
262 bool enable_extension_blacklist,
263 bool enable_side_effect_free_whitelist,
264 bool enable_ip_blacklist,
265 bool enabled_unwanted_software_list) override {
266 db_ = new TestSafeBrowsingDatabase();
267 return db_;
269 TestSafeBrowsingDatabase* GetDb() {
270 return db_;
272 private:
273 // Owned by the SafebrowsingService.
274 TestSafeBrowsingDatabase* db_;
277 // A TestProtocolManager that could return fixed responses from
278 // safebrowsing server for testing purpose.
279 class TestProtocolManager : public SafeBrowsingProtocolManager {
280 public:
281 TestProtocolManager(SafeBrowsingProtocolManagerDelegate* delegate,
282 net::URLRequestContextGetter* request_context_getter,
283 const SafeBrowsingProtocolConfig& config)
284 : SafeBrowsingProtocolManager(delegate, request_context_getter, config) {
285 create_count_++;
288 ~TestProtocolManager() override { delete_count_++; }
290 // This function is called when there is a prefix hit in local safebrowsing
291 // database and safebrowsing service issues a get hash request to backends.
292 // We return a result from the prefilled full_hashes_ hash_map to simulate
293 // server's response. At the same time, latency is added to simulate real
294 // life network issues.
295 void GetFullHash(const std::vector<SBPrefix>& prefixes,
296 SafeBrowsingProtocolManager::FullHashCallback callback,
297 bool is_download) override {
298 BrowserThread::PostDelayedTask(
299 BrowserThread::IO, FROM_HERE,
300 base::Bind(InvokeFullHashCallback, callback, full_hashes_),
301 delay_);
304 // Prepare the GetFullHash results for the next request.
305 void AddGetFullHashResponse(const SBFullHashResult& full_hash_result) {
306 full_hashes_.push_back(full_hash_result);
309 void IntroduceDelay(const base::TimeDelta& delay) {
310 delay_ = delay;
313 static int create_count() {
314 return create_count_;
317 static int delete_count() {
318 return delete_count_;
321 private:
322 std::vector<SBFullHashResult> full_hashes_;
323 base::TimeDelta delay_;
324 static int create_count_;
325 static int delete_count_;
328 // static
329 int TestProtocolManager::create_count_ = 0;
330 // static
331 int TestProtocolManager::delete_count_ = 0;
333 // Factory that creates TestProtocolManager instances.
334 class TestSBProtocolManagerFactory : public SBProtocolManagerFactory {
335 public:
336 TestSBProtocolManagerFactory() : pm_(NULL) {}
337 ~TestSBProtocolManagerFactory() override {}
339 SafeBrowsingProtocolManager* CreateProtocolManager(
340 SafeBrowsingProtocolManagerDelegate* delegate,
341 net::URLRequestContextGetter* request_context_getter,
342 const SafeBrowsingProtocolConfig& config) override {
343 pm_ = new TestProtocolManager(delegate, request_context_getter, config);
344 return pm_;
347 TestProtocolManager* GetProtocolManager() {
348 return pm_;
351 private:
352 // Owned by the SafebrowsingService.
353 TestProtocolManager* pm_;
356 class MockObserver : public SafeBrowsingUIManager::Observer {
357 public:
358 MockObserver() {}
359 virtual ~MockObserver() {}
360 MOCK_METHOD1(OnSafeBrowsingHit,
361 void(const SafeBrowsingUIManager::UnsafeResource&));
362 MOCK_METHOD1(OnSafeBrowsingMatch,
363 void(const SafeBrowsingUIManager::UnsafeResource&));
366 MATCHER_P(IsUnsafeResourceFor, url, "") {
367 return (arg.url.spec() == url.spec() &&
368 arg.threat_type != SB_THREAT_TYPE_SAFE);
371 } // namespace
373 // Tests the safe browsing blocking page in a browser.
374 class SafeBrowsingServiceTest : public InProcessBrowserTest {
375 public:
376 SafeBrowsingServiceTest() {
379 static void GenUrlFullhashResult(const GURL& url,
380 int list_id,
381 SBFullHashResult* full_hash) {
382 std::string host;
383 std::string path;
384 safe_browsing_util::CanonicalizeUrl(url, &host, &path, NULL);
385 full_hash->hash = SBFullHashForString(host + path);
386 full_hash->list_id = list_id;
389 virtual void SetUp() {
390 // InProcessBrowserTest::SetUp() instantiates SafebrowsingService and
391 // RegisterFactory has to be called before SafeBrowsingService is created.
392 sb_factory_.reset(new TestSafeBrowsingServiceFactory(
393 "https://definatelynotarealdomain/safebrowsing"));
394 SafeBrowsingService::RegisterFactory(sb_factory_.get());
395 SafeBrowsingDatabase::RegisterFactory(&db_factory_);
396 SafeBrowsingProtocolManager::RegisterFactory(&pm_factory_);
397 InProcessBrowserTest::SetUp();
400 virtual void TearDown() {
401 InProcessBrowserTest::TearDown();
403 // Unregister test factories after InProcessBrowserTest::TearDown
404 // (which destructs SafeBrowsingService).
405 SafeBrowsingDatabase::RegisterFactory(NULL);
406 SafeBrowsingProtocolManager::RegisterFactory(NULL);
407 SafeBrowsingService::RegisterFactory(NULL);
410 virtual void SetUpCommandLine(base::CommandLine* command_line) override {
411 // Makes sure the auto update is not triggered during the test.
412 // This test will fill up the database using testing prefixes
413 // and urls.
414 command_line->AppendSwitch(switches::kSbDisableAutoUpdate);
415 #if defined(OS_CHROMEOS)
416 command_line->AppendSwitch(
417 chromeos::switches::kIgnoreUserProfileMappingForTests);
418 #endif
421 void SetUpOnMainThread() override {
422 InProcessBrowserTest::SetUpOnMainThread();
423 g_browser_process->safe_browsing_service()->ui_manager()->AddObserver(
424 &observer_);
427 void TearDownOnMainThread() override {
428 g_browser_process->safe_browsing_service()->ui_manager()->RemoveObserver(
429 &observer_);
430 InProcessBrowserTest::TearDownOnMainThread();
433 virtual void SetUpInProcessBrowserTestFixture() {
434 ASSERT_TRUE(test_server()->Start());
437 // This will setup the "url" prefix in database and prepare protocol manager
438 // to respond with |full_hash|, as well as other |full_hash|es previously set
439 // via this call, on GetFullHash requests.
440 void SetupResponseForUrl(const GURL& url, const SBFullHashResult& full_hash) {
441 std::vector<SBPrefix> prefix_hits;
442 prefix_hits.push_back(full_hash.hash.prefix);
444 // Make sure the full hits is empty unless we need to test the
445 // full hash is hit in database's local cache.
446 TestSafeBrowsingDatabase* db = db_factory_.GetDb();
447 db->AddUrl(url, full_hash.list_id, prefix_hits);
449 TestProtocolManager* pm = pm_factory_.GetProtocolManager();
450 pm->AddGetFullHashResponse(full_hash);
453 bool ShowingInterstitialPage() {
454 WebContents* contents =
455 browser()->tab_strip_model()->GetActiveWebContents();
456 InterstitialPage* interstitial_page = contents->GetInterstitialPage();
457 return interstitial_page != NULL;
460 void IntroduceGetHashDelay(const base::TimeDelta& delay) {
461 pm_factory_.GetProtocolManager()->IntroduceDelay(delay);
464 base::TimeDelta GetCheckTimeout(SafeBrowsingService* sb_service) {
465 return sb_service->database_manager()->check_timeout_;
468 void SetCheckTimeout(SafeBrowsingService* sb_service,
469 const base::TimeDelta& delay) {
470 sb_service->database_manager()->check_timeout_ = delay;
473 void CreateCSDService() {
474 safe_browsing::ClientSideDetectionService* csd_service =
475 safe_browsing::ClientSideDetectionService::Create(NULL);
476 SafeBrowsingService* sb_service =
477 g_browser_process->safe_browsing_service();
478 sb_service->csd_service_.reset(csd_service);
479 sb_service->RefreshState();
482 void ProceedAndWhitelist(
483 const SafeBrowsingUIManager::UnsafeResource& resource) {
484 std::vector<SafeBrowsingUIManager::UnsafeResource> resources;
485 resources.push_back(resource);
486 BrowserThread::PostTask(
487 BrowserThread::IO, FROM_HERE,
488 base::Bind(&SafeBrowsingUIManager::OnBlockingPageDone,
489 g_browser_process->safe_browsing_service()->ui_manager(),
490 resources, true));
491 WaitForIOThread();
494 protected:
495 StrictMock<MockObserver> observer_;
497 // Temporary profile dir for test cases that create a second profile. This is
498 // owned by the SafeBrowsingServiceTest object so that it will not get
499 // destructed until after the test Browser has been torn down, since the
500 // ImportantFileWriter may still be modifying it after the Profile object has
501 // been destroyed.
502 base::ScopedTempDir temp_profile_dir_;
504 // Waits for pending tasks on the IO thread to complete. This is useful
505 // to wait for the SafeBrowsingService to finish loading/stopping.
506 void WaitForIOThread() {
507 scoped_refptr<base::ThreadTestHelper> io_helper(new base::ThreadTestHelper(
508 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get()));
509 ASSERT_TRUE(io_helper->Run());
512 private:
513 scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
514 TestSafeBrowsingDatabaseFactory db_factory_;
515 TestSBProtocolManagerFactory pm_factory_;
517 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTest);
520 enum MalwareMetadataTestType {
521 METADATA_NONE,
522 METADATA_LANDING,
523 METADATA_DISTRIBUTION,
526 class SafeBrowsingServiceMetadataTest
527 : public SafeBrowsingServiceTest,
528 public ::testing::WithParamInterface<MalwareMetadataTestType> {
529 public:
530 SafeBrowsingServiceMetadataTest() {}
532 void GenUrlFullhashResultWithMetadata(const GURL& url,
533 SBFullHashResult* full_hash) {
534 GenUrlFullhashResult(url, safe_browsing_util::MALWARE, full_hash);
536 safe_browsing::MalwarePatternType proto;
537 switch (GetParam()) {
538 case METADATA_NONE:
539 full_hash->metadata = std::string();
540 break;
541 case METADATA_LANDING:
542 proto.set_pattern_type(safe_browsing::MalwarePatternType::LANDING);
543 full_hash->metadata = proto.SerializeAsString();
544 break;
545 case METADATA_DISTRIBUTION:
546 proto.set_pattern_type(safe_browsing::MalwarePatternType::DISTRIBUTION);
547 full_hash->metadata = proto.SerializeAsString();
548 break;
552 private:
553 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceMetadataTest);
556 namespace {
558 const char kEmptyPage[] = "files/empty.html";
559 const char kMalwareFile[] = "files/downloads/dangerous/dangerous.exe";
560 const char kMalwarePage[] = "files/safe_browsing/malware.html";
561 const char kMalwareIFrame[] = "files/safe_browsing/malware_iframe.html";
562 const char kMalwareImg[] = "files/safe_browsing/malware_image.png";
564 // This test goes through DownloadResourceHandler.
565 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareMainFrame) {
566 GURL url = test_server()->GetURL(kEmptyPage);
568 // After adding the url to safebrowsing database and getfullhash result,
569 // we should see the interstitial page.
570 SBFullHashResult malware_full_hash;
571 GenUrlFullhashResultWithMetadata(url, &malware_full_hash);
572 EXPECT_CALL(observer_,
573 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
574 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1);
575 SetupResponseForUrl(url, malware_full_hash);
576 ui_test_utils::NavigateToURL(browser(), url);
577 // All types should show the interstitial.
578 EXPECT_TRUE(ShowingInterstitialPage());
581 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareIFrame) {
582 GURL main_url = test_server()->GetURL(kMalwarePage);
583 GURL iframe_url = test_server()->GetURL(kMalwareIFrame);
585 // Add the iframe url as malware and then load the parent page.
586 SBFullHashResult malware_full_hash;
587 GenUrlFullhashResultWithMetadata(iframe_url, &malware_full_hash);
588 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(iframe_url)))
589 .Times(1);
590 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(iframe_url)))
591 .Times(1);
592 SetupResponseForUrl(iframe_url, malware_full_hash);
593 ui_test_utils::NavigateToURL(browser(), main_url);
594 // All types should show the interstitial.
595 EXPECT_TRUE(ShowingInterstitialPage());
598 IN_PROC_BROWSER_TEST_P(SafeBrowsingServiceMetadataTest, MalwareImg) {
599 GURL main_url = test_server()->GetURL(kMalwarePage);
600 GURL img_url = test_server()->GetURL(kMalwareImg);
602 // Add the img url as malware and then load the parent page.
603 SBFullHashResult malware_full_hash;
604 GenUrlFullhashResultWithMetadata(img_url, &malware_full_hash);
605 switch (GetParam()) {
606 case METADATA_NONE: // Falls through.
607 case METADATA_DISTRIBUTION:
608 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(img_url)))
609 .Times(1);
610 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(img_url)))
611 .Times(1);
612 break;
613 case METADATA_LANDING:
614 // No interstitial shown, so no notifications expected.
615 break;
617 SetupResponseForUrl(img_url, malware_full_hash);
618 ui_test_utils::NavigateToURL(browser(), main_url);
619 // Subresource which is tagged as a landing page should not show an
620 // interstitial, the other types should.
621 switch (GetParam()) {
622 case METADATA_NONE:
623 case METADATA_DISTRIBUTION:
624 EXPECT_TRUE(ShowingInterstitialPage());
625 break;
626 case METADATA_LANDING:
627 EXPECT_FALSE(ShowingInterstitialPage());
628 break;
632 INSTANTIATE_TEST_CASE_P(MaybeSetMetadata,
633 SafeBrowsingServiceMetadataTest,
634 testing::Values(METADATA_NONE,
635 METADATA_LANDING,
636 METADATA_DISTRIBUTION));
638 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, UnwantedImgIgnored) {
639 GURL main_url = test_server()->GetURL(kMalwarePage);
640 GURL img_url = test_server()->GetURL(kMalwareImg);
642 // Add the img url as coming from a site serving UwS and then load the parent
643 // page.
644 SBFullHashResult uws_full_hash;
645 GenUrlFullhashResult(img_url, safe_browsing_util::UNWANTEDURL,
646 &uws_full_hash);
647 SetupResponseForUrl(img_url, uws_full_hash);
649 ui_test_utils::NavigateToURL(browser(), main_url);
651 EXPECT_FALSE(ShowingInterstitialPage());
654 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, DISABLED_MalwareWithWhitelist) {
655 GURL url = test_server()->GetURL(kEmptyPage);
657 // After adding the url to safebrowsing database and getfullhash result,
658 // we should see the interstitial page.
659 SBFullHashResult malware_full_hash;
660 GenUrlFullhashResult(url, safe_browsing_util::MALWARE, &malware_full_hash);
661 EXPECT_CALL(observer_,
662 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
663 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(1)
664 .WillOnce(testing::Invoke(
665 this, &SafeBrowsingServiceTest::ProceedAndWhitelist));
666 SetupResponseForUrl(url, malware_full_hash);
668 ui_test_utils::NavigateToURL(browser(), url);
669 // Mock calls OnBlockingPageDone set to proceed, so the interstitial
670 // is removed.
671 EXPECT_FALSE(ShowingInterstitialPage());
672 Mock::VerifyAndClearExpectations(&observer_);
674 // Navigate back to kEmptyPage -- should hit the whitelist, and send a match
675 // call, but no hit call.
676 EXPECT_CALL(observer_,
677 OnSafeBrowsingMatch(IsUnsafeResourceFor(url))).Times(1);
678 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(url))).Times(0);
679 ui_test_utils::NavigateToURL(browser(), url);
680 EXPECT_FALSE(ShowingInterstitialPage());
683 const char kPrefetchMalwarePage[] = "files/safe_browsing/prefetch_malware.html";
685 // This test confirms that prefetches don't themselves get the
686 // interstitial treatment.
687 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, Prefetch) {
688 GURL url = test_server()->GetURL(kPrefetchMalwarePage);
689 GURL malware_url = test_server()->GetURL(kMalwarePage);
691 class SetPrefetchForTest {
692 public:
693 explicit SetPrefetchForTest(bool prefetch)
694 : old_prerender_mode_(prerender::PrerenderManager::GetMode()) {
695 std::string exp_group = prefetch ? "ExperimentYes" : "ExperimentNo";
696 base::FieldTrialList::CreateFieldTrial("Prefetch", exp_group);
698 prerender::PrerenderManager::SetMode(
699 prerender::PrerenderManager::PRERENDER_MODE_DISABLED);
702 ~SetPrefetchForTest() {
703 prerender::PrerenderManager::SetMode(old_prerender_mode_);
706 private:
707 prerender::PrerenderManager::PrerenderManagerMode old_prerender_mode_;
708 } set_prefetch_for_test(true);
710 // Even though we have added this uri to the safebrowsing database and
711 // getfullhash result, we should not see the interstitial page since the
712 // only malware was a prefetch target.
713 SBFullHashResult malware_full_hash;
714 GenUrlFullhashResult(malware_url, safe_browsing_util::MALWARE,
715 &malware_full_hash);
716 SetupResponseForUrl(malware_url, malware_full_hash);
717 ui_test_utils::NavigateToURL(browser(), url);
718 EXPECT_FALSE(ShowingInterstitialPage());
719 Mock::VerifyAndClear(&observer_);
721 // However, when we navigate to the malware page, we should still get
722 // the interstitial.
723 EXPECT_CALL(observer_, OnSafeBrowsingMatch(IsUnsafeResourceFor(malware_url)))
724 .Times(1);
725 EXPECT_CALL(observer_, OnSafeBrowsingHit(IsUnsafeResourceFor(malware_url)))
726 .Times(1);
727 ui_test_utils::NavigateToURL(browser(), malware_url);
728 EXPECT_TRUE(ShowingInterstitialPage());
729 Mock::VerifyAndClear(&observer_);
732 } // namespace
734 class TestSBClient
735 : public base::RefCountedThreadSafe<TestSBClient>,
736 public SafeBrowsingDatabaseManager::Client {
737 public:
738 TestSBClient()
739 : threat_type_(SB_THREAT_TYPE_SAFE),
740 safe_browsing_service_(g_browser_process->safe_browsing_service()) {
743 SBThreatType GetThreatType() const {
744 return threat_type_;
747 void CheckDownloadUrl(const std::vector<GURL>& url_chain) {
748 BrowserThread::PostTask(
749 BrowserThread::IO, FROM_HERE,
750 base::Bind(&TestSBClient::CheckDownloadUrlOnIOThread,
751 this, url_chain));
752 content::RunMessageLoop(); // Will stop in OnCheckDownloadUrlResult.
755 void CheckBrowseUrl(const GURL& url) {
756 BrowserThread::PostTask(
757 BrowserThread::IO, FROM_HERE,
758 base::Bind(&TestSBClient::CheckBrowseUrlOnIOThread, this, url));
759 content::RunMessageLoop(); // Will stop in OnCheckBrowseUrlResult.
762 private:
763 friend class base::RefCountedThreadSafe<TestSBClient>;
764 ~TestSBClient() override {}
766 void CheckDownloadUrlOnIOThread(const std::vector<GURL>& url_chain) {
767 bool synchronous_safe_signal =
768 safe_browsing_service_->database_manager()->CheckDownloadUrl(url_chain,
769 this);
770 if (synchronous_safe_signal) {
771 threat_type_ = SB_THREAT_TYPE_SAFE;
772 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
773 base::Bind(&TestSBClient::CheckDone, this));
777 void CheckBrowseUrlOnIOThread(const GURL& url) {
778 // The async CheckDone() hook will not be called when we have a synchronous
779 // safe signal, handle it right away.
780 bool synchronous_safe_signal =
781 safe_browsing_service_->database_manager()->CheckBrowseUrl(url, this);
782 if (synchronous_safe_signal) {
783 threat_type_ = SB_THREAT_TYPE_SAFE;
784 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
785 base::Bind(&TestSBClient::CheckDone, this));
789 // Called when the result of checking a download URL is known.
790 void OnCheckDownloadUrlResult(const std::vector<GURL>& /* url_chain */,
791 SBThreatType threat_type) override {
792 threat_type_ = threat_type;
793 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
794 base::Bind(&TestSBClient::CheckDone, this));
797 // Called when the result of checking a browse URL is known.
798 void OnCheckBrowseUrlResult(const GURL& /* url */,
799 SBThreatType threat_type,
800 const std::string& /* metadata */) override {
801 threat_type_ = threat_type;
802 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
803 base::Bind(&TestSBClient::CheckDone, this));
806 void CheckDone() {
807 base::MessageLoopForUI::current()->Quit();
810 SBThreatType threat_type_;
811 SafeBrowsingService* safe_browsing_service_;
813 DISALLOW_COPY_AND_ASSIGN(TestSBClient);
816 // These tests use SafeBrowsingService::Client to directly interact with
817 // SafeBrowsingService.
818 namespace {
820 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrl) {
821 GURL badbin_url = test_server()->GetURL(kMalwareFile);
822 std::vector<GURL> badbin_urls(1, badbin_url);
824 scoped_refptr<TestSBClient> client(new TestSBClient);
825 client->CheckDownloadUrl(badbin_urls);
827 // Since badbin_url is not in database, it is considered to be safe.
828 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
830 SBFullHashResult full_hash_result;
831 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
832 &full_hash_result);
833 SetupResponseForUrl(badbin_url, full_hash_result);
835 client->CheckDownloadUrl(badbin_urls);
837 // Now, the badbin_url is not safe since it is added to download database.
838 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
841 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckUnwantedSoftwareUrl) {
842 const GURL bad_url = test_server()->GetURL(kMalwareFile);
844 scoped_refptr<TestSBClient> client(new TestSBClient);
846 // Since bad_url is not in database, it is considered to be
847 // safe.
848 client->CheckBrowseUrl(bad_url);
849 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
851 SBFullHashResult full_hash_result;
852 GenUrlFullhashResult(
853 bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
854 SetupResponseForUrl(bad_url, full_hash_result);
856 // Now, the bad_url is not safe since it is added to download
857 // database.
858 client->CheckBrowseUrl(bad_url);
859 EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
862 // The unwantedness should survive across multiple clients.
864 scoped_refptr<TestSBClient> client(new TestSBClient);
865 client->CheckBrowseUrl(bad_url);
866 EXPECT_EQ(SB_THREAT_TYPE_URL_UNWANTED, client->GetThreatType());
869 // An unwanted URL also marked as malware should be flagged as malware.
871 scoped_refptr<TestSBClient> client(new TestSBClient);
873 SBFullHashResult full_hash_result;
874 GenUrlFullhashResult(
875 bad_url, safe_browsing_util::MALWARE, &full_hash_result);
876 SetupResponseForUrl(bad_url, full_hash_result);
878 client->CheckBrowseUrl(bad_url);
879 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
883 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckBrowseUrl) {
884 const GURL bad_url = test_server()->GetURL(kMalwareFile);
886 scoped_refptr<TestSBClient> client(new TestSBClient);
888 // Since bad_url is not in database, it is considered to be
889 // safe.
890 client->CheckBrowseUrl(bad_url);
891 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
893 SBFullHashResult full_hash_result;
894 GenUrlFullhashResult(
895 bad_url, safe_browsing_util::MALWARE, &full_hash_result);
896 SetupResponseForUrl(bad_url, full_hash_result);
898 // Now, the bad_url is not safe since it is added to download
899 // database.
900 client->CheckBrowseUrl(bad_url);
901 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
904 // The unwantedness should survive across multiple clients.
906 scoped_refptr<TestSBClient> client(new TestSBClient);
907 client->CheckBrowseUrl(bad_url);
908 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
911 // Adding the unwanted state to an existing malware URL should have no impact
912 // (i.e. a malware hit should still prevail).
914 scoped_refptr<TestSBClient> client(new TestSBClient);
916 SBFullHashResult full_hash_result;
917 GenUrlFullhashResult(
918 bad_url, safe_browsing_util::UNWANTEDURL, &full_hash_result);
919 SetupResponseForUrl(bad_url, full_hash_result);
921 client->CheckBrowseUrl(bad_url);
922 EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, client->GetThreatType());
926 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, CheckDownloadUrlRedirects) {
927 GURL original_url = test_server()->GetURL(kEmptyPage);
928 GURL badbin_url = test_server()->GetURL(kMalwareFile);
929 GURL final_url = test_server()->GetURL(kEmptyPage);
930 std::vector<GURL> badbin_urls;
931 badbin_urls.push_back(original_url);
932 badbin_urls.push_back(badbin_url);
933 badbin_urls.push_back(final_url);
935 scoped_refptr<TestSBClient> client(new TestSBClient);
936 client->CheckDownloadUrl(badbin_urls);
938 // Since badbin_url is not in database, it is considered to be safe.
939 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
941 SBFullHashResult full_hash_result;
942 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
943 &full_hash_result);
944 SetupResponseForUrl(badbin_url, full_hash_result);
946 client->CheckDownloadUrl(badbin_urls);
948 // Now, the badbin_url is not safe since it is added to download database.
949 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
952 #if defined(OS_WIN)
953 // http://crbug.com/396409
954 #define MAYBE_CheckDownloadUrlTimedOut DISABLED_CheckDownloadUrlTimedOut
955 #else
956 #define MAYBE_CheckDownloadUrlTimedOut CheckDownloadUrlTimedOut
957 #endif
958 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest,
959 MAYBE_CheckDownloadUrlTimedOut) {
960 GURL badbin_url = test_server()->GetURL(kMalwareFile);
961 std::vector<GURL> badbin_urls(1, badbin_url);
963 scoped_refptr<TestSBClient> client(new TestSBClient);
964 SBFullHashResult full_hash_result;
965 GenUrlFullhashResult(badbin_url, safe_browsing_util::BINURL,
966 &full_hash_result);
967 SetupResponseForUrl(badbin_url, full_hash_result);
968 client->CheckDownloadUrl(badbin_urls);
970 // badbin_url is not safe since it is added to download database.
971 EXPECT_EQ(SB_THREAT_TYPE_BINARY_MALWARE_URL, client->GetThreatType());
974 // Now introducing delays and we should hit timeout.
976 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
977 base::TimeDelta default_urlcheck_timeout = GetCheckTimeout(sb_service);
978 IntroduceGetHashDelay(base::TimeDelta::FromSeconds(1));
979 SetCheckTimeout(sb_service, base::TimeDelta::FromMilliseconds(1));
980 client->CheckDownloadUrl(badbin_urls);
982 // There should be a timeout and the hash would be considered as safe.
983 EXPECT_EQ(SB_THREAT_TYPE_SAFE, client->GetThreatType());
985 // Need to set the timeout back to the default value.
986 SetCheckTimeout(sb_service, default_urlcheck_timeout);
989 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, StartAndStop) {
990 CreateCSDService();
991 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
992 safe_browsing::ClientSideDetectionService* csd_service =
993 sb_service->safe_browsing_detection_service();
994 PrefService* pref_service = browser()->profile()->GetPrefs();
996 ASSERT_TRUE(sb_service != NULL);
997 ASSERT_TRUE(csd_service != NULL);
998 ASSERT_TRUE(pref_service != NULL);
1000 EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
1002 // SBS might still be starting, make sure this doesn't flake.
1003 WaitForIOThread();
1004 EXPECT_TRUE(sb_service->enabled());
1005 EXPECT_TRUE(csd_service->enabled());
1007 // Add a new Profile. SBS should keep running.
1008 ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
1009 scoped_ptr<Profile> profile2(Profile::CreateProfile(
1010 temp_profile_dir_.path(), NULL, Profile::CREATE_MODE_SYNCHRONOUS));
1011 ASSERT_TRUE(profile2.get() != NULL);
1012 StartupTaskRunnerServiceFactory::GetForProfile(profile2.get())->
1013 StartDeferredTaskRunners();
1014 PrefService* pref_service2 = profile2->GetPrefs();
1015 EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1016 // We don't expect the state to have changed, but if it did, wait for it.
1017 WaitForIOThread();
1018 EXPECT_TRUE(sb_service->enabled());
1019 EXPECT_TRUE(csd_service->enabled());
1021 // Change one of the prefs. SBS should keep running.
1022 pref_service->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1023 WaitForIOThread();
1024 EXPECT_TRUE(sb_service->enabled());
1025 EXPECT_TRUE(csd_service->enabled());
1027 // Change the other pref. SBS should stop now.
1028 pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, false);
1029 WaitForIOThread();
1030 EXPECT_FALSE(sb_service->enabled());
1031 EXPECT_FALSE(csd_service->enabled());
1033 // Turn it back on. SBS comes back.
1034 pref_service2->SetBoolean(prefs::kSafeBrowsingEnabled, true);
1035 WaitForIOThread();
1036 EXPECT_TRUE(sb_service->enabled());
1037 EXPECT_TRUE(csd_service->enabled());
1039 // Delete the Profile. SBS stops again.
1040 pref_service2 = NULL;
1041 profile2.reset();
1042 WaitForIOThread();
1043 EXPECT_FALSE(sb_service->enabled());
1044 EXPECT_FALSE(csd_service->enabled());
1047 } // namespace
1049 class SafeBrowsingServiceShutdownTest : public SafeBrowsingServiceTest {
1050 public:
1051 void TearDown() override {
1052 // Browser should be fully torn down by now, so we can safely check these
1053 // counters.
1054 EXPECT_EQ(1, TestProtocolManager::create_count());
1055 EXPECT_EQ(1, TestProtocolManager::delete_count());
1057 SafeBrowsingServiceTest::TearDown();
1060 // An observer that returns back to test code after a new profile is
1061 // initialized.
1062 void OnUnblockOnProfileCreation(Profile* profile,
1063 Profile::CreateStatus status) {
1064 if (status == Profile::CREATE_STATUS_INITIALIZED) {
1065 profile2_ = profile;
1066 base::MessageLoop::current()->Quit();
1070 protected:
1071 Profile* profile2_;
1074 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceShutdownTest,
1075 DontStartAfterShutdown) {
1076 CreateCSDService();
1077 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
1078 safe_browsing::ClientSideDetectionService* csd_service =
1079 sb_service->safe_browsing_detection_service();
1080 PrefService* pref_service = browser()->profile()->GetPrefs();
1082 ASSERT_TRUE(sb_service != NULL);
1083 ASSERT_TRUE(csd_service != NULL);
1084 ASSERT_TRUE(pref_service != NULL);
1086 EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
1088 // SBS might still be starting, make sure this doesn't flake.
1089 WaitForIOThread();
1090 EXPECT_EQ(1, TestProtocolManager::create_count());
1091 EXPECT_EQ(0, TestProtocolManager::delete_count());
1093 // Create an additional profile. We need to use the ProfileManager so that
1094 // the profile will get destroyed in the normal browser shutdown process.
1095 ProfileManager* profile_manager = g_browser_process->profile_manager();
1096 ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
1097 profile_manager->CreateProfileAsync(
1098 temp_profile_dir_.path(),
1099 base::Bind(&SafeBrowsingServiceShutdownTest::OnUnblockOnProfileCreation,
1100 this),
1101 base::string16(), base::string16(), std::string());
1103 // Spin to allow profile creation to take place, loop is terminated
1104 // by OnUnblockOnProfileCreation when the profile is created.
1105 content::RunMessageLoop();
1107 PrefService* pref_service2 = profile2_->GetPrefs();
1108 EXPECT_TRUE(pref_service2->GetBoolean(prefs::kSafeBrowsingEnabled));
1110 // We don't expect the state to have changed, but if it did, wait for it.
1111 WaitForIOThread();
1112 EXPECT_EQ(1, TestProtocolManager::create_count());
1113 EXPECT_EQ(0, TestProtocolManager::delete_count());
1115 // End the test, shutting down the browser.
1116 // SafeBrowsingServiceShutdownTest::TearDown will check the create_count and
1117 // delete_count again.
1120 class SafeBrowsingDatabaseManagerCookieTest : public InProcessBrowserTest {
1121 public:
1122 SafeBrowsingDatabaseManagerCookieTest() {}
1124 void SetUp() override {
1125 // We need to start the test server to get the host&port in the url.
1126 ASSERT_TRUE(test_server()->Start());
1128 // Point to the testing server for all SafeBrowsing requests.
1129 GURL url_prefix = test_server()->GetURL(
1130 "expect-and-set-cookie?expect=a%3db"
1131 "&set=c%3dd%3b%20Expires=Fri,%2001%20Jan%202038%2001:01:01%20GMT"
1132 "&data=foo#");
1133 sb_factory_.reset(new TestSafeBrowsingServiceFactory(url_prefix.spec()));
1134 SafeBrowsingService::RegisterFactory(sb_factory_.get());
1136 InProcessBrowserTest::SetUp();
1139 void TearDown() override {
1140 InProcessBrowserTest::TearDown();
1142 SafeBrowsingService::RegisterFactory(NULL);
1145 bool SetUpUserDataDirectory() override {
1146 base::FilePath cookie_path(
1147 SafeBrowsingService::GetCookieFilePathForTesting());
1148 EXPECT_FALSE(base::PathExists(cookie_path));
1150 base::FilePath test_dir;
1151 if (!PathService::Get(chrome::DIR_TEST_DATA, &test_dir)) {
1152 EXPECT_TRUE(false);
1153 return false;
1156 // Initialize the SafeBrowsing cookies with a pre-created cookie store. It
1157 // contains a single cookie, for domain 127.0.0.1, with value a=b, and
1158 // expires in 2038.
1159 base::FilePath initial_cookies = test_dir.AppendASCII("safe_browsing")
1160 .AppendASCII("Safe Browsing Cookies");
1161 if (!base::CopyFile(initial_cookies, cookie_path)) {
1162 EXPECT_TRUE(false);
1163 return false;
1166 sql::Connection db;
1167 if (!db.Open(cookie_path)) {
1168 EXPECT_TRUE(false);
1169 return false;
1171 // Ensure the host value in the cookie file matches the test server we will
1172 // be connecting to.
1173 sql::Statement smt(db.GetUniqueStatement(
1174 "UPDATE cookies SET host_key = ?"));
1175 if (!smt.is_valid()) {
1176 EXPECT_TRUE(false);
1177 return false;
1179 if (!smt.BindString(0, test_server()->host_port_pair().host())) {
1180 EXPECT_TRUE(false);
1181 return false;
1183 if (!smt.Run()) {
1184 EXPECT_TRUE(false);
1185 return false;
1188 return InProcessBrowserTest::SetUpUserDataDirectory();
1191 void TearDownInProcessBrowserTestFixture() override {
1192 InProcessBrowserTest::TearDownInProcessBrowserTestFixture();
1194 sql::Connection db;
1195 base::FilePath cookie_path(
1196 SafeBrowsingService::GetCookieFilePathForTesting());
1197 ASSERT_TRUE(db.Open(cookie_path));
1199 sql::Statement smt(db.GetUniqueStatement(
1200 "SELECT name, value FROM cookies ORDER BY name"));
1201 ASSERT_TRUE(smt.is_valid());
1203 ASSERT_TRUE(smt.Step());
1204 ASSERT_EQ("a", smt.ColumnString(0));
1205 ASSERT_EQ("b", smt.ColumnString(1));
1206 ASSERT_TRUE(smt.Step());
1207 ASSERT_EQ("c", smt.ColumnString(0));
1208 ASSERT_EQ("d", smt.ColumnString(1));
1209 EXPECT_FALSE(smt.Step());
1212 void SetUpOnMainThread() override {
1213 sb_service_ = g_browser_process->safe_browsing_service();
1214 ASSERT_TRUE(sb_service_.get() != NULL);
1217 void TearDownOnMainThread() override { sb_service_ = NULL; }
1219 void ForceUpdate() {
1220 sb_service_->protocol_manager()->ForceScheduleNextUpdate(
1221 base::TimeDelta::FromSeconds(0));
1224 scoped_refptr<SafeBrowsingService> sb_service_;
1226 private:
1227 scoped_ptr<TestSafeBrowsingServiceFactory> sb_factory_;
1229 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingDatabaseManagerCookieTest);
1232 // Test that a Safe Browsing database update request both sends cookies and can
1233 // save cookies.
1234 IN_PROC_BROWSER_TEST_F(SafeBrowsingDatabaseManagerCookieTest,
1235 TestSBUpdateCookies) {
1236 content::WindowedNotificationObserver observer(
1237 chrome::NOTIFICATION_SAFE_BROWSING_UPDATE_COMPLETE,
1238 content::Source<SafeBrowsingDatabaseManager>(
1239 sb_service_->database_manager().get()));
1240 BrowserThread::PostTask(
1241 BrowserThread::IO,
1242 FROM_HERE,
1243 base::Bind(&SafeBrowsingDatabaseManagerCookieTest::ForceUpdate, this));
1244 observer.Wait();