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.
5 #include "content/browser/net/sqlite_persistent_cookie_store.h"
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/files/file_util.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/sequenced_task_runner.h"
17 #include "base/stl_util.h"
18 #include "base/synchronization/waitable_event.h"
19 #include "base/test/sequenced_worker_pool_owner.h"
20 #include "base/threading/sequenced_worker_pool.h"
21 #include "base/time/time.h"
22 #include "content/public/browser/cookie_crypto_delegate.h"
23 #include "content/public/browser/cookie_store_factory.h"
24 #include "crypto/encryptor.h"
25 #include "crypto/symmetric_key.h"
26 #include "net/cookies/canonical_cookie.h"
27 #include "net/cookies/cookie_constants.h"
28 #include "sql/connection.h"
29 #include "sql/meta_table.h"
30 #include "sql/statement.h"
31 #include "testing/gtest/include/gtest/gtest.h"
38 const base::FilePath::CharType kCookieFilename
[] = FILE_PATH_LITERAL("Cookies");
40 class CookieCryptor
: public content::CookieCryptoDelegate
{
43 bool EncryptString(const std::string
& plaintext
,
44 std::string
* ciphertext
) override
;
45 bool DecryptString(const std::string
& ciphertext
,
46 std::string
* plaintext
) override
;
49 scoped_ptr
<crypto::SymmetricKey
> key_
;
50 crypto::Encryptor encryptor_
;
53 CookieCryptor::CookieCryptor() : key_(
54 crypto::SymmetricKey::DeriveKeyFromPassword(
55 crypto::SymmetricKey::AES
, "password", "saltiest", 1000, 256)) {
56 std::string
iv("the iv: 16 bytes");
57 encryptor_
.Init(key_
.get(), crypto::Encryptor::CBC
, iv
);
60 bool CookieCryptor::EncryptString(const std::string
& plaintext
,
61 std::string
* ciphertext
) {
62 return encryptor_
.Encrypt(plaintext
, ciphertext
);
65 bool CookieCryptor::DecryptString(const std::string
& ciphertext
,
66 std::string
* plaintext
) {
67 return encryptor_
.Decrypt(ciphertext
, plaintext
);
72 typedef std::vector
<net::CanonicalCookie
*> CanonicalCookieVector
;
74 class SQLitePersistentCookieStoreTest
: public testing::Test
{
76 SQLitePersistentCookieStoreTest()
77 : pool_owner_(new base::SequencedWorkerPoolOwner(3, "Background Pool")),
78 loaded_event_(false, false),
79 key_loaded_event_(false, false),
80 db_thread_event_(false, false) {
83 void OnLoaded(const CanonicalCookieVector
& cookies
) {
85 loaded_event_
.Signal();
88 void OnKeyLoaded(const CanonicalCookieVector
& cookies
) {
90 key_loaded_event_
.Signal();
93 void Load(CanonicalCookieVector
* cookies
) {
94 EXPECT_FALSE(loaded_event_
.IsSignaled());
95 store_
->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded
,
96 base::Unretained(this)));
102 base::WaitableEvent
event(false, false);
103 store_
->Flush(base::Bind(&base::WaitableEvent::Signal
,
104 base::Unretained(&event
)));
108 scoped_refptr
<base::SequencedTaskRunner
> background_task_runner() {
109 return pool_owner_
->pool()->GetSequencedTaskRunner(
110 pool_owner_
->pool()->GetNamedSequenceToken("background"));
113 scoped_refptr
<base::SequencedTaskRunner
> client_task_runner() {
114 return pool_owner_
->pool()->GetSequencedTaskRunner(
115 pool_owner_
->pool()->GetNamedSequenceToken("client"));
118 void DestroyStore() {
120 // Make sure we wait until the destructor has run by shutting down the pool
121 // resetting the owner (whose destructor blocks on the pool completion).
122 pool_owner_
->pool()->Shutdown();
123 // Create a new pool for the few tests that create multiple stores. In other
124 // cases this is wasted but harmless.
125 pool_owner_
.reset(new base::SequencedWorkerPoolOwner(3, "Background Pool"));
128 void CreateAndLoad(bool crypt_cookies
,
129 bool restore_old_session_cookies
,
130 CanonicalCookieVector
* cookies
) {
132 cookie_crypto_delegate_
.reset(new CookieCryptor());
134 store_
= new SQLitePersistentCookieStore(
135 temp_dir_
.path().Append(kCookieFilename
),
136 client_task_runner(),
137 background_task_runner(),
138 restore_old_session_cookies
,
140 cookie_crypto_delegate_
.get());
144 void InitializeStore(bool crypt
, bool restore_old_session_cookies
) {
145 CanonicalCookieVector cookies
;
146 CreateAndLoad(crypt
, restore_old_session_cookies
, &cookies
);
147 EXPECT_EQ(0U, cookies
.size());
150 // We have to create this method to wrap WaitableEvent::Wait, since we cannot
151 // bind a non-void returning method as a Closure.
152 void WaitOnDBEvent() {
153 db_thread_event_
.Wait();
156 // Adds a persistent cookie to store_.
157 void AddCookie(const std::string
& name
,
158 const std::string
& value
,
159 const std::string
& domain
,
160 const std::string
& path
,
161 const base::Time
& creation
) {
163 net::CanonicalCookie(GURL(), name
, value
, domain
, path
, creation
,
164 creation
, creation
, false, false,
165 net::COOKIE_PRIORITY_DEFAULT
));
168 std::string
ReadRawDBContents() {
169 std::string contents
;
170 if (!base::ReadFileToString(temp_dir_
.path().Append(kCookieFilename
),
172 return std::string();
176 void SetUp() override
{ ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir()); }
178 void TearDown() override
{
180 pool_owner_
->pool()->Shutdown();
184 base::MessageLoop main_loop_
;
185 scoped_ptr
<base::SequencedWorkerPoolOwner
> pool_owner_
;
186 base::WaitableEvent loaded_event_
;
187 base::WaitableEvent key_loaded_event_
;
188 base::WaitableEvent db_thread_event_
;
189 CanonicalCookieVector cookies_
;
190 base::ScopedTempDir temp_dir_
;
191 scoped_refptr
<SQLitePersistentCookieStore
> store_
;
192 scoped_ptr
<content::CookieCryptoDelegate
> cookie_crypto_delegate_
;
195 TEST_F(SQLitePersistentCookieStoreTest
, TestInvalidMetaTableRecovery
) {
196 InitializeStore(false, false);
197 AddCookie("A", "B", "foo.bar", "/", base::Time::Now());
200 // Load up the store and verify that it has good data in it.
201 CanonicalCookieVector cookies
;
202 CreateAndLoad(false, false, &cookies
);
203 ASSERT_EQ(1U, cookies
.size());
204 ASSERT_STREQ("foo.bar", cookies
[0]->Domain().c_str());
205 ASSERT_STREQ("A", cookies
[0]->Name().c_str());
206 ASSERT_STREQ("B", cookies
[0]->Value().c_str());
208 STLDeleteElements(&cookies
);
210 // Now corrupt the meta table.
213 ASSERT_TRUE(db
.Open(temp_dir_
.path().Append(kCookieFilename
)));
214 sql::MetaTable meta_table_
;
215 meta_table_
.Init(&db
, 1, 1);
216 ASSERT_TRUE(db
.Execute("DELETE FROM meta"));
220 // Upon loading, the database should be reset to a good, blank state.
221 CreateAndLoad(false, false, &cookies
);
222 ASSERT_EQ(0U, cookies
.size());
224 // Verify that, after, recovery, the database persists properly.
225 AddCookie("X", "Y", "foo.bar", "/", base::Time::Now());
227 CreateAndLoad(false, false, &cookies
);
228 ASSERT_EQ(1U, cookies
.size());
229 ASSERT_STREQ("foo.bar", cookies
[0]->Domain().c_str());
230 ASSERT_STREQ("X", cookies
[0]->Name().c_str());
231 ASSERT_STREQ("Y", cookies
[0]->Value().c_str());
232 STLDeleteElements(&cookies
);
235 // Test if data is stored as expected in the SQLite database.
236 TEST_F(SQLitePersistentCookieStoreTest
, TestPersistance
) {
237 InitializeStore(false, false);
238 AddCookie("A", "B", "foo.bar", "/", base::Time::Now());
239 // Replace the store effectively destroying the current one and forcing it
240 // to write its data to disk. Then we can see if after loading it again it
243 // Reload and test for persistence
244 CanonicalCookieVector cookies
;
245 CreateAndLoad(false, false, &cookies
);
246 ASSERT_EQ(1U, cookies
.size());
247 ASSERT_STREQ("foo.bar", cookies
[0]->Domain().c_str());
248 ASSERT_STREQ("A", cookies
[0]->Name().c_str());
249 ASSERT_STREQ("B", cookies
[0]->Value().c_str());
251 // Now delete the cookie and check persistence again.
252 store_
->DeleteCookie(*cookies
[0]);
254 STLDeleteElements(&cookies
);
256 // Reload and check if the cookie has been removed.
257 CreateAndLoad(false, false, &cookies
);
258 ASSERT_EQ(0U, cookies
.size());
261 // Test that priority load of cookies for a specfic domain key could be
262 // completed before the entire store is loaded
263 TEST_F(SQLitePersistentCookieStoreTest
, TestLoadCookiesForKey
) {
264 InitializeStore(false, false);
265 base::Time t
= base::Time::Now();
266 AddCookie("A", "B", "foo.bar", "/", t
);
267 t
+= base::TimeDelta::FromInternalValue(10);
268 AddCookie("A", "B", "www.aaa.com", "/", t
);
269 t
+= base::TimeDelta::FromInternalValue(10);
270 AddCookie("A", "B", "travel.aaa.com", "/", t
);
271 t
+= base::TimeDelta::FromInternalValue(10);
272 AddCookie("A", "B", "www.bbb.com", "/", t
);
275 store_
= new SQLitePersistentCookieStore(
276 temp_dir_
.path().Append(kCookieFilename
),
277 client_task_runner(),
278 background_task_runner(),
281 // Posting a blocking task to db_thread_ makes sure that the DB thread waits
282 // until both Load and LoadCookiesForKey have been posted to its task queue.
283 background_task_runner()->PostTask(
285 base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent
,
286 base::Unretained(this)));
287 store_
->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded
,
288 base::Unretained(this)));
289 store_
->LoadCookiesForKey("aaa.com",
290 base::Bind(&SQLitePersistentCookieStoreTest::OnKeyLoaded
,
291 base::Unretained(this)));
292 background_task_runner()->PostTask(
294 base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent
,
295 base::Unretained(this)));
297 // Now the DB-thread queue contains:
299 // 1. Wait (on db_event)
301 // 2. "Init And Chain-Load First Domain"
302 // 3. Priority Load (aaa.com)
303 // 4. Wait (on db_event)
304 db_thread_event_
.Signal();
305 key_loaded_event_
.Wait();
306 ASSERT_EQ(loaded_event_
.IsSignaled(), false);
307 std::set
<std::string
> cookies_loaded
;
308 for (CanonicalCookieVector::const_iterator it
= cookies_
.begin();
309 it
!= cookies_
.end();
311 cookies_loaded
.insert((*it
)->Domain().c_str());
313 STLDeleteElements(&cookies_
);
314 ASSERT_GT(4U, cookies_loaded
.size());
315 ASSERT_EQ(true, cookies_loaded
.find("www.aaa.com") != cookies_loaded
.end());
317 cookies_loaded
.find("travel.aaa.com") != cookies_loaded
.end());
319 db_thread_event_
.Signal();
320 loaded_event_
.Wait();
321 for (CanonicalCookieVector::const_iterator it
= cookies_
.begin();
322 it
!= cookies_
.end();
324 cookies_loaded
.insert((*it
)->Domain().c_str());
326 ASSERT_EQ(4U, cookies_loaded
.size());
327 ASSERT_EQ(cookies_loaded
.find("foo.bar") != cookies_loaded
.end(),
329 ASSERT_EQ(cookies_loaded
.find("www.bbb.com") != cookies_loaded
.end(), true);
330 STLDeleteElements(&cookies_
);
333 // Test that we can force the database to be written by calling Flush().
334 TEST_F(SQLitePersistentCookieStoreTest
, TestFlush
) {
335 InitializeStore(false, false);
336 // File timestamps don't work well on all platforms, so we'll determine
337 // whether the DB file has been modified by checking its size.
338 base::FilePath path
= temp_dir_
.path().Append(kCookieFilename
);
339 base::File::Info info
;
340 ASSERT_TRUE(base::GetFileInfo(path
, &info
));
341 int64 base_size
= info
.size
;
343 // Write some large cookies, so the DB will have to expand by several KB.
344 for (char c
= 'a'; c
< 'z'; ++c
) {
345 // Each cookie needs a unique timestamp for creation_utc (see DB schema).
346 base::Time t
= base::Time::Now() + base::TimeDelta::FromMicroseconds(c
);
347 std::string
name(1, c
);
348 std::string
value(1000, c
);
349 AddCookie(name
, value
, "foo.bar", "/", t
);
354 // We forced a write, so now the file will be bigger.
355 ASSERT_TRUE(base::GetFileInfo(path
, &info
));
356 ASSERT_GT(info
.size
, base_size
);
359 // Test loading old session cookies from the disk.
360 TEST_F(SQLitePersistentCookieStoreTest
, TestLoadOldSessionCookies
) {
361 InitializeStore(false, true);
363 // Add a session cookie.
365 net::CanonicalCookie(
366 GURL(), "C", "D", "sessioncookie.com", "/", base::Time::Now(),
367 base::Time(), base::Time::Now(), false, false,
368 net::COOKIE_PRIORITY_DEFAULT
));
370 // Force the store to write its data to the disk.
373 // Create a store that loads session cookies and test that the session cookie
375 CanonicalCookieVector cookies
;
376 CreateAndLoad(false, true, &cookies
);
378 ASSERT_EQ(1U, cookies
.size());
379 ASSERT_STREQ("sessioncookie.com", cookies
[0]->Domain().c_str());
380 ASSERT_STREQ("C", cookies
[0]->Name().c_str());
381 ASSERT_STREQ("D", cookies
[0]->Value().c_str());
382 ASSERT_EQ(net::COOKIE_PRIORITY_DEFAULT
, cookies
[0]->Priority());
384 STLDeleteElements(&cookies
);
387 // Test loading old session cookies from the disk.
388 TEST_F(SQLitePersistentCookieStoreTest
, TestDontLoadOldSessionCookies
) {
389 InitializeStore(false, true);
391 // Add a session cookie.
393 net::CanonicalCookie(
394 GURL(), "C", "D", "sessioncookie.com", "/", base::Time::Now(),
395 base::Time(), base::Time::Now(), false, false,
396 net::COOKIE_PRIORITY_DEFAULT
));
398 // Force the store to write its data to the disk.
401 // Create a store that doesn't load old session cookies and test that the
402 // session cookie was not loaded.
403 CanonicalCookieVector cookies
;
404 CreateAndLoad(false, false, &cookies
);
405 ASSERT_EQ(0U, cookies
.size());
407 // The store should also delete the session cookie. Wait until that has been
411 // Create a store that loads old session cookies and test that the session
413 CreateAndLoad(false, true, &cookies
);
414 ASSERT_EQ(0U, cookies
.size());
417 TEST_F(SQLitePersistentCookieStoreTest
, PersistIsPersistent
) {
418 InitializeStore(false, true);
419 static const char kSessionName
[] = "session";
420 static const char kPersistentName
[] = "persistent";
422 // Add a session cookie.
424 net::CanonicalCookie(
425 GURL(), kSessionName
, "val", "sessioncookie.com", "/",
426 base::Time::Now(), base::Time(), base::Time::Now(), false, false,
427 net::COOKIE_PRIORITY_DEFAULT
));
428 // Add a persistent cookie.
430 net::CanonicalCookie(
431 GURL(), kPersistentName
, "val", "sessioncookie.com", "/",
432 base::Time::Now() - base::TimeDelta::FromDays(1),
433 base::Time::Now() + base::TimeDelta::FromDays(1),
434 base::Time::Now(), false, false,
435 net::COOKIE_PRIORITY_DEFAULT
));
437 // Force the store to write its data to the disk.
440 // Create a store that loads session cookie and test that the IsPersistent
441 // attribute is restored.
442 CanonicalCookieVector cookies
;
443 CreateAndLoad(false, true, &cookies
);
444 ASSERT_EQ(2U, cookies
.size());
446 std::map
<std::string
, net::CanonicalCookie
*> cookie_map
;
447 for (CanonicalCookieVector::const_iterator it
= cookies
.begin();
450 cookie_map
[(*it
)->Name()] = *it
;
453 std::map
<std::string
, net::CanonicalCookie
*>::const_iterator it
=
454 cookie_map
.find(kSessionName
);
455 ASSERT_TRUE(it
!= cookie_map
.end());
456 EXPECT_FALSE(cookie_map
[kSessionName
]->IsPersistent());
458 it
= cookie_map
.find(kPersistentName
);
459 ASSERT_TRUE(it
!= cookie_map
.end());
460 EXPECT_TRUE(cookie_map
[kPersistentName
]->IsPersistent());
462 STLDeleteElements(&cookies
);
465 TEST_F(SQLitePersistentCookieStoreTest
, PriorityIsPersistent
) {
466 static const char kLowName
[] = "low";
467 static const char kMediumName
[] = "medium";
468 static const char kHighName
[] = "high";
469 static const char kCookieDomain
[] = "sessioncookie.com";
470 static const char kCookieValue
[] = "value";
471 static const char kCookiePath
[] = "/";
473 InitializeStore(false, true);
475 // Add a low-priority persistent cookie.
477 net::CanonicalCookie(
478 GURL(), kLowName
, kCookieValue
, kCookieDomain
, kCookiePath
,
479 base::Time::Now() - base::TimeDelta::FromMinutes(1),
480 base::Time::Now() + base::TimeDelta::FromDays(1),
481 base::Time::Now(), false, false,
482 net::COOKIE_PRIORITY_LOW
));
484 // Add a medium-priority persistent cookie.
486 net::CanonicalCookie(
487 GURL(), kMediumName
, kCookieValue
, kCookieDomain
, kCookiePath
,
488 base::Time::Now() - base::TimeDelta::FromMinutes(2),
489 base::Time::Now() + base::TimeDelta::FromDays(1),
490 base::Time::Now(), false, false,
491 net::COOKIE_PRIORITY_MEDIUM
));
493 // Add a high-priority peristent cookie.
495 net::CanonicalCookie(
496 GURL(), kHighName
, kCookieValue
, kCookieDomain
, kCookiePath
,
497 base::Time::Now() - base::TimeDelta::FromMinutes(3),
498 base::Time::Now() + base::TimeDelta::FromDays(1),
499 base::Time::Now(), false, false,
500 net::COOKIE_PRIORITY_HIGH
));
502 // Force the store to write its data to the disk.
505 // Create a store that loads session cookie and test that the priority
506 // attribute values are restored.
507 CanonicalCookieVector cookies
;
508 CreateAndLoad(false, true, &cookies
);
509 ASSERT_EQ(3U, cookies
.size());
511 // Put the cookies into a map, by name, so we can easily find them.
512 std::map
<std::string
, net::CanonicalCookie
*> cookie_map
;
513 for (CanonicalCookieVector::const_iterator it
= cookies
.begin();
516 cookie_map
[(*it
)->Name()] = *it
;
519 // Validate that each cookie has the correct priority.
520 std::map
<std::string
, net::CanonicalCookie
*>::const_iterator it
=
521 cookie_map
.find(kLowName
);
522 ASSERT_TRUE(it
!= cookie_map
.end());
523 EXPECT_EQ(net::COOKIE_PRIORITY_LOW
, cookie_map
[kLowName
]->Priority());
525 it
= cookie_map
.find(kMediumName
);
526 ASSERT_TRUE(it
!= cookie_map
.end());
527 EXPECT_EQ(net::COOKIE_PRIORITY_MEDIUM
, cookie_map
[kMediumName
]->Priority());
529 it
= cookie_map
.find(kHighName
);
530 ASSERT_TRUE(it
!= cookie_map
.end());
531 EXPECT_EQ(net::COOKIE_PRIORITY_HIGH
, cookie_map
[kHighName
]->Priority());
533 STLDeleteElements(&cookies
);
536 TEST_F(SQLitePersistentCookieStoreTest
, UpdateToEncryption
) {
537 CanonicalCookieVector cookies
;
539 // Create unencrypted cookie store and write something to it.
540 InitializeStore(false, false);
541 AddCookie("name", "value123XYZ", "foo.bar", "/", base::Time::Now());
544 // Verify that "value" is visible in the file. This is necessary in order to
545 // have confidence in a later test that "encrypted_value" is not visible.
546 std::string contents
= ReadRawDBContents();
547 EXPECT_NE(0U, contents
.length());
548 EXPECT_NE(contents
.find("value123XYZ"), std::string::npos
);
550 // Create encrypted cookie store and ensure old cookie still reads.
551 STLDeleteElements(&cookies_
);
552 EXPECT_EQ(0U, cookies_
.size());
553 CreateAndLoad(true, false, &cookies
);
554 EXPECT_EQ(1U, cookies_
.size());
555 EXPECT_EQ("name", cookies_
[0]->Name());
556 EXPECT_EQ("value123XYZ", cookies_
[0]->Value());
558 // Make sure we can update existing cookie and add new cookie as encrypted.
559 store_
->DeleteCookie(*(cookies_
[0]));
560 AddCookie("name", "encrypted_value123XYZ", "foo.bar", "/", base::Time::Now());
561 AddCookie("other", "something456ABC", "foo.bar", "/",
562 base::Time::Now() + base::TimeDelta::FromInternalValue(10));
564 STLDeleteElements(&cookies_
);
565 CreateAndLoad(true, false, &cookies
);
566 EXPECT_EQ(2U, cookies_
.size());
567 net::CanonicalCookie
* cookie_name
= NULL
;
568 net::CanonicalCookie
* cookie_other
= NULL
;
569 if (cookies_
[0]->Name() == "name") {
570 cookie_name
= cookies_
[0];
571 cookie_other
= cookies_
[1];
573 cookie_name
= cookies_
[1];
574 cookie_other
= cookies_
[0];
576 EXPECT_EQ("encrypted_value123XYZ", cookie_name
->Value());
577 EXPECT_EQ("something456ABC", cookie_other
->Value());
579 STLDeleteElements(&cookies_
);
581 // Examine the real record to make sure plaintext version doesn't exist.
585 ASSERT_TRUE(db
.Open(temp_dir_
.path().Append(kCookieFilename
)));
586 smt
.Assign(db
.GetCachedStatement(SQL_FROM_HERE
,
589 "WHERE host_key = 'foo.bar'"));
592 for (int i
=0; i
< smt
.ColumnCount(); i
++) {
593 EXPECT_EQ(smt
.ColumnString(i
).find("value"), std::string::npos
);
594 EXPECT_EQ(smt
.ColumnString(i
).find("something"), std::string::npos
);
597 EXPECT_EQ(2, resultcount
);
599 // Verify that "encrypted_value" is NOT visible in the file.
600 contents
= ReadRawDBContents();
601 EXPECT_NE(0U, contents
.length());
602 EXPECT_EQ(contents
.find("encrypted_value123XYZ"), std::string::npos
);
603 EXPECT_EQ(contents
.find("something456ABC"), std::string::npos
);
606 } // namespace content