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 "net/extras/sqlite/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/location.h"
15 #include "base/memory/ref_counted.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 "crypto/encryptor.h"
23 #include "crypto/symmetric_key.h"
24 #include "net/cookies/canonical_cookie.h"
25 #include "net/cookies/cookie_constants.h"
26 #include "net/extras/sqlite/cookie_crypto_delegate.h"
27 #include "sql/connection.h"
28 #include "sql/meta_table.h"
29 #include "sql/statement.h"
30 #include "testing/gtest/include/gtest/gtest.h"
37 const base::FilePath::CharType kCookieFilename
[] = FILE_PATH_LITERAL("Cookies");
39 class CookieCryptor
: public CookieCryptoDelegate
{
42 bool ShouldEncrypt() override
;
43 bool EncryptString(const std::string
& plaintext
,
44 std::string
* ciphertext
) override
;
45 bool DecryptString(const std::string
& ciphertext
,
46 std::string
* plaintext
) override
;
51 scoped_ptr
<crypto::SymmetricKey
> key_
;
52 crypto::Encryptor encryptor_
;
55 CookieCryptor::CookieCryptor()
56 : should_encrypt_(true),
58 crypto::SymmetricKey::DeriveKeyFromPassword(crypto::SymmetricKey::AES
,
63 std::string
iv("the iv: 16 bytes");
64 encryptor_
.Init(key_
.get(), crypto::Encryptor::CBC
, iv
);
67 bool CookieCryptor::ShouldEncrypt() {
68 return should_encrypt_
;
71 bool CookieCryptor::EncryptString(const std::string
& plaintext
,
72 std::string
* ciphertext
) {
73 return encryptor_
.Encrypt(plaintext
, ciphertext
);
76 bool CookieCryptor::DecryptString(const std::string
& ciphertext
,
77 std::string
* plaintext
) {
78 return encryptor_
.Decrypt(ciphertext
, plaintext
);
83 typedef std::vector
<CanonicalCookie
*> CanonicalCookieVector
;
85 class SQLitePersistentCookieStoreTest
: public testing::Test
{
87 SQLitePersistentCookieStoreTest()
88 : pool_owner_(new base::SequencedWorkerPoolOwner(3, "Background Pool")),
89 loaded_event_(false, false),
90 key_loaded_event_(false, false),
91 db_thread_event_(false, false) {}
93 void OnLoaded(const CanonicalCookieVector
& cookies
) {
95 loaded_event_
.Signal();
98 void OnKeyLoaded(const CanonicalCookieVector
& cookies
) {
100 key_loaded_event_
.Signal();
103 void Load(CanonicalCookieVector
* cookies
) {
104 EXPECT_FALSE(loaded_event_
.IsSignaled());
105 store_
->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded
,
106 base::Unretained(this)));
107 loaded_event_
.Wait();
112 base::WaitableEvent
event(false, false);
114 base::Bind(&base::WaitableEvent::Signal
, base::Unretained(&event
)));
118 scoped_refptr
<base::SequencedTaskRunner
> background_task_runner() {
119 return pool_owner_
->pool()->GetSequencedTaskRunner(
120 pool_owner_
->pool()->GetNamedSequenceToken("background"));
123 scoped_refptr
<base::SequencedTaskRunner
> client_task_runner() {
124 return pool_owner_
->pool()->GetSequencedTaskRunner(
125 pool_owner_
->pool()->GetNamedSequenceToken("client"));
128 void DestroyStore() {
130 // Make sure we wait until the destructor has run by shutting down the pool
131 // resetting the owner (whose destructor blocks on the pool completion).
132 pool_owner_
->pool()->Shutdown();
133 // Create a new pool for the few tests that create multiple stores. In other
134 // cases this is wasted but harmless.
135 pool_owner_
.reset(new base::SequencedWorkerPoolOwner(3, "Background Pool"));
138 void Create(bool crypt_cookies
, bool restore_old_session_cookies
) {
140 cookie_crypto_delegate_
.reset(new CookieCryptor());
142 store_
= new SQLitePersistentCookieStore(
143 temp_dir_
.path().Append(kCookieFilename
), client_task_runner(),
144 background_task_runner(), restore_old_session_cookies
,
145 cookie_crypto_delegate_
.get());
148 void CreateAndLoad(bool crypt_cookies
,
149 bool restore_old_session_cookies
,
150 CanonicalCookieVector
* cookies
) {
151 Create(crypt_cookies
, restore_old_session_cookies
);
155 void InitializeStore(bool crypt
, bool restore_old_session_cookies
) {
156 CanonicalCookieVector cookies
;
157 CreateAndLoad(crypt
, restore_old_session_cookies
, &cookies
);
158 EXPECT_EQ(0U, cookies
.size());
161 // We have to create this method to wrap WaitableEvent::Wait, since we cannot
162 // bind a non-void returning method as a Closure.
163 void WaitOnDBEvent() { db_thread_event_
.Wait(); }
165 // Adds a persistent cookie to store_.
166 void AddCookie(const std::string
& name
,
167 const std::string
& value
,
168 const std::string
& domain
,
169 const std::string
& path
,
170 const base::Time
& creation
) {
171 store_
->AddCookie(CanonicalCookie(GURL(), name
, value
, domain
, path
,
172 creation
, creation
, creation
, false,
173 false, false, COOKIE_PRIORITY_DEFAULT
));
176 void AddCookieWithExpiration(const std::string
& name
,
177 const std::string
& value
,
178 const std::string
& domain
,
179 const std::string
& path
,
180 const base::Time
& creation
,
181 const base::Time
& expiration
) {
182 store_
->AddCookie(CanonicalCookie(GURL(), name
, value
, domain
, path
,
183 creation
, expiration
, creation
, false,
184 false, false, COOKIE_PRIORITY_DEFAULT
));
187 std::string
ReadRawDBContents() {
188 std::string contents
;
189 if (!base::ReadFileToString(temp_dir_
.path().Append(kCookieFilename
),
191 return std::string();
195 void SetUp() override
{ ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir()); }
197 void TearDown() override
{
199 pool_owner_
->pool()->Shutdown();
203 scoped_ptr
<base::SequencedWorkerPoolOwner
> pool_owner_
;
204 base::WaitableEvent loaded_event_
;
205 base::WaitableEvent key_loaded_event_
;
206 base::WaitableEvent db_thread_event_
;
207 CanonicalCookieVector cookies_
;
208 base::ScopedTempDir temp_dir_
;
209 scoped_refptr
<SQLitePersistentCookieStore
> store_
;
210 scoped_ptr
<CookieCryptor
> cookie_crypto_delegate_
;
213 TEST_F(SQLitePersistentCookieStoreTest
, TestInvalidMetaTableRecovery
) {
214 InitializeStore(false, false);
215 AddCookie("A", "B", "foo.bar", "/", base::Time::Now());
218 // Load up the store and verify that it has good data in it.
219 CanonicalCookieVector cookies
;
220 CreateAndLoad(false, false, &cookies
);
221 ASSERT_EQ(1U, cookies
.size());
222 ASSERT_STREQ("foo.bar", cookies
[0]->Domain().c_str());
223 ASSERT_STREQ("A", cookies
[0]->Name().c_str());
224 ASSERT_STREQ("B", cookies
[0]->Value().c_str());
226 STLDeleteElements(&cookies
);
228 // Now corrupt the meta table.
231 ASSERT_TRUE(db
.Open(temp_dir_
.path().Append(kCookieFilename
)));
232 sql::MetaTable meta_table_
;
233 meta_table_
.Init(&db
, 1, 1);
234 ASSERT_TRUE(db
.Execute("DELETE FROM meta"));
238 // Upon loading, the database should be reset to a good, blank state.
239 CreateAndLoad(false, false, &cookies
);
240 ASSERT_EQ(0U, cookies
.size());
242 // Verify that, after, recovery, the database persists properly.
243 AddCookie("X", "Y", "foo.bar", "/", base::Time::Now());
245 CreateAndLoad(false, false, &cookies
);
246 ASSERT_EQ(1U, cookies
.size());
247 ASSERT_STREQ("foo.bar", cookies
[0]->Domain().c_str());
248 ASSERT_STREQ("X", cookies
[0]->Name().c_str());
249 ASSERT_STREQ("Y", cookies
[0]->Value().c_str());
250 STLDeleteElements(&cookies
);
253 // Test if data is stored as expected in the SQLite database.
254 TEST_F(SQLitePersistentCookieStoreTest
, TestPersistance
) {
255 InitializeStore(false, false);
256 AddCookie("A", "B", "foo.bar", "/", base::Time::Now());
257 // Replace the store effectively destroying the current one and forcing it
258 // to write its data to disk. Then we can see if after loading it again it
261 // Reload and test for persistence
262 CanonicalCookieVector cookies
;
263 CreateAndLoad(false, false, &cookies
);
264 ASSERT_EQ(1U, cookies
.size());
265 ASSERT_STREQ("foo.bar", cookies
[0]->Domain().c_str());
266 ASSERT_STREQ("A", cookies
[0]->Name().c_str());
267 ASSERT_STREQ("B", cookies
[0]->Value().c_str());
269 // Now delete the cookie and check persistence again.
270 store_
->DeleteCookie(*cookies
[0]);
272 STLDeleteElements(&cookies
);
274 // Reload and check if the cookie has been removed.
275 CreateAndLoad(false, false, &cookies
);
276 ASSERT_EQ(0U, cookies
.size());
279 TEST_F(SQLitePersistentCookieStoreTest
, TestSessionCookiesDeletedOnStartup
) {
280 // Initialize the cookie store with 3 persistent cookies, 5 transient
282 InitializeStore(false, false);
284 // Add persistent cookies.
285 base::Time t
= base::Time::Now();
286 AddCookie("A", "B", "a1.com", "/", t
);
287 t
+= base::TimeDelta::FromInternalValue(10);
288 AddCookie("A", "B", "a2.com", "/", t
);
289 t
+= base::TimeDelta::FromInternalValue(10);
290 AddCookie("A", "B", "a3.com", "/", t
);
292 // Add transient cookies.
293 t
+= base::TimeDelta::FromInternalValue(10);
294 AddCookieWithExpiration("A", "B", "b1.com", "/", t
, base::Time());
295 t
+= base::TimeDelta::FromInternalValue(10);
296 AddCookieWithExpiration("A", "B", "b2.com", "/", t
, base::Time());
297 t
+= base::TimeDelta::FromInternalValue(10);
298 AddCookieWithExpiration("A", "B", "b3.com", "/", t
, base::Time());
299 t
+= base::TimeDelta::FromInternalValue(10);
300 AddCookieWithExpiration("A", "B", "b4.com", "/", t
, base::Time());
301 t
+= base::TimeDelta::FromInternalValue(10);
302 AddCookieWithExpiration("A", "B", "b5.com", "/", t
, base::Time());
305 // Load the store a second time. Before the store finishes loading, add a
306 // transient cookie and flush it to disk.
307 store_
= new SQLitePersistentCookieStore(
308 temp_dir_
.path().Append(kCookieFilename
), client_task_runner(),
309 background_task_runner(), false, nullptr);
311 // Posting a blocking task to db_thread_ makes sure that the DB thread waits
312 // until both Load and Flush have been posted to its task queue.
313 background_task_runner()->PostTask(
314 FROM_HERE
, base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent
,
315 base::Unretained(this)));
316 store_
->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded
,
317 base::Unretained(this)));
318 t
+= base::TimeDelta::FromInternalValue(10);
319 AddCookieWithExpiration("A", "B", "c.com", "/", t
, base::Time());
320 base::WaitableEvent
event(false, false);
322 base::Bind(&base::WaitableEvent::Signal
, base::Unretained(&event
)));
324 // Now the DB-thread queue contains:
326 // 1. Wait (on db_event)
328 // 2. "Init And Chain-Load First Domain"
329 // 3. Add Cookie (c.com)
330 // 4. Flush Cookie (c.com)
331 db_thread_event_
.Signal();
333 loaded_event_
.Wait();
334 STLDeleteElements(&cookies_
);
337 // Load the store a third time, this time restoring session cookies. The
338 // store should contain exactly 4 cookies: the 3 persistent, and "c.com",
339 // which was added during the second cookie store load.
340 store_
= new SQLitePersistentCookieStore(
341 temp_dir_
.path().Append(kCookieFilename
), client_task_runner(),
342 background_task_runner(), true, nullptr);
343 store_
->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded
,
344 base::Unretained(this)));
345 loaded_event_
.Wait();
346 ASSERT_EQ(4u, cookies_
.size());
347 STLDeleteElements(&cookies_
);
350 // Test that priority load of cookies for a specfic domain key could be
351 // completed before the entire store is loaded
352 TEST_F(SQLitePersistentCookieStoreTest
, TestLoadCookiesForKey
) {
353 InitializeStore(false, false);
354 base::Time t
= base::Time::Now();
355 AddCookie("A", "B", "foo.bar", "/", t
);
356 t
+= base::TimeDelta::FromInternalValue(10);
357 AddCookie("A", "B", "www.aaa.com", "/", t
);
358 t
+= base::TimeDelta::FromInternalValue(10);
359 AddCookie("A", "B", "travel.aaa.com", "/", t
);
360 t
+= base::TimeDelta::FromInternalValue(10);
361 AddCookie("A", "B", "www.bbb.com", "/", t
);
364 store_
= new SQLitePersistentCookieStore(
365 temp_dir_
.path().Append(kCookieFilename
), client_task_runner(),
366 background_task_runner(), false, nullptr);
368 // Posting a blocking task to db_thread_ makes sure that the DB thread waits
369 // until both Load and LoadCookiesForKey have been posted to its task queue.
370 background_task_runner()->PostTask(
371 FROM_HERE
, base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent
,
372 base::Unretained(this)));
373 store_
->Load(base::Bind(&SQLitePersistentCookieStoreTest::OnLoaded
,
374 base::Unretained(this)));
375 store_
->LoadCookiesForKey(
376 "aaa.com", base::Bind(&SQLitePersistentCookieStoreTest::OnKeyLoaded
,
377 base::Unretained(this)));
378 background_task_runner()->PostTask(
379 FROM_HERE
, base::Bind(&SQLitePersistentCookieStoreTest::WaitOnDBEvent
,
380 base::Unretained(this)));
382 // Now the DB-thread queue contains:
384 // 1. Wait (on db_event)
386 // 2. "Init And Chain-Load First Domain"
387 // 3. Priority Load (aaa.com)
388 // 4. Wait (on db_event)
389 db_thread_event_
.Signal();
390 key_loaded_event_
.Wait();
391 ASSERT_EQ(loaded_event_
.IsSignaled(), false);
392 std::set
<std::string
> cookies_loaded
;
393 for (CanonicalCookieVector::const_iterator it
= cookies_
.begin();
394 it
!= cookies_
.end(); ++it
) {
395 cookies_loaded
.insert((*it
)->Domain().c_str());
397 STLDeleteElements(&cookies_
);
398 ASSERT_GT(4U, cookies_loaded
.size());
399 ASSERT_EQ(true, cookies_loaded
.find("www.aaa.com") != cookies_loaded
.end());
401 cookies_loaded
.find("travel.aaa.com") != cookies_loaded
.end());
403 db_thread_event_
.Signal();
404 loaded_event_
.Wait();
405 for (CanonicalCookieVector::const_iterator it
= cookies_
.begin();
406 it
!= cookies_
.end(); ++it
) {
407 cookies_loaded
.insert((*it
)->Domain().c_str());
409 ASSERT_EQ(4U, cookies_loaded
.size());
410 ASSERT_EQ(cookies_loaded
.find("foo.bar") != cookies_loaded
.end(), true);
411 ASSERT_EQ(cookies_loaded
.find("www.bbb.com") != cookies_loaded
.end(), true);
412 STLDeleteElements(&cookies_
);
415 // Test that we can force the database to be written by calling Flush().
416 TEST_F(SQLitePersistentCookieStoreTest
, TestFlush
) {
417 InitializeStore(false, false);
418 // File timestamps don't work well on all platforms, so we'll determine
419 // whether the DB file has been modified by checking its size.
420 base::FilePath path
= temp_dir_
.path().Append(kCookieFilename
);
421 base::File::Info info
;
422 ASSERT_TRUE(base::GetFileInfo(path
, &info
));
423 int64 base_size
= info
.size
;
425 // Write some large cookies, so the DB will have to expand by several KB.
426 for (char c
= 'a'; c
< 'z'; ++c
) {
427 // Each cookie needs a unique timestamp for creation_utc (see DB schema).
428 base::Time t
= base::Time::Now() + base::TimeDelta::FromMicroseconds(c
);
429 std::string
name(1, c
);
430 std::string
value(1000, c
);
431 AddCookie(name
, value
, "foo.bar", "/", t
);
436 // We forced a write, so now the file will be bigger.
437 ASSERT_TRUE(base::GetFileInfo(path
, &info
));
438 ASSERT_GT(info
.size
, base_size
);
441 // Test loading old session cookies from the disk.
442 TEST_F(SQLitePersistentCookieStoreTest
, TestLoadOldSessionCookies
) {
443 InitializeStore(false, true);
445 // Add a session cookie.
446 store_
->AddCookie(CanonicalCookie(GURL(), "C", "D", "sessioncookie.com", "/",
447 base::Time::Now(), base::Time(),
448 base::Time::Now(), false, false, false,
449 COOKIE_PRIORITY_DEFAULT
));
451 // Force the store to write its data to the disk.
454 // Create a store that loads session cookies and test that the session cookie
456 CanonicalCookieVector cookies
;
457 CreateAndLoad(false, true, &cookies
);
459 ASSERT_EQ(1U, cookies
.size());
460 ASSERT_STREQ("sessioncookie.com", cookies
[0]->Domain().c_str());
461 ASSERT_STREQ("C", cookies
[0]->Name().c_str());
462 ASSERT_STREQ("D", cookies
[0]->Value().c_str());
463 ASSERT_EQ(COOKIE_PRIORITY_DEFAULT
, cookies
[0]->Priority());
465 STLDeleteElements(&cookies
);
468 // Test loading old session cookies from the disk.
469 TEST_F(SQLitePersistentCookieStoreTest
, TestDontLoadOldSessionCookies
) {
470 InitializeStore(false, true);
472 // Add a session cookie.
473 store_
->AddCookie(CanonicalCookie(GURL(), "C", "D", "sessioncookie.com", "/",
474 base::Time::Now(), base::Time(),
475 base::Time::Now(), false, false, false,
476 COOKIE_PRIORITY_DEFAULT
));
478 // Force the store to write its data to the disk.
481 // Create a store that doesn't load old session cookies and test that the
482 // session cookie was not loaded.
483 CanonicalCookieVector cookies
;
484 CreateAndLoad(false, false, &cookies
);
485 ASSERT_EQ(0U, cookies
.size());
487 // The store should also delete the session cookie. Wait until that has been
491 // Create a store that loads old session cookies and test that the session
493 CreateAndLoad(false, true, &cookies
);
494 ASSERT_EQ(0U, cookies
.size());
497 TEST_F(SQLitePersistentCookieStoreTest
, PersistIsPersistent
) {
498 InitializeStore(false, true);
499 static const char kSessionName
[] = "session";
500 static const char kPersistentName
[] = "persistent";
502 // Add a session cookie.
503 store_
->AddCookie(CanonicalCookie(GURL(), kSessionName
, "val",
504 "sessioncookie.com", "/", base::Time::Now(),
505 base::Time(), base::Time::Now(), false,
506 false, false, COOKIE_PRIORITY_DEFAULT
));
507 // Add a persistent cookie.
508 store_
->AddCookie(CanonicalCookie(
509 GURL(), kPersistentName
, "val", "sessioncookie.com", "/",
510 base::Time::Now() - base::TimeDelta::FromDays(1),
511 base::Time::Now() + base::TimeDelta::FromDays(1), base::Time::Now(),
512 false, false, false, COOKIE_PRIORITY_DEFAULT
));
514 // Force the store to write its data to the disk.
517 // Create a store that loads session cookie and test that the IsPersistent
518 // attribute is restored.
519 CanonicalCookieVector cookies
;
520 CreateAndLoad(false, true, &cookies
);
521 ASSERT_EQ(2U, cookies
.size());
523 std::map
<std::string
, CanonicalCookie
*> cookie_map
;
524 for (CanonicalCookieVector::const_iterator it
= cookies
.begin();
525 it
!= cookies
.end(); ++it
) {
526 cookie_map
[(*it
)->Name()] = *it
;
529 std::map
<std::string
, CanonicalCookie
*>::const_iterator it
=
530 cookie_map
.find(kSessionName
);
531 ASSERT_TRUE(it
!= cookie_map
.end());
532 EXPECT_FALSE(cookie_map
[kSessionName
]->IsPersistent());
534 it
= cookie_map
.find(kPersistentName
);
535 ASSERT_TRUE(it
!= cookie_map
.end());
536 EXPECT_TRUE(cookie_map
[kPersistentName
]->IsPersistent());
538 STLDeleteElements(&cookies
);
541 TEST_F(SQLitePersistentCookieStoreTest
, PriorityIsPersistent
) {
542 static const char kLowName
[] = "low";
543 static const char kMediumName
[] = "medium";
544 static const char kHighName
[] = "high";
545 static const char kCookieDomain
[] = "sessioncookie.com";
546 static const char kCookieValue
[] = "value";
547 static const char kCookiePath
[] = "/";
549 InitializeStore(false, true);
551 // Add a low-priority persistent cookie.
552 store_
->AddCookie(CanonicalCookie(
553 GURL(), kLowName
, kCookieValue
, kCookieDomain
, kCookiePath
,
554 base::Time::Now() - base::TimeDelta::FromMinutes(1),
555 base::Time::Now() + base::TimeDelta::FromDays(1), base::Time::Now(),
556 false, false, false, COOKIE_PRIORITY_LOW
));
558 // Add a medium-priority persistent cookie.
559 store_
->AddCookie(CanonicalCookie(
560 GURL(), kMediumName
, kCookieValue
, kCookieDomain
, kCookiePath
,
561 base::Time::Now() - base::TimeDelta::FromMinutes(2),
562 base::Time::Now() + base::TimeDelta::FromDays(1), base::Time::Now(),
563 false, false, false, COOKIE_PRIORITY_MEDIUM
));
565 // Add a high-priority peristent cookie.
566 store_
->AddCookie(CanonicalCookie(
567 GURL(), kHighName
, kCookieValue
, kCookieDomain
, kCookiePath
,
568 base::Time::Now() - base::TimeDelta::FromMinutes(3),
569 base::Time::Now() + base::TimeDelta::FromDays(1), base::Time::Now(),
570 false, false, false, COOKIE_PRIORITY_HIGH
));
572 // Force the store to write its data to the disk.
575 // Create a store that loads session cookie and test that the priority
576 // attribute values are restored.
577 CanonicalCookieVector cookies
;
578 CreateAndLoad(false, true, &cookies
);
579 ASSERT_EQ(3U, cookies
.size());
581 // Put the cookies into a map, by name, so we can easily find them.
582 std::map
<std::string
, CanonicalCookie
*> cookie_map
;
583 for (CanonicalCookieVector::const_iterator it
= cookies
.begin();
584 it
!= cookies
.end(); ++it
) {
585 cookie_map
[(*it
)->Name()] = *it
;
588 // Validate that each cookie has the correct priority.
589 std::map
<std::string
, CanonicalCookie
*>::const_iterator it
=
590 cookie_map
.find(kLowName
);
591 ASSERT_TRUE(it
!= cookie_map
.end());
592 EXPECT_EQ(COOKIE_PRIORITY_LOW
, cookie_map
[kLowName
]->Priority());
594 it
= cookie_map
.find(kMediumName
);
595 ASSERT_TRUE(it
!= cookie_map
.end());
596 EXPECT_EQ(COOKIE_PRIORITY_MEDIUM
, cookie_map
[kMediumName
]->Priority());
598 it
= cookie_map
.find(kHighName
);
599 ASSERT_TRUE(it
!= cookie_map
.end());
600 EXPECT_EQ(COOKIE_PRIORITY_HIGH
, cookie_map
[kHighName
]->Priority());
602 STLDeleteElements(&cookies
);
605 TEST_F(SQLitePersistentCookieStoreTest
, UpdateToEncryption
) {
606 CanonicalCookieVector cookies
;
608 // Create unencrypted cookie store and write something to it.
609 InitializeStore(false, false);
610 AddCookie("name", "value123XYZ", "foo.bar", "/", base::Time::Now());
613 // Verify that "value" is visible in the file. This is necessary in order to
614 // have confidence in a later test that "encrypted_value" is not visible.
615 std::string contents
= ReadRawDBContents();
616 EXPECT_NE(0U, contents
.length());
617 EXPECT_NE(contents
.find("value123XYZ"), std::string::npos
);
619 // Create encrypted cookie store and ensure old cookie still reads.
620 STLDeleteElements(&cookies_
);
621 EXPECT_EQ(0U, cookies_
.size());
622 CreateAndLoad(true, false, &cookies
);
623 EXPECT_EQ(1U, cookies_
.size());
624 EXPECT_EQ("name", cookies_
[0]->Name());
625 EXPECT_EQ("value123XYZ", cookies_
[0]->Value());
627 // Make sure we can update existing cookie and add new cookie as encrypted.
628 store_
->DeleteCookie(*(cookies_
[0]));
629 AddCookie("name", "encrypted_value123XYZ", "foo.bar", "/", base::Time::Now());
630 AddCookie("other", "something456ABC", "foo.bar", "/",
631 base::Time::Now() + base::TimeDelta::FromInternalValue(10));
633 STLDeleteElements(&cookies_
);
634 CreateAndLoad(true, false, &cookies
);
635 EXPECT_EQ(2U, cookies_
.size());
636 CanonicalCookie
* cookie_name
= nullptr;
637 CanonicalCookie
* cookie_other
= nullptr;
638 if (cookies_
[0]->Name() == "name") {
639 cookie_name
= cookies_
[0];
640 cookie_other
= cookies_
[1];
642 cookie_name
= cookies_
[1];
643 cookie_other
= cookies_
[0];
645 EXPECT_EQ("encrypted_value123XYZ", cookie_name
->Value());
646 EXPECT_EQ("something456ABC", cookie_other
->Value());
648 STLDeleteElements(&cookies_
);
650 // Examine the real record to make sure plaintext version doesn't exist.
654 ASSERT_TRUE(db
.Open(temp_dir_
.path().Append(kCookieFilename
)));
655 smt
.Assign(db
.GetCachedStatement(SQL_FROM_HERE
,
658 "WHERE host_key = 'foo.bar'"));
661 for (int i
= 0; i
< smt
.ColumnCount(); i
++) {
662 EXPECT_EQ(smt
.ColumnString(i
).find("value"), std::string::npos
);
663 EXPECT_EQ(smt
.ColumnString(i
).find("something"), std::string::npos
);
666 EXPECT_EQ(2, resultcount
);
668 // Verify that "encrypted_value" is NOT visible in the file.
669 contents
= ReadRawDBContents();
670 EXPECT_NE(0U, contents
.length());
671 EXPECT_EQ(contents
.find("encrypted_value123XYZ"), std::string::npos
);
672 EXPECT_EQ(contents
.find("something456ABC"), std::string::npos
);
675 TEST_F(SQLitePersistentCookieStoreTest
, UpdateFromEncryption
) {
676 CanonicalCookieVector cookies
;
678 // Create unencrypted cookie store and write something to it.
679 InitializeStore(true, false);
680 AddCookie("name", "value123XYZ", "foo.bar", "/", base::Time::Now());
683 // Verify that "value" is not visible in the file.
684 std::string contents
= ReadRawDBContents();
685 EXPECT_NE(0U, contents
.length());
686 EXPECT_EQ(contents
.find("value123XYZ"), std::string::npos
);
688 // Create encrypted cookie store and ensure old cookie still reads.
689 STLDeleteElements(&cookies_
);
690 EXPECT_EQ(0U, cookies_
.size());
691 CreateAndLoad(true, false, &cookies
);
692 EXPECT_EQ(1U, cookies_
.size());
693 EXPECT_EQ("name", cookies_
[0]->Name());
694 EXPECT_EQ("value123XYZ", cookies_
[0]->Value());
696 // Make sure we can update existing cookie and it writes unencrypted.
697 cookie_crypto_delegate_
->should_encrypt_
= false;
698 store_
->DeleteCookie(*(cookies_
[0]));
699 AddCookie("name", "plaintext_value123XYZ", "foo.bar", "/", base::Time::Now());
700 AddCookie("other", "something456ABC", "foo.bar", "/",
701 base::Time::Now() + base::TimeDelta::FromInternalValue(10));
703 STLDeleteElements(&cookies_
);
704 CreateAndLoad(true, false, &cookies
);
705 EXPECT_EQ(2U, cookies_
.size());
706 CanonicalCookie
* cookie_name
= nullptr;
707 CanonicalCookie
* cookie_other
= nullptr;
708 if (cookies_
[0]->Name() == "name") {
709 cookie_name
= cookies_
[0];
710 cookie_other
= cookies_
[1];
712 cookie_name
= cookies_
[1];
713 cookie_other
= cookies_
[0];
715 EXPECT_EQ("plaintext_value123XYZ", cookie_name
->Value());
716 EXPECT_EQ("something456ABC", cookie_other
->Value());
718 STLDeleteElements(&cookies_
);
720 // Verify that "value" is now visible in the file.
721 contents
= ReadRawDBContents();
722 EXPECT_NE(0U, contents
.length());
723 EXPECT_NE(contents
.find("value123XYZ"), std::string::npos
);
727 void WasCalledWithNoCookies(bool* was_called_with_no_cookies
,
728 const std::vector
<CanonicalCookie
*>& cookies
) {
729 *was_called_with_no_cookies
= cookies
.empty();
733 TEST_F(SQLitePersistentCookieStoreTest
, EmptyLoadAfterClose
) {
734 // Create unencrypted cookie store and write something to it.
735 InitializeStore(false, false);
736 AddCookie("name", "value123XYZ", "foo.bar", "/", base::Time::Now());
739 // Create the cookie store, but immediately close it.
740 Create(false, false);
741 store_
->Close(base::Closure());
743 // Expect any attempt to call Load() to synchronously respond with an empty
744 // vector of cookies after we've Close()d the database.
745 bool was_called_with_no_cookies
= false;
746 store_
->Load(base::Bind(WasCalledWithNoCookies
, &was_called_with_no_cookies
));
747 EXPECT_TRUE(was_called_with_no_cookies
);
749 // Same with trying to load a specific cookie.
750 was_called_with_no_cookies
= false;
751 store_
->LoadCookiesForKey("foo.bar", base::Bind(WasCalledWithNoCookies
,
752 &was_called_with_no_cookies
));
753 EXPECT_TRUE(was_called_with_no_cookies
);