• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/cookies/cookie_monster.h"
6 
7 #include <stdint.h>
8 
9 #include <algorithm>
10 #include <memory>
11 #include <string>
12 #include <utility>
13 #include <vector>
14 
15 #include "base/containers/queue.h"
16 #include "base/functional/bind.h"
17 #include "base/functional/callback.h"
18 #include "base/functional/callback_helpers.h"
19 #include "base/location.h"
20 #include "base/memory/raw_ptr.h"
21 #include "base/memory/ref_counted.h"
22 #include "base/metrics/histogram.h"
23 #include "base/metrics/histogram_samples.h"
24 #include "base/ranges/algorithm.h"
25 #include "base/run_loop.h"
26 #include "base/strings/strcat.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_tokenizer.h"
31 #include "base/strings/stringprintf.h"
32 #include "base/task/single_thread_task_runner.h"
33 #include "base/test/bind.h"
34 #include "base/test/metrics/histogram_tester.h"
35 #include "base/test/mock_callback.h"
36 #include "base/test/scoped_feature_list.h"
37 #include "base/test/test_future.h"
38 #include "base/threading/thread.h"
39 #include "base/time/time.h"
40 #include "net/base/features.h"
41 #include "net/cookies/canonical_cookie.h"
42 #include "net/cookies/canonical_cookie_test_helpers.h"
43 #include "net/cookies/cookie_change_dispatcher.h"
44 #include "net/cookies/cookie_constants.h"
45 #include "net/cookies/cookie_inclusion_status.h"
46 #include "net/cookies/cookie_monster_store_test.h"  // For CookieStore mock
47 #include "net/cookies/cookie_partition_key.h"
48 #include "net/cookies/cookie_store.h"
49 #include "net/cookies/cookie_store_change_unittest.h"
50 #include "net/cookies/cookie_store_test_callbacks.h"
51 #include "net/cookies/cookie_store_test_helpers.h"
52 #include "net/cookies/cookie_store_unittest.h"
53 #include "net/cookies/cookie_util.h"
54 #include "net/cookies/parsed_cookie.h"
55 #include "net/cookies/test_cookie_access_delegate.h"
56 #include "net/log/net_log_with_source.h"
57 #include "net/log/test_net_log.h"
58 #include "net/log/test_net_log_util.h"
59 #include "testing/gmock/include/gmock/gmock-matchers.h"
60 #include "testing/gmock/include/gmock/gmock.h"
61 #include "testing/gtest/include/gtest/gtest.h"
62 #include "third_party/abseil-cpp/absl/types/optional.h"
63 #include "url/gurl.h"
64 #include "url/third_party/mozilla/url_parse.h"
65 #include "url/url_constants.h"
66 
67 namespace net {
68 
69 using base::Time;
70 using CookieDeletionInfo = net::CookieDeletionInfo;
71 
72 namespace {
73 
74 using testing::ElementsAre;
75 
76 // False means 'less than or equal', so we test both ways for full equal.
77 MATCHER_P(CookieEquals, expected, "") {
78   return !(arg.FullCompare(expected) || expected.FullCompare(arg));
79 }
80 
81 MATCHER_P2(MatchesCookieNameDomain, name, domain, "") {
82   return testing::ExplainMatchResult(
83       testing::AllOf(testing::Property(&net::CanonicalCookie::Name, name),
84                      testing::Property(&net::CanonicalCookie::Domain, domain)),
85       arg, result_listener);
86 }
87 
88 MATCHER_P4(MatchesCookieNameValueCreationExpiry,
89            name,
90            value,
91            creation,
92            expiry,
93            "") {
94   return testing::ExplainMatchResult(
95       testing::AllOf(
96           testing::Property(&net::CanonicalCookie::Name, name),
97           testing::Property(&net::CanonicalCookie::Value, value),
98           testing::Property(&net::CanonicalCookie::CreationDate, creation),
99           // We need a margin of error when testing the ExpiryDate as, if
100           // clamped, it is set relative to the current time.
101           testing::Property(&net::CanonicalCookie::ExpiryDate,
102                             testing::Gt(expiry - base::Minutes(1))),
103           testing::Property(&net::CanonicalCookie::ExpiryDate,
104                             testing::Lt(expiry + base::Minutes(1)))),
105       arg, result_listener);
106 }
107 
108 const char kTopLevelDomainPlus1[] = "http://www.harvard.edu";
109 const char kTopLevelDomainPlus2[] = "http://www.math.harvard.edu";
110 const char kTopLevelDomainPlus2Secure[] = "https://www.math.harvard.edu";
111 const char kTopLevelDomainPlus3[] = "http://www.bourbaki.math.harvard.edu";
112 const char kOtherDomain[] = "http://www.mit.edu";
113 
114 struct CookieMonsterTestTraits {
Createnet::__anon76a117f60111::CookieMonsterTestTraits115   static std::unique_ptr<CookieStore> Create() {
116     return std::make_unique<CookieMonster>(nullptr /* store */,
117                                            nullptr /* netlog */);
118   }
119 
DeliverChangeNotificationsnet::__anon76a117f60111::CookieMonsterTestTraits120   static void DeliverChangeNotifications() { base::RunLoop().RunUntilIdle(); }
121 
122   static const bool supports_http_only = true;
123   static const bool supports_non_dotted_domains = true;
124   static const bool preserves_trailing_dots = true;
125   static const bool filters_schemes = true;
126   static const bool has_path_prefix_bug = false;
127   static const bool forbids_setting_empty_name = false;
128   static const bool supports_global_cookie_tracking = true;
129   static const bool supports_url_cookie_tracking = true;
130   static const bool supports_named_cookie_tracking = true;
131   static const bool supports_multiple_tracking_callbacks = true;
132   static const bool has_exact_change_cause = true;
133   static const bool has_exact_change_ordering = true;
134   static const int creation_time_granularity_in_ms = 0;
135   static const bool supports_cookie_access_semantics = true;
136   static const bool supports_partitioned_cookies = true;
137 };
138 
139 INSTANTIATE_TYPED_TEST_SUITE_P(CookieMonster,
140                                CookieStoreTest,
141                                CookieMonsterTestTraits);
142 INSTANTIATE_TYPED_TEST_SUITE_P(CookieMonster,
143                                CookieStoreChangeGlobalTest,
144                                CookieMonsterTestTraits);
145 INSTANTIATE_TYPED_TEST_SUITE_P(CookieMonster,
146                                CookieStoreChangeUrlTest,
147                                CookieMonsterTestTraits);
148 INSTANTIATE_TYPED_TEST_SUITE_P(CookieMonster,
149                                CookieStoreChangeNamedTest,
150                                CookieMonsterTestTraits);
151 
152 template <typename T>
153 class CookieMonsterTestBase : public CookieStoreTest<T> {
154  public:
155   using CookieStoreTest<T>::SetCookie;
156 
157  protected:
158   using CookieStoreTest<T>::http_www_foo_;
159   using CookieStoreTest<T>::https_www_foo_;
160 
GetAllCookiesForURLWithOptions(CookieMonster * cm,const GURL & url,const CookieOptions & options,const CookiePartitionKeyCollection & cookie_partition_key_collection=CookiePartitionKeyCollection ())161   CookieList GetAllCookiesForURLWithOptions(
162       CookieMonster* cm,
163       const GURL& url,
164       const CookieOptions& options,
165       const CookiePartitionKeyCollection& cookie_partition_key_collection =
166           CookiePartitionKeyCollection()) {
167     DCHECK(cm);
168     GetCookieListCallback callback;
169     cm->GetCookieListWithOptionsAsync(
170         url, options, cookie_partition_key_collection, callback.MakeCallback());
171     callback.WaitUntilDone();
172     return callback.cookies();
173   }
174 
GetExcludedCookiesForURLWithOptions(CookieMonster * cm,const GURL & url,const CookieOptions & options,const CookiePartitionKeyCollection & cookie_partition_key_collection=CookiePartitionKeyCollection ())175   CookieAccessResultList GetExcludedCookiesForURLWithOptions(
176       CookieMonster* cm,
177       const GURL& url,
178       const CookieOptions& options,
179       const CookiePartitionKeyCollection& cookie_partition_key_collection =
180           CookiePartitionKeyCollection()) {
181     DCHECK(cm);
182     GetCookieListCallback callback;
183     cm->GetCookieListWithOptionsAsync(
184         url, options, cookie_partition_key_collection, callback.MakeCallback());
185     callback.WaitUntilDone();
186     return callback.excluded_cookies();
187   }
188 
SetAllCookies(CookieMonster * cm,const CookieList & list)189   bool SetAllCookies(CookieMonster* cm, const CookieList& list) {
190     DCHECK(cm);
191     ResultSavingCookieCallback<CookieAccessResult> callback;
192     cm->SetAllCookiesAsync(list, callback.MakeCallback());
193     callback.WaitUntilDone();
194     return callback.result().status.IsInclude();
195   }
196 
SetCookieWithCreationTime(CookieMonster * cm,const GURL & url,const std::string & cookie_line,base::Time creation_time,absl::optional<CookiePartitionKey> cookie_partition_key=absl::nullopt)197   bool SetCookieWithCreationTime(
198       CookieMonster* cm,
199       const GURL& url,
200       const std::string& cookie_line,
201       base::Time creation_time,
202       absl::optional<CookiePartitionKey> cookie_partition_key = absl::nullopt) {
203     DCHECK(cm);
204     DCHECK(!creation_time.is_null());
205     ResultSavingCookieCallback<CookieAccessResult> callback;
206     cm->SetCanonicalCookieAsync(
207         CanonicalCookie::Create(url, cookie_line, creation_time,
208                                 absl::nullopt /* server_time */,
209                                 cookie_partition_key),
210         url, CookieOptions::MakeAllInclusive(), callback.MakeCallback());
211     callback.WaitUntilDone();
212     return callback.result().status.IsInclude();
213   }
214 
DeleteAllCreatedInTimeRange(CookieMonster * cm,const TimeRange & creation_range)215   uint32_t DeleteAllCreatedInTimeRange(CookieMonster* cm,
216                                        const TimeRange& creation_range) {
217     DCHECK(cm);
218     ResultSavingCookieCallback<uint32_t> callback;
219     cm->DeleteAllCreatedInTimeRangeAsync(creation_range,
220                                          callback.MakeCallback());
221     callback.WaitUntilDone();
222     return callback.result();
223   }
224 
DeleteAllMatchingInfo(CookieMonster * cm,CookieDeletionInfo delete_info)225   uint32_t DeleteAllMatchingInfo(CookieMonster* cm,
226                                  CookieDeletionInfo delete_info) {
227     DCHECK(cm);
228     ResultSavingCookieCallback<uint32_t> callback;
229     cm->DeleteAllMatchingInfoAsync(std::move(delete_info),
230                                    callback.MakeCallback());
231     callback.WaitUntilDone();
232     return callback.result();
233   }
234 
DeleteMatchingCookies(CookieMonster * cm,CookieStore::DeletePredicate predicate)235   uint32_t DeleteMatchingCookies(CookieMonster* cm,
236                                  CookieStore::DeletePredicate predicate) {
237     DCHECK(cm);
238     ResultSavingCookieCallback<uint32_t> callback;
239     cm->DeleteMatchingCookiesAsync(std::move(predicate),
240                                    callback.MakeCallback());
241     callback.WaitUntilDone();
242     return callback.result();
243   }
244 
245   // Helper for PredicateSeesAllCookies test; repopulates CM with same layout
246   // each time. Returns the time which is strictly greater than any creation
247   // time which was passed to created cookies.
PopulateCmForPredicateCheck(CookieMonster * cm)248   base::Time PopulateCmForPredicateCheck(CookieMonster* cm) {
249     std::string url_top_level_domain_plus_1(GURL(kTopLevelDomainPlus1).host());
250     std::string url_top_level_domain_plus_2(GURL(kTopLevelDomainPlus2).host());
251     std::string url_top_level_domain_plus_3(GURL(kTopLevelDomainPlus3).host());
252     std::string url_top_level_domain_secure(
253         GURL(kTopLevelDomainPlus2Secure).host());
254     std::string url_other(GURL(kOtherDomain).host());
255 
256     this->DeleteAll(cm);
257 
258     // Static population for probe:
259     //    * Three levels of domain cookie (.b.a, .c.b.a, .d.c.b.a)
260     //    * Three levels of host cookie (w.b.a, w.c.b.a, w.d.c.b.a)
261     //    * http_only cookie (w.c.b.a)
262     //    * same_site cookie (w.c.b.a)
263     //    * same_party cookie (w.c.b.a)
264     //    * Two secure cookies (.c.b.a, w.c.b.a)
265     //    * Two domain path cookies (.c.b.a/dir1, .c.b.a/dir1/dir2)
266     //    * Two host path cookies (w.c.b.a/dir1, w.c.b.a/dir1/dir2)
267 
268     std::vector<std::unique_ptr<CanonicalCookie>> cookies;
269     const base::Time now = base::Time::Now();
270 
271     // Domain cookies
272     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
273         "dom_1", "A", ".harvard.edu", "/", now, base::Time(), base::Time(),
274         base::Time(), false, false, CookieSameSite::LAX_MODE,
275         COOKIE_PRIORITY_DEFAULT, false));
276     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
277         "dom_2", "B", ".math.harvard.edu", "/", now, base::Time(), base::Time(),
278         base::Time(), false, false, CookieSameSite::LAX_MODE,
279         COOKIE_PRIORITY_DEFAULT, false));
280     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
281         "dom_3", "C", ".bourbaki.math.harvard.edu", "/", now, base::Time(),
282         base::Time(), base::Time(), false, false, CookieSameSite::LAX_MODE,
283         COOKIE_PRIORITY_DEFAULT, false));
284 
285     // Host cookies
286     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
287         "host_1", "A", url_top_level_domain_plus_1, "/", now, base::Time(),
288         base::Time(), base::Time(), false, false, CookieSameSite::LAX_MODE,
289         COOKIE_PRIORITY_DEFAULT, false));
290     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
291         "host_2", "B", url_top_level_domain_plus_2, "/", now, base::Time(),
292         base::Time(), base::Time(), false, false, CookieSameSite::LAX_MODE,
293         COOKIE_PRIORITY_DEFAULT, false));
294     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
295         "host_3", "C", url_top_level_domain_plus_3, "/", now, base::Time(),
296         base::Time(), base::Time(), false, false, CookieSameSite::LAX_MODE,
297         COOKIE_PRIORITY_DEFAULT, false));
298 
299     // http_only cookie
300     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
301         "httpo_check", "A", url_top_level_domain_plus_2, "/", now, base::Time(),
302         base::Time(), base::Time(), false, true, CookieSameSite::LAX_MODE,
303         COOKIE_PRIORITY_DEFAULT, false));
304 
305     // same-site cookie
306     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
307         "same_site_check", "A", url_top_level_domain_plus_2, "/", now,
308         base::Time(), base::Time(), base::Time(), false, false,
309         CookieSameSite::STRICT_MODE, COOKIE_PRIORITY_DEFAULT, false));
310 
311     // same-party cookie
312     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
313         "same_party_check", "A", url_top_level_domain_plus_2, "/", now,
314         base::Time(), base::Time(), base::Time(), true /* secure */, false,
315         CookieSameSite::LAX_MODE, COOKIE_PRIORITY_DEFAULT,
316         true /* same_party */));
317 
318     // Secure cookies
319     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
320         "sec_dom", "A", ".math.harvard.edu", "/", now, base::Time(),
321         base::Time(), base::Time(), true, false, CookieSameSite::NO_RESTRICTION,
322         COOKIE_PRIORITY_DEFAULT, false));
323     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
324         "sec_host", "B", url_top_level_domain_plus_2, "/", now, base::Time(),
325         base::Time(), base::Time(), true, false, CookieSameSite::NO_RESTRICTION,
326         COOKIE_PRIORITY_DEFAULT, false));
327 
328     // Domain path cookies
329     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
330         "dom_path_1", "A", ".math.harvard.edu", "/dir1", now, base::Time(),
331         base::Time(), base::Time(), false, false, CookieSameSite::LAX_MODE,
332         COOKIE_PRIORITY_DEFAULT, false));
333     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
334         "dom_path_2", "B", ".math.harvard.edu", "/dir1/dir2", now, base::Time(),
335         base::Time(), base::Time(), false, false, CookieSameSite::LAX_MODE,
336         COOKIE_PRIORITY_DEFAULT, false));
337 
338     // Host path cookies
339     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
340         "host_path_1", "A", url_top_level_domain_plus_2, "/dir1", now,
341         base::Time(), base::Time(), base::Time(), false, false,
342         CookieSameSite::LAX_MODE, COOKIE_PRIORITY_DEFAULT, false));
343     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
344         "host_path_2", "B", url_top_level_domain_plus_2, "/dir1/dir2", now,
345         base::Time(), base::Time(), base::Time(), false, false,
346         CookieSameSite::LAX_MODE, COOKIE_PRIORITY_DEFAULT, false));
347 
348     // Partitioned cookies
349     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
350         "__Host-pc_1", "A", url_top_level_domain_secure, "/", now, base::Time(),
351         base::Time(), base::Time(), true, false, CookieSameSite::NO_RESTRICTION,
352         CookiePriority::COOKIE_PRIORITY_DEFAULT, false,
353         CookiePartitionKey::FromURLForTesting(GURL(kTopLevelDomainPlus1))));
354     cookies.push_back(CanonicalCookie::CreateUnsafeCookieForTesting(
355         "__Host-pc_2", "B", url_top_level_domain_secure, "/", now, base::Time(),
356         base::Time(), base::Time(), true, false, CookieSameSite::NO_RESTRICTION,
357         CookiePriority::COOKIE_PRIORITY_DEFAULT, false,
358         CookiePartitionKey::FromURLForTesting(GURL(kTopLevelDomainPlus1))));
359 
360     for (auto& cookie : cookies) {
361       GURL source_url = cookie_util::SimulatedCookieSource(
362           *cookie, cookie->IsSecure() ? "https" : "http");
363       EXPECT_TRUE(this->SetCanonicalCookie(cm, std::move(cookie), source_url,
364                                            true /* modify_httponly */));
365     }
366 
367     EXPECT_EQ(cookies.size(), this->GetAllCookies(cm).size());
368     return now + base::Milliseconds(100);
369   }
370 
GetFirstCookieAccessDate(CookieMonster * cm)371   Time GetFirstCookieAccessDate(CookieMonster* cm) {
372     const CookieList all_cookies(this->GetAllCookies(cm));
373     return all_cookies.front().LastAccessDate();
374   }
375 
FindAndDeleteCookie(CookieMonster * cm,const std::string & domain,const std::string & name)376   bool FindAndDeleteCookie(CookieMonster* cm,
377                            const std::string& domain,
378                            const std::string& name) {
379     CookieList cookies = this->GetAllCookies(cm);
380     for (auto& cookie : cookies)
381       if (cookie.Domain() == domain && cookie.Name() == name)
382         return this->DeleteCanonicalCookie(cm, cookie);
383     return false;
384   }
385 
TestHostGarbageCollectHelper()386   void TestHostGarbageCollectHelper() {
387     int domain_max_cookies = CookieMonster::kDomainMaxCookies;
388     int domain_purge_cookies = CookieMonster::kDomainPurgeCookies;
389     const int more_than_enough_cookies = domain_max_cookies + 10;
390     // Add a bunch of cookies on a single host, should purge them.
391     {
392       auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
393       for (int i = 0; i < more_than_enough_cookies; ++i) {
394         std::string cookie = base::StringPrintf("a%03d=b", i);
395         EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), cookie));
396         std::string cookies = this->GetCookies(cm.get(), http_www_foo_.url());
397         // Make sure we find it in the cookies.
398         EXPECT_NE(cookies.find(cookie), std::string::npos);
399         // Count the number of cookies.
400         EXPECT_LE(base::ranges::count(cookies, '='), domain_max_cookies);
401       }
402     }
403 
404     // Add a bunch of cookies on multiple hosts within a single eTLD.
405     // Should keep at least kDomainMaxCookies - kDomainPurgeCookies
406     // between them.  We shouldn't go above kDomainMaxCookies for both together.
407     GURL url_google_specific(http_www_foo_.Format("http://www.gmail.%D"));
408     {
409       auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
410       for (int i = 0; i < more_than_enough_cookies; ++i) {
411         std::string cookie_general = base::StringPrintf("a%03d=b", i);
412         EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), cookie_general));
413         std::string cookie_specific = base::StringPrintf("c%03d=b", i);
414         EXPECT_TRUE(SetCookie(cm.get(), url_google_specific, cookie_specific));
415         std::string cookies_general =
416             this->GetCookies(cm.get(), http_www_foo_.url());
417         EXPECT_NE(cookies_general.find(cookie_general), std::string::npos);
418         std::string cookies_specific =
419             this->GetCookies(cm.get(), url_google_specific);
420         EXPECT_NE(cookies_specific.find(cookie_specific), std::string::npos);
421         EXPECT_LE((base::ranges::count(cookies_general, '=') +
422                    base::ranges::count(cookies_specific, '=')),
423                   domain_max_cookies);
424       }
425       // After all this, there should be at least
426       // kDomainMaxCookies - kDomainPurgeCookies for both URLs.
427       std::string cookies_general =
428           this->GetCookies(cm.get(), http_www_foo_.url());
429       std::string cookies_specific =
430           this->GetCookies(cm.get(), url_google_specific);
431       int total_cookies = (base::ranges::count(cookies_general, '=') +
432                            base::ranges::count(cookies_specific, '='));
433       EXPECT_GE(total_cookies, domain_max_cookies - domain_purge_cookies);
434       EXPECT_LE(total_cookies, domain_max_cookies);
435     }
436 
437     // Test histogram for the number of registrable domains affected by domain
438     // purge.
439     {
440       auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
441       GURL url;
442       for (int domain_num = 0; domain_num < 3; ++domain_num) {
443         url = GURL(base::StringPrintf("http://domain%d.test", domain_num));
444         for (int i = 0; i < more_than_enough_cookies; ++i) {
445           std::string cookie = base::StringPrintf("a%03d=b", i);
446           EXPECT_TRUE(SetCookie(cm.get(), url, cookie));
447           std::string cookies = this->GetCookies(cm.get(), url);
448           // Make sure we find it in the cookies.
449           EXPECT_NE(cookies.find(cookie), std::string::npos);
450           // Count the number of cookies.
451           EXPECT_LE(base::ranges::count(cookies, '='), domain_max_cookies);
452         }
453       }
454 
455       // Triggering eviction again for a previously affected registrable domain
456       // does not increment the histogram.
457       for (int i = 0; i < domain_purge_cookies * 2; ++i) {
458         // Add some extra cookies (different names than before).
459         std::string cookie = base::StringPrintf("b%03d=b", i);
460         EXPECT_TRUE(SetCookie(cm.get(), url, cookie));
461         std::string cookies = this->GetCookies(cm.get(), url);
462         // Make sure we find it in the cookies.
463         EXPECT_NE(cookies.find(cookie), std::string::npos);
464         // Count the number of cookies.
465         EXPECT_LE(base::ranges::count(cookies, '='), domain_max_cookies);
466       }
467     }
468   }
469 
CharToPriority(char ch)470   CookiePriority CharToPriority(char ch) {
471     switch (ch) {
472       case 'L':
473         return COOKIE_PRIORITY_LOW;
474       case 'M':
475         return COOKIE_PRIORITY_MEDIUM;
476       case 'H':
477         return COOKIE_PRIORITY_HIGH;
478     }
479     NOTREACHED();
480     return COOKIE_PRIORITY_DEFAULT;
481   }
482 
483   // Instantiates a CookieMonster, adds multiple cookies (to http_www_foo_)
484   // with priorities specified by |coded_priority_str|, and tests priority-aware
485   // domain cookie eviction.
486   //
487   // Example: |coded_priority_string| of "2MN 3LS MN 4HN" specifies sequential
488   // (i.e., from least- to most-recently accessed) insertion of 2
489   // medium-priority non-secure cookies, 3 low-priority secure cookies, 1
490   // medium-priority non-secure cookie, and 4 high-priority non-secure cookies.
491   //
492   // Within each priority, only the least-accessed cookies should be evicted.
493   // Thus, to describe expected suriving cookies, it suffices to specify the
494   // expected population of surviving cookies per priority, i.e.,
495   // |expected_low_count|, |expected_medium_count|, and |expected_high_count|.
TestPriorityCookieCase(CookieMonster * cm,const std::string & coded_priority_str,size_t expected_low_count,size_t expected_medium_count,size_t expected_high_count,size_t expected_nonsecure,size_t expected_secure)496   void TestPriorityCookieCase(CookieMonster* cm,
497                               const std::string& coded_priority_str,
498                               size_t expected_low_count,
499                               size_t expected_medium_count,
500                               size_t expected_high_count,
501                               size_t expected_nonsecure,
502                               size_t expected_secure) {
503     SCOPED_TRACE(coded_priority_str);
504     this->DeleteAll(cm);
505     int next_cookie_id = 0;
506     // A list of cookie IDs, indexed by secure status, then by priority.
507     std::vector<int> id_list[2][3];
508     // A list of all the cookies stored, along with their properties.
509     std::vector<std::pair<bool, CookiePriority>> cookie_data;
510 
511     // Parse |coded_priority_str| and add cookies.
512     for (const std::string& token :
513          base::SplitString(coded_priority_str, " ", base::TRIM_WHITESPACE,
514                            base::SPLIT_WANT_ALL)) {
515       DCHECK(!token.empty());
516 
517       bool is_secure = token.back() == 'S';
518 
519       // The second-to-last character is the priority. Grab and discard it.
520       CookiePriority priority = CharToPriority(token[token.size() - 2]);
521 
522       // Discard the security status and priority tokens. The rest of the string
523       // (possibly empty) specifies repetition.
524       int rep = 1;
525       if (!token.empty()) {
526         bool result = base::StringToInt(
527             base::MakeStringPiece(token.begin(), token.end() - 2), &rep);
528         DCHECK(result);
529       }
530       for (; rep > 0; --rep, ++next_cookie_id) {
531         std::string cookie =
532             base::StringPrintf("a%d=b;priority=%s;%s", next_cookie_id,
533                                CookiePriorityToString(priority).c_str(),
534                                is_secure ? "secure" : "");
535         EXPECT_TRUE(SetCookie(cm, https_www_foo_.url(), cookie));
536         cookie_data.emplace_back(is_secure, priority);
537         id_list[is_secure][priority].push_back(next_cookie_id);
538       }
539     }
540 
541     int num_cookies = static_cast<int>(cookie_data.size());
542     // A list of cookie IDs, indexed by secure status, then by priority.
543     std::vector<int> surviving_id_list[2][3];
544 
545     // Parse the list of cookies
546     std::string cookie_str = this->GetCookies(cm, https_www_foo_.url());
547     size_t num_nonsecure = 0;
548     size_t num_secure = 0;
549     for (const std::string& token : base::SplitString(
550              cookie_str, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
551       // Assuming *it is "a#=b", so extract and parse "#" portion.
552       int id = -1;
553       bool result = base::StringToInt(
554           base::MakeStringPiece(token.begin() + 1, token.end() - 2), &id);
555       DCHECK(result);
556       DCHECK_GE(id, 0);
557       DCHECK_LT(id, num_cookies);
558       surviving_id_list[cookie_data[id].first][cookie_data[id].second]
559           .push_back(id);
560       if (cookie_data[id].first)
561         num_secure += 1;
562       else
563         num_nonsecure += 1;
564     }
565 
566     EXPECT_EQ(expected_nonsecure, num_nonsecure);
567     EXPECT_EQ(expected_secure, num_secure);
568 
569     // Validate each priority.
570     size_t expected_count[3] = {expected_low_count, expected_medium_count,
571                                 expected_high_count};
572     for (int i = 0; i < 3; ++i) {
573       size_t num_for_priority =
574           surviving_id_list[0][i].size() + surviving_id_list[1][i].size();
575       EXPECT_EQ(expected_count[i], num_for_priority);
576       // Verify that the remaining cookies are the most recent among those
577       // with the same priorities.
578       if (expected_count[i] == num_for_priority) {
579         // Non-secure:
580         std::sort(surviving_id_list[0][i].begin(),
581                   surviving_id_list[0][i].end());
582         EXPECT_TRUE(std::equal(
583             surviving_id_list[0][i].begin(), surviving_id_list[0][i].end(),
584             id_list[0][i].end() - surviving_id_list[0][i].size()));
585 
586         // Secure:
587         std::sort(surviving_id_list[1][i].begin(),
588                   surviving_id_list[1][i].end());
589         EXPECT_TRUE(std::equal(
590             surviving_id_list[1][i].begin(), surviving_id_list[1][i].end(),
591             id_list[1][i].end() - surviving_id_list[1][i].size()));
592       }
593     }
594   }
595 
596   // Represents a number of cookies to create, if they are Secure cookies, and
597   // a url to add them to.
598   struct CookiesEntry {
599     size_t num_cookies;
600     bool is_secure;
601   };
602   // A number of secure and a number of non-secure alternative hosts to create
603   // for testing.
604   typedef std::pair<size_t, size_t> AltHosts;
605   // Takes an array of CookieEntries which specify the number, type, and order
606   // of cookies to create. Cookies are created in the order they appear in
607   // cookie_entries. The value of cookie_entries[x].num_cookies specifies how
608   // many cookies of that type to create consecutively, while if
609   // cookie_entries[x].is_secure is |true|, those cookies will be marked as
610   // Secure.
TestSecureCookieEviction(base::span<const CookiesEntry> cookie_entries,size_t expected_secure_cookies,size_t expected_non_secure_cookies,const AltHosts * alt_host_entries)611   void TestSecureCookieEviction(base::span<const CookiesEntry> cookie_entries,
612                                 size_t expected_secure_cookies,
613                                 size_t expected_non_secure_cookies,
614                                 const AltHosts* alt_host_entries) {
615     std::unique_ptr<CookieMonster> cm;
616 
617     if (alt_host_entries == nullptr) {
618       cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
619     } else {
620       // When generating all of these cookies on alternate hosts, they need to
621       // be all older than the max "safe" date for GC, which is currently 30
622       // days, so we set them to 60.
623       cm = CreateMonsterFromStoreForGC(
624           alt_host_entries->first, alt_host_entries->first,
625           alt_host_entries->second, alt_host_entries->second, 60);
626     }
627 
628     int next_cookie_id = 0;
629     for (const auto& cookie_entry : cookie_entries) {
630       for (size_t j = 0; j < cookie_entry.num_cookies; j++) {
631         std::string cookie;
632         if (cookie_entry.is_secure)
633           cookie = base::StringPrintf("a%d=b; Secure", next_cookie_id);
634         else
635           cookie = base::StringPrintf("a%d=b", next_cookie_id);
636         EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(), cookie));
637         ++next_cookie_id;
638       }
639     }
640 
641     CookieList cookies = this->GetAllCookies(cm.get());
642     EXPECT_EQ(expected_secure_cookies + expected_non_secure_cookies,
643               cookies.size());
644     size_t total_secure_cookies = 0;
645     size_t total_non_secure_cookies = 0;
646     for (const auto& cookie : cookies) {
647       if (cookie.IsSecure())
648         ++total_secure_cookies;
649       else
650         ++total_non_secure_cookies;
651     }
652 
653     EXPECT_EQ(expected_secure_cookies, total_secure_cookies);
654     EXPECT_EQ(expected_non_secure_cookies, total_non_secure_cookies);
655   }
656 
TestPriorityAwareGarbageCollectHelperNonSecure()657   void TestPriorityAwareGarbageCollectHelperNonSecure() {
658     // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint.
659     DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies);
660     DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies -
661                         CookieMonster::kDomainPurgeCookies);
662 
663     auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
664     // Key:
665     // Round 1 => LN; round 2 => LS; round 3 => MN.
666     // Round 4 => HN; round 5 => MS; round 6 => HS
667 
668     // Each test case adds 181 cookies, so 31 cookies are evicted.
669     // Cookie same priority, repeated for each priority.
670     TestPriorityCookieCase(cm.get(), "181LN", 150U, 0U, 0U, 150U, 0U);
671     TestPriorityCookieCase(cm.get(), "181MN", 0U, 150U, 0U, 150U, 0U);
672     TestPriorityCookieCase(cm.get(), "181HN", 0U, 0U, 150U, 150U, 0U);
673 
674     // Pairwise scenarios.
675     // Round 1 => none; round2 => 31M; round 3 => none.
676     TestPriorityCookieCase(cm.get(), "10HN 171MN", 0U, 140U, 10U, 150U, 0U);
677     // Round 1 => 10L; round2 => 21M; round 3 => none.
678     TestPriorityCookieCase(cm.get(), "141MN 40LN", 30U, 120U, 0U, 150U, 0U);
679     // Round 1 => none; round2 => 30M; round 3 => 1H.
680     TestPriorityCookieCase(cm.get(), "101HN 80MN", 0U, 50U, 100U, 150U, 0U);
681 
682     // For {low, medium} priorities right on quota, different orders.
683     // Round 1 => 1L; round 2 => none, round3 => 30H.
684     TestPriorityCookieCase(cm.get(), "31LN 50MN 100HN", 30U, 50U, 70U, 150U,
685                            0U);
686     // Round 1 => none; round 2 => 1M, round3 => 30H.
687     TestPriorityCookieCase(cm.get(), "51MN 100HN 30LN", 30U, 50U, 70U, 150U,
688                            0U);
689     // Round 1 => none; round 2 => none; round3 => 31H.
690     TestPriorityCookieCase(cm.get(), "101HN 50MN 30LN", 30U, 50U, 70U, 150U,
691                            0U);
692 
693     // Round 1 => 10L; round 2 => 10M; round3 => 11H.
694     TestPriorityCookieCase(cm.get(), "81HN 60MN 40LN", 30U, 50U, 70U, 150U, 0U);
695 
696     // More complex scenarios.
697     // Round 1 => 10L; round 2 => 10M; round 3 => 11H.
698     TestPriorityCookieCase(cm.get(), "21HN 60MN 40LN 60HN", 30U, 50U, 70U, 150U,
699                            0U);
700     // Round 1 => 10L; round 2 => 21M; round 3 => 0H.
701     TestPriorityCookieCase(cm.get(), "11HN 10MN 20LN 110MN 20LN 10HN", 30U, 99U,
702                            21U, 150U, 0U);
703     // Round 1 => none; round 2 => none; round 3 => 31H.
704     TestPriorityCookieCase(cm.get(), "11LN 10MN 140HN 10MN 10LN", 21U, 20U,
705                            109U, 150U, 0U);
706     // Round 1 => none; round 2 => 21M; round 3 => 10H.
707     TestPriorityCookieCase(cm.get(), "11MN 10HN 10LN 60MN 90HN", 10U, 50U, 90U,
708                            150U, 0U);
709     // Round 1 => none; round 2 => 31M; round 3 => none.
710     TestPriorityCookieCase(cm.get(), "11MN 10HN 10LN 90MN 60HN", 10U, 70U, 70U,
711                            150U, 0U);
712 
713     // Round 1 => 20L; round 2 => 0; round 3 => 11H
714     TestPriorityCookieCase(cm.get(), "50LN 131HN", 30U, 0U, 120U, 150U, 0U);
715     // Round 1 => 20L; round 2 => 0; round 3 => 11H
716     TestPriorityCookieCase(cm.get(), "131HN 50LN", 30U, 0U, 120U, 150U, 0U);
717     // Round 1 => 20L; round 2 => none; round 3 => 11H.
718     TestPriorityCookieCase(cm.get(), "50HN 50LN 81HN", 30U, 0U, 120U, 150U, 0U);
719     // Round 1 => 20L; round 2 => none; round 3 => 11H.
720     TestPriorityCookieCase(cm.get(), "81HN 50LN 50HN", 30U, 0U, 120U, 150U, 0U);
721   }
722 
TestPriorityAwareGarbageCollectHelperSecure()723   void TestPriorityAwareGarbageCollectHelperSecure() {
724     // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint.
725     DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies);
726     DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies -
727                         CookieMonster::kDomainPurgeCookies);
728 
729     auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
730     // Key:
731     // Round 1 => LN; round 2 => LS; round 3 => MN.
732     // Round 4 => HN; round 5 => MS; round 6 => HS
733 
734     // Each test case adds 181 cookies, so 31 cookies are evicted.
735     // Cookie same priority, repeated for each priority.
736     // Round 1 => 31L; round2 => none; round 3 => none.
737     TestPriorityCookieCase(cm.get(), "181LS", 150U, 0U, 0U, 0U, 150U);
738     // Round 1 => none; round2 => 31M; round 3 => none.
739     TestPriorityCookieCase(cm.get(), "181MS", 0U, 150U, 0U, 0U, 150U);
740     // Round 1 => none; round2 => none; round 3 => 31H.
741     TestPriorityCookieCase(cm.get(), "181HS", 0U, 0U, 150U, 0U, 150U);
742 
743     // Pairwise scenarios.
744     // Round 1 => none; round2 => 31M; round 3 => none.
745     TestPriorityCookieCase(cm.get(), "10HS 171MS", 0U, 140U, 10U, 0U, 150U);
746     // Round 1 => 10L; round2 => 21M; round 3 => none.
747     TestPriorityCookieCase(cm.get(), "141MS 40LS", 30U, 120U, 0U, 0U, 150U);
748     // Round 1 => none; round2 => 30M; round 3 => 1H.
749     TestPriorityCookieCase(cm.get(), "101HS 80MS", 0U, 50U, 100U, 0U, 150U);
750 
751     // For {low, medium} priorities right on quota, different orders.
752     // Round 1 => 1L; round 2 => none, round3 => 30H.
753     TestPriorityCookieCase(cm.get(), "31LS 50MS 100HS", 30U, 50U, 70U, 0U,
754                            150U);
755     // Round 1 => none; round 2 => 1M, round3 => 30H.
756     TestPriorityCookieCase(cm.get(), "51MS 100HS 30LS", 30U, 50U, 70U, 0U,
757                            150U);
758     // Round 1 => none; round 2 => none; round3 => 31H.
759     TestPriorityCookieCase(cm.get(), "101HS 50MS 30LS", 30U, 50U, 70U, 0U,
760                            150U);
761 
762     // Round 1 => 10L; round 2 => 10M; round3 => 11H.
763     TestPriorityCookieCase(cm.get(), "81HS 60MS 40LS", 30U, 50U, 70U, 0U, 150U);
764 
765     // More complex scenarios.
766     // Round 1 => 10L; round 2 => 10M; round 3 => 11H.
767     TestPriorityCookieCase(cm.get(), "21HS 60MS 40LS 60HS", 30U, 50U, 70U, 0U,
768                            150U);
769     // Round 1 => 10L; round 2 => 21M; round 3 => none.
770     TestPriorityCookieCase(cm.get(), "11HS 10MS 20LS 110MS 20LS 10HS", 30U, 99U,
771                            21U, 0U, 150U);
772     // Round 1 => none; round 2 => none; round 3 => 31H.
773     TestPriorityCookieCase(cm.get(), "11LS 10MS 140HS 10MS 10LS", 21U, 20U,
774                            109U, 0U, 150U);
775     // Round 1 => none; round 2 => 21M; round 3 => 10H.
776     TestPriorityCookieCase(cm.get(), "11MS 10HS 10LS 60MS 90HS", 10U, 50U, 90U,
777                            0U, 150U);
778     // Round 1 => none; round 2 => 31M; round 3 => none.
779     TestPriorityCookieCase(cm.get(), "11MS 10HS 10LS 90MS 60HS", 10U, 70U, 70U,
780                            0U, 150U);
781   }
782 
TestPriorityAwareGarbageCollectHelperMixed()783   void TestPriorityAwareGarbageCollectHelperMixed() {
784     // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint.
785     DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies);
786     DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies -
787                         CookieMonster::kDomainPurgeCookies);
788 
789     auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
790     // Key:
791     // Round 1 => LN; round 2 => LS; round 3 => MN.
792     // Round 4 => HN; round 5 => MS; round 6 => HS
793 
794     // Each test case adds 180 secure cookies, and some non-secure cookie. The
795     // secure cookies take priority, so the non-secure cookie is removed, along
796     // with 30 secure cookies. Repeated for each priority, and with the
797     // non-secure cookie as older and newer.
798     // Round 1 => 1LN; round 2 => 30LS; round 3 => none.
799     // Round 4 => none; round 5 => none; round 6 => none.
800     TestPriorityCookieCase(cm.get(), "1LN 180LS", 150U, 0U, 0U, 0U, 150U);
801     // Round 1 => none; round 2 => none; round 3 => 1MN.
802     // Round 4 => none; round 5 => 30MS; round 6 => none.
803     TestPriorityCookieCase(cm.get(), "1MN 180MS", 0U, 150U, 0U, 0U, 150U);
804     // Round 1 => none; round 2 => none; round 3 => none.
805     // Round 4 => 1HN; round 5 => none; round 6 => 30HS.
806     TestPriorityCookieCase(cm.get(), "1HN 180HS", 0U, 0U, 150U, 0U, 150U);
807     // Round 1 => 1LN; round 2 => 30LS; round 3 => none.
808     // Round 4 => none; round 5 => none; round 6 => none.
809     TestPriorityCookieCase(cm.get(), "180LS 1LN", 150U, 0U, 0U, 0U, 150U);
810     // Round 1 => none; round 2 => none; round 3 => 1MN.
811     // Round 4 => none; round 5 => 30MS; round 6 => none.
812     TestPriorityCookieCase(cm.get(), "180MS 1MN", 0U, 150U, 0U, 0U, 150U);
813     // Round 1 => none; round 2 => none; round 3 => none.
814     // Round 4 => 1HN; round 5 => none; round 6 => 30HS.
815     TestPriorityCookieCase(cm.get(), "180HS 1HN", 0U, 0U, 150U, 0U, 150U);
816 
817     // Quotas should be correctly maintained when a given priority has both
818     // secure and non-secure cookies.
819     //
820     // Round 1 => 10LN; round 2 => none; round 3 => none.
821     // Round 4 => 21HN; round 5 => none; round 6 => none.
822     TestPriorityCookieCase(cm.get(), "39LN 1LS 141HN", 30U, 0U, 120U, 149U, 1U);
823     // Round 1 => none; round 2 => none; round 3 => 10MN.
824     // Round 4 => none; round 5 => none; round 6 => 21HS.
825     TestPriorityCookieCase(cm.get(), "29LN 1LS 59MN 1MS 91HS", 30U, 50U, 70U,
826                            78U, 72U);
827 
828     // Low-priority secure cookies are removed before higher priority non-secure
829     // cookies.
830     // Round 1 => none; round 2 => 31LS; round 3 => none.
831     // Round 4 => none; round 5 => none; round 6 => none.
832     TestPriorityCookieCase(cm.get(), "180LS 1MN", 149U, 1U, 0U, 1U, 149U);
833     // Round 1 => none; round 2 => 31LS; round 3 => none.
834     // Round 4 => none; round 5 => none; round 6 => none.
835     TestPriorityCookieCase(cm.get(), "180LS 1HN", 149U, 0U, 1U, 1U, 149U);
836     // Round 1 => none; round 2 => 31LS; round 3 => none.
837     // Round 4 => none; round 5 => none; round 6 => none.
838     TestPriorityCookieCase(cm.get(), "1MN 180LS", 149U, 1U, 0U, 1U, 149U);
839     // Round 1 => none; round 2 => 31LS; round 3 => none.
840     // Round 4 => none; round 5 => none; round 6 => none.
841     TestPriorityCookieCase(cm.get(), "1HN 180LS", 149U, 0U, 1U, 1U, 149U);
842 
843     // Higher-priority non-secure cookies are removed before any secure cookie
844     // with greater than low-priority. Is it true? How about the quota?
845     // Round 1 => none; round 2 => none; round 3 => none.
846     // Round 4 => none; round 5 => 31MS; round 6 => none.
847     TestPriorityCookieCase(cm.get(), "180MS 1HN", 0U, 149U, 1U, 1U, 149U);
848     // Round 1 => none; round 2 => none; round 3 => none.
849     // Round 4 => none; round 5 => 31MS; round 6 => none.
850     TestPriorityCookieCase(cm.get(), "1HN 180MS", 0U, 149U, 1U, 1U, 149U);
851 
852     // Pairwise:
853     // Round 1 => 31LN; round 2 => none; round 3 => none.
854     // Round 4 => none; round 5 => none; round 6 => none.
855     TestPriorityCookieCase(cm.get(), "1LS 180LN", 150U, 0U, 0U, 149U, 1U);
856     // Round 1 => 31LN; round 2 => none; round 3 => none.
857     // Round 4 => none; round 5 => none; round 6 => none.
858     TestPriorityCookieCase(cm.get(), "100LS 81LN", 150U, 0U, 0U, 50U, 100U);
859     // Round 1 => 31LN; round 2 => none; round 3 => none.
860     // Round 4 => none; round 5 => none; round 6 => none.
861     TestPriorityCookieCase(cm.get(), "150LS 31LN", 150U, 0U, 0U, 0U, 150U);
862     // Round 1 => none; round 2 => none; round 3 => none.
863     // Round 4 => 31HN; round 5 => none; round 6 => none.
864     TestPriorityCookieCase(cm.get(), "1LS 180HN", 1U, 0U, 149U, 149U, 1U);
865     // Round 1 => none; round 2 => 31LS; round 3 => none.
866     // Round 4 => none; round 5 => none; round 6 => none.
867     TestPriorityCookieCase(cm.get(), "100LS 81HN", 69U, 0U, 81U, 81U, 69U);
868     // Round 1 => none; round 2 => 31LS; round 3 => none.
869     // Round 4 => none; round 5 => none; round 6 => none.
870     TestPriorityCookieCase(cm.get(), "150LS 31HN", 119U, 0U, 31U, 31U, 119U);
871 
872     // Quota calculations inside non-secure/secure blocks remain in place:
873     // Round 1 => none; round 2 => 20LS; round 3 => none.
874     // Round 4 => 11HN; round 5 => none; round 6 => none.
875     TestPriorityCookieCase(cm.get(), "50HN 50LS 81HS", 30U, 0U, 120U, 39U,
876                            111U);
877     // Round 1 => none; round 2 => none; round 3 => 31MN.
878     // Round 4 => none; round 5 => none; round 6 => none.
879     TestPriorityCookieCase(cm.get(), "11MS 10HN 10LS 90MN 60HN", 10U, 70U, 70U,
880                            129U, 21U);
881     // Round 1 => 31LN; round 2 => none; round 3 => none.
882     // Round 4 => none; round 5 => none; round 6 => none.
883     TestPriorityCookieCase(cm.get(), "40LS 40LN 101HS", 49U, 0U, 101U, 9U,
884                            141U);
885 
886     // Multiple GC rounds end up with consistent behavior:
887     // GC is started as soon as there are 181 cookies in the store.
888     // On each major round it tries to preserve the quota for each priority.
889     // It is not aware about more cookies going in.
890     // 1 GC notices there are 181 cookies - 100HS 81LN 0MN
891     // Round 1 => 31LN; round 2 => none; round 3 => none.
892     // Round 4 => none; round 5 => none; round 6 => none.
893     // 2 GC notices there are 181 cookies - 100HS 69LN 12MN
894     // Round 1 => 31LN; round 2 => none; round 3 => none.
895     // Round 4 => none; round 5 => none; round 6 => none.
896     // 3 GC notices there are 181 cookies - 100HS 38LN 43MN
897     // Round 1 =>  8LN; round 2 => none; round 3 => none.
898     // Round 4 => none; round 5 => none; round 6 => 23HS.
899     // 4 GC notcies there are 181 cookies - 77HS 30LN 74MN
900     // Round 1 => none; round 2 => none; round 3 => 24MN.
901     // Round 4 => none; round 5 => none; round 6 =>  7HS.
902     TestPriorityCookieCase(cm.get(), "100HS 100LN 100MN", 30U, 76U, 70U, 106U,
903                            70U);
904   }
905 
906   // Function for creating a CM with a number of cookies in it,
907   // no store (and hence no ability to affect access time).
CreateMonsterForGC(int num_cookies)908   std::unique_ptr<CookieMonster> CreateMonsterForGC(int num_cookies) {
909     auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
910     base::Time creation_time = base::Time::Now();
911     for (int i = 0; i < num_cookies; i++) {
912       std::unique_ptr<CanonicalCookie> cc(
913           CanonicalCookie::CreateUnsafeCookieForTesting(
914               "a", "1", base::StringPrintf("h%05d.izzle", i), /*path=*/"/",
915               creation_time, /*=expiration_time=*/base::Time(),
916               /*last_access=*/creation_time, /*last_update=*/creation_time,
917               /*secure=*/true,
918               /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
919               COOKIE_PRIORITY_DEFAULT, false /* same_party */));
920       GURL source_url = cookie_util::SimulatedCookieSource(*cc, "https");
921       cm->SetCanonicalCookieAsync(std::move(cc), source_url,
922                                   CookieOptions::MakeAllInclusive(),
923                                   CookieStore::SetCookiesCallback());
924     }
925     return cm;
926   }
927 
IsCookieInList(const CanonicalCookie & cookie,const CookieList & list)928   bool IsCookieInList(const CanonicalCookie& cookie, const CookieList& list) {
929     for (const auto& c : list) {
930       if (c.Name() == cookie.Name() && c.Value() == cookie.Value() &&
931           c.Domain() == cookie.Domain() && c.Path() == cookie.Path() &&
932           c.CreationDate() == cookie.CreationDate() &&
933           c.ExpiryDate() == cookie.ExpiryDate() &&
934           c.LastAccessDate() == cookie.LastAccessDate() &&
935           c.LastUpdateDate() == cookie.LastUpdateDate() &&
936           c.IsSecure() == cookie.IsSecure() &&
937           c.IsHttpOnly() == cookie.IsHttpOnly() &&
938           c.Priority() == cookie.Priority()) {
939         return true;
940       }
941     }
942 
943     return false;
944   }
945   RecordingNetLogObserver net_log_;
946 };
947 
948 using CookieMonsterTest = CookieMonsterTestBase<CookieMonsterTestTraits>;
949 
950 struct CookiesInputInfo {
951   const GURL url;
952   const std::string name;
953   const std::string value;
954   const std::string domain;
955   const std::string path;
956   const base::Time expiration_time;
957   bool secure;
958   bool http_only;
959   CookieSameSite same_site;
960   CookiePriority priority;
961   bool same_party;
962 };
963 
964 }  // namespace
965 
966 // This test suite verifies the task deferral behaviour of the CookieMonster.
967 // Specifically, for each asynchronous method, verify that:
968 // 1. invoking it on an uninitialized cookie store causes the store to begin
969 //    chain-loading its backing data or loading data for a specific domain key
970 //    (eTLD+1).
971 // 2. The initial invocation does not complete until the loading completes.
972 // 3. Invocations after the loading has completed complete immediately.
973 class DeferredCookieTaskTest : public CookieMonsterTest {
974  protected:
DeferredCookieTaskTest()975   DeferredCookieTaskTest() {
976     persistent_store_ = base::MakeRefCounted<MockPersistentCookieStore>();
977     persistent_store_->set_store_load_commands(true);
978     cookie_monster_ = std::make_unique<CookieMonster>(persistent_store_.get(),
979                                                       net::NetLog::Get());
980   }
981 
982   // Defines a cookie to be returned from PersistentCookieStore::Load
DeclareLoadedCookie(const GURL & url,const std::string & cookie_line,const base::Time & creation_time)983   void DeclareLoadedCookie(const GURL& url,
984                            const std::string& cookie_line,
985                            const base::Time& creation_time) {
986     AddCookieToList(url, cookie_line, creation_time, &loaded_cookies_);
987   }
988 
ExecuteLoads(CookieStoreCommand::Type type)989   void ExecuteLoads(CookieStoreCommand::Type type) {
990     const auto& commands = persistent_store_->commands();
991     for (size_t i = 0; i < commands.size(); ++i) {
992       // Only the first load command will produce the cookies.
993       if (commands[i].type == type) {
994         persistent_store_->TakeCallbackAt(i).Run(std::move(loaded_cookies_));
995       }
996     }
997   }
998 
CommandSummary(const MockPersistentCookieStore::CommandList & commands)999   std::string CommandSummary(
1000       const MockPersistentCookieStore::CommandList& commands) {
1001     std::string out;
1002     for (const auto& command : commands) {
1003       switch (command.type) {
1004         case CookieStoreCommand::LOAD:
1005           base::StrAppend(&out, {"LOAD; "});
1006           break;
1007         case CookieStoreCommand::LOAD_COOKIES_FOR_KEY:
1008           base::StrAppend(&out, {"LOAD_FOR_KEY:", command.key, "; "});
1009           break;
1010         case CookieStoreCommand::ADD:
1011           base::StrAppend(&out, {"ADD; "});
1012           break;
1013         case CookieStoreCommand::REMOVE:
1014           base::StrAppend(&out, {"REMOVE; "});
1015           break;
1016       }
1017     }
1018     return out;
1019   }
1020 
TakeCommandSummary()1021   std::string TakeCommandSummary() {
1022     return CommandSummary(persistent_store_->TakeCommands());
1023   }
1024 
1025   // Holds cookies to be returned from PersistentCookieStore::Load or
1026   // PersistentCookieStore::LoadCookiesForKey.
1027   std::vector<std::unique_ptr<CanonicalCookie>> loaded_cookies_;
1028 
1029   std::unique_ptr<CookieMonster> cookie_monster_;
1030   scoped_refptr<MockPersistentCookieStore> persistent_store_;
1031 };
1032 
TEST_F(DeferredCookieTaskTest,DeferredGetCookieList)1033 TEST_F(DeferredCookieTaskTest, DeferredGetCookieList) {
1034   DeclareLoadedCookie(http_www_foo_.url(),
1035                       "X=1; path=/" + FutureCookieExpirationString(),
1036                       Time::Now() + base::Days(3));
1037 
1038   GetCookieListCallback call1;
1039   cookie_monster_->GetCookieListWithOptionsAsync(
1040       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1041       CookiePartitionKeyCollection(), call1.MakeCallback());
1042   base::RunLoop().RunUntilIdle();
1043   EXPECT_FALSE(call1.was_run());
1044 
1045   // Finish the per-key load, not everything-load (which is always initiated).
1046   ExecuteLoads(CookieStoreCommand::LOAD_COOKIES_FOR_KEY);
1047   call1.WaitUntilDone();
1048   EXPECT_THAT(call1.cookies(), MatchesCookieLine("X=1"));
1049   EXPECT_EQ("LOAD; LOAD_FOR_KEY:foo.com; ", TakeCommandSummary());
1050 
1051   GetCookieListCallback call2;
1052   cookie_monster_->GetCookieListWithOptionsAsync(
1053       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1054       CookiePartitionKeyCollection(), call2.MakeCallback());
1055   // Already ready, no need for second load.
1056   EXPECT_THAT(call2.cookies(), MatchesCookieLine("X=1"));
1057   EXPECT_EQ("", TakeCommandSummary());
1058 }
1059 
TEST_F(DeferredCookieTaskTest,DeferredSetCookie)1060 TEST_F(DeferredCookieTaskTest, DeferredSetCookie) {
1061   // Generate puts to store w/o needing a proper expiration.
1062   cookie_monster_->SetPersistSessionCookies(true);
1063 
1064   ResultSavingCookieCallback<CookieAccessResult> call1;
1065   cookie_monster_->SetCanonicalCookieAsync(
1066       CanonicalCookie::Create(http_www_foo_.url(), "A=B", base::Time::Now(),
1067                               absl::nullopt /* server_time */,
1068                               absl::nullopt /* cookie_partition_key */),
1069       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1070       call1.MakeCallback());
1071   base::RunLoop().RunUntilIdle();
1072   EXPECT_FALSE(call1.was_run());
1073 
1074   ExecuteLoads(CookieStoreCommand::LOAD_COOKIES_FOR_KEY);
1075   call1.WaitUntilDone();
1076   EXPECT_TRUE(call1.result().status.IsInclude());
1077   EXPECT_EQ("LOAD; LOAD_FOR_KEY:foo.com; ADD; ", TakeCommandSummary());
1078 
1079   ResultSavingCookieCallback<CookieAccessResult> call2;
1080   cookie_monster_->SetCanonicalCookieAsync(
1081       CanonicalCookie::Create(http_www_foo_.url(), "X=Y", base::Time::Now(),
1082                               absl::nullopt /* server_time */,
1083                               absl::nullopt /* cookie_partition_key */),
1084       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1085       call2.MakeCallback());
1086   ASSERT_TRUE(call2.was_run());
1087   EXPECT_TRUE(call2.result().status.IsInclude());
1088   EXPECT_EQ("ADD; ", TakeCommandSummary());
1089 }
1090 
TEST_F(DeferredCookieTaskTest,DeferredSetAllCookies)1091 TEST_F(DeferredCookieTaskTest, DeferredSetAllCookies) {
1092   // Generate puts to store w/o needing a proper expiration.
1093   cookie_monster_->SetPersistSessionCookies(true);
1094 
1095   CookieList list;
1096   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
1097       "A", "B", "." + http_www_foo_.domain(), "/", base::Time::Now(),
1098       base::Time(), base::Time(), base::Time(), false, true,
1099       CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false));
1100   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
1101       "C", "D", "." + http_www_foo_.domain(), "/", base::Time::Now(),
1102       base::Time(), base::Time(), base::Time(), false, true,
1103       CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false));
1104 
1105   ResultSavingCookieCallback<CookieAccessResult> call1;
1106   cookie_monster_->SetAllCookiesAsync(list, call1.MakeCallback());
1107   base::RunLoop().RunUntilIdle();
1108   EXPECT_FALSE(call1.was_run());
1109 
1110   ExecuteLoads(CookieStoreCommand::LOAD);
1111   call1.WaitUntilDone();
1112   EXPECT_TRUE(call1.result().status.IsInclude());
1113   EXPECT_EQ("LOAD; ADD; ADD; ", TakeCommandSummary());
1114 
1115   // 2nd set doesn't need to read from store. It erases the old cookies, though.
1116   ResultSavingCookieCallback<CookieAccessResult> call2;
1117   cookie_monster_->SetAllCookiesAsync(list, call2.MakeCallback());
1118   ASSERT_TRUE(call2.was_run());
1119   EXPECT_TRUE(call2.result().status.IsInclude());
1120   EXPECT_EQ("REMOVE; REMOVE; ADD; ADD; ", TakeCommandSummary());
1121 }
1122 
TEST_F(DeferredCookieTaskTest,DeferredGetAllCookies)1123 TEST_F(DeferredCookieTaskTest, DeferredGetAllCookies) {
1124   DeclareLoadedCookie(http_www_foo_.url(),
1125                       "X=1; path=/" + FutureCookieExpirationString(),
1126                       Time::Now() + base::Days(3));
1127 
1128   GetAllCookiesCallback call1;
1129   cookie_monster_->GetAllCookiesAsync(call1.MakeCallback());
1130   base::RunLoop().RunUntilIdle();
1131   EXPECT_FALSE(call1.was_run());
1132 
1133   ExecuteLoads(CookieStoreCommand::LOAD);
1134   call1.WaitUntilDone();
1135   EXPECT_THAT(call1.cookies(), MatchesCookieLine("X=1"));
1136   EXPECT_EQ("LOAD; ", TakeCommandSummary());
1137 
1138   GetAllCookiesCallback call2;
1139   cookie_monster_->GetAllCookiesAsync(call2.MakeCallback());
1140   EXPECT_TRUE(call2.was_run());
1141   EXPECT_THAT(call2.cookies(), MatchesCookieLine("X=1"));
1142   EXPECT_EQ("", TakeCommandSummary());
1143 }
1144 
TEST_F(DeferredCookieTaskTest,DeferredGetAllForUrlCookies)1145 TEST_F(DeferredCookieTaskTest, DeferredGetAllForUrlCookies) {
1146   DeclareLoadedCookie(http_www_foo_.url(),
1147                       "X=1; path=/" + FutureCookieExpirationString(),
1148                       Time::Now() + base::Days(3));
1149 
1150   GetCookieListCallback call1;
1151   cookie_monster_->GetCookieListWithOptionsAsync(
1152       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1153       CookiePartitionKeyCollection(), call1.MakeCallback());
1154   base::RunLoop().RunUntilIdle();
1155   EXPECT_FALSE(call1.was_run());
1156 
1157   ExecuteLoads(CookieStoreCommand::LOAD_COOKIES_FOR_KEY);
1158   call1.WaitUntilDone();
1159   EXPECT_THAT(call1.cookies(), MatchesCookieLine("X=1"));
1160   EXPECT_EQ("LOAD; LOAD_FOR_KEY:foo.com; ", TakeCommandSummary());
1161 
1162   GetCookieListCallback call2;
1163   cookie_monster_->GetCookieListWithOptionsAsync(
1164       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1165       CookiePartitionKeyCollection(), call2.MakeCallback());
1166   EXPECT_TRUE(call2.was_run());
1167   EXPECT_THAT(call2.cookies(), MatchesCookieLine("X=1"));
1168   EXPECT_EQ("", TakeCommandSummary());
1169 }
1170 
TEST_F(DeferredCookieTaskTest,DeferredGetAllForUrlWithOptionsCookies)1171 TEST_F(DeferredCookieTaskTest, DeferredGetAllForUrlWithOptionsCookies) {
1172   DeclareLoadedCookie(http_www_foo_.url(),
1173                       "X=1; path=/" + FutureCookieExpirationString(),
1174                       Time::Now() + base::Days(3));
1175 
1176   GetCookieListCallback call1;
1177   cookie_monster_->GetCookieListWithOptionsAsync(
1178       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1179       CookiePartitionKeyCollection(), call1.MakeCallback());
1180   base::RunLoop().RunUntilIdle();
1181   EXPECT_FALSE(call1.was_run());
1182 
1183   ExecuteLoads(CookieStoreCommand::LOAD_COOKIES_FOR_KEY);
1184   call1.WaitUntilDone();
1185   EXPECT_THAT(call1.cookies(), MatchesCookieLine("X=1"));
1186   EXPECT_EQ("LOAD; LOAD_FOR_KEY:foo.com; ", TakeCommandSummary());
1187 
1188   GetCookieListCallback call2;
1189   cookie_monster_->GetCookieListWithOptionsAsync(
1190       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1191       CookiePartitionKeyCollection(), call2.MakeCallback());
1192   EXPECT_TRUE(call2.was_run());
1193   EXPECT_THAT(call2.cookies(), MatchesCookieLine("X=1"));
1194   EXPECT_EQ("", TakeCommandSummary());
1195 }
1196 
TEST_F(DeferredCookieTaskTest,DeferredDeleteAllCookies)1197 TEST_F(DeferredCookieTaskTest, DeferredDeleteAllCookies) {
1198   DeclareLoadedCookie(http_www_foo_.url(),
1199                       "X=1; path=/" + FutureCookieExpirationString(),
1200                       Time::Now() + base::Days(3));
1201 
1202   ResultSavingCookieCallback<uint32_t> call1;
1203   cookie_monster_->DeleteAllAsync(call1.MakeCallback());
1204   base::RunLoop().RunUntilIdle();
1205   EXPECT_FALSE(call1.was_run());
1206 
1207   ExecuteLoads(CookieStoreCommand::LOAD);
1208   call1.WaitUntilDone();
1209   EXPECT_EQ(1u, call1.result());
1210   EXPECT_EQ("LOAD; REMOVE; ", TakeCommandSummary());
1211 
1212   ResultSavingCookieCallback<uint32_t> call2;
1213   cookie_monster_->DeleteAllAsync(call2.MakeCallback());
1214   // This needs an event loop spin since DeleteAllAsync always reports
1215   // asynchronously.
1216   call2.WaitUntilDone();
1217   EXPECT_EQ(0u, call2.result());
1218   EXPECT_EQ("", TakeCommandSummary());
1219 }
1220 
TEST_F(DeferredCookieTaskTest,DeferredDeleteAllCreatedInTimeRangeCookies)1221 TEST_F(DeferredCookieTaskTest, DeferredDeleteAllCreatedInTimeRangeCookies) {
1222   const TimeRange time_range(base::Time(), base::Time::Now());
1223 
1224   ResultSavingCookieCallback<uint32_t> call1;
1225   cookie_monster_->DeleteAllCreatedInTimeRangeAsync(time_range,
1226                                                     call1.MakeCallback());
1227   base::RunLoop().RunUntilIdle();
1228   EXPECT_FALSE(call1.was_run());
1229 
1230   ExecuteLoads(CookieStoreCommand::LOAD);
1231   call1.WaitUntilDone();
1232   EXPECT_EQ(0u, call1.result());
1233   EXPECT_EQ("LOAD; ", TakeCommandSummary());
1234 
1235   ResultSavingCookieCallback<uint32_t> call2;
1236   cookie_monster_->DeleteAllCreatedInTimeRangeAsync(time_range,
1237                                                     call2.MakeCallback());
1238   call2.WaitUntilDone();
1239   EXPECT_EQ(0u, call2.result());
1240   EXPECT_EQ("", TakeCommandSummary());
1241 }
1242 
TEST_F(DeferredCookieTaskTest,DeferredDeleteAllWithPredicateCreatedInTimeRangeCookies)1243 TEST_F(DeferredCookieTaskTest,
1244        DeferredDeleteAllWithPredicateCreatedInTimeRangeCookies) {
1245   ResultSavingCookieCallback<uint32_t> call1;
1246   cookie_monster_->DeleteAllMatchingInfoAsync(
1247       CookieDeletionInfo(Time(), Time::Now()), call1.MakeCallback());
1248   base::RunLoop().RunUntilIdle();
1249   EXPECT_FALSE(call1.was_run());
1250 
1251   ExecuteLoads(CookieStoreCommand::LOAD);
1252   call1.WaitUntilDone();
1253   EXPECT_EQ(0u, call1.result());
1254   EXPECT_EQ("LOAD; ", TakeCommandSummary());
1255 
1256   ResultSavingCookieCallback<uint32_t> call2;
1257   cookie_monster_->DeleteAllMatchingInfoAsync(
1258       CookieDeletionInfo(Time(), Time::Now()), call2.MakeCallback());
1259   call2.WaitUntilDone();
1260   EXPECT_EQ(0u, call2.result());
1261   EXPECT_EQ("", TakeCommandSummary());
1262 }
1263 
TEST_F(DeferredCookieTaskTest,DeferredDeleteMatchingCookies)1264 TEST_F(DeferredCookieTaskTest, DeferredDeleteMatchingCookies) {
1265   ResultSavingCookieCallback<uint32_t> call1;
1266   cookie_monster_->DeleteMatchingCookiesAsync(
1267       base::BindRepeating(
1268           [](const net::CanonicalCookie& cookie) { return true; }),
1269       call1.MakeCallback());
1270   base::RunLoop().RunUntilIdle();
1271   EXPECT_FALSE(call1.was_run());
1272 
1273   ExecuteLoads(CookieStoreCommand::LOAD);
1274   call1.WaitUntilDone();
1275   EXPECT_EQ(0u, call1.result());
1276   EXPECT_EQ("LOAD; ", TakeCommandSummary());
1277 
1278   ResultSavingCookieCallback<uint32_t> call2;
1279   cookie_monster_->DeleteMatchingCookiesAsync(
1280       base::BindRepeating(
1281           [](const net::CanonicalCookie& cookie) { return true; }),
1282       call2.MakeCallback());
1283   call2.WaitUntilDone();
1284   EXPECT_EQ(0u, call2.result());
1285   EXPECT_EQ("", TakeCommandSummary());
1286 }
1287 
TEST_F(DeferredCookieTaskTest,DeferredDeleteCanonicalCookie)1288 TEST_F(DeferredCookieTaskTest, DeferredDeleteCanonicalCookie) {
1289   std::unique_ptr<CanonicalCookie> cookie = BuildCanonicalCookie(
1290       http_www_foo_.url(), "X=1; path=/", base::Time::Now());
1291 
1292   ResultSavingCookieCallback<uint32_t> call1;
1293   cookie_monster_->DeleteCanonicalCookieAsync(*cookie, call1.MakeCallback());
1294   base::RunLoop().RunUntilIdle();
1295   EXPECT_FALSE(call1.was_run());
1296 
1297   // TODO(morlovich): Fix DeleteCanonicalCookieAsync. This test should pass
1298   // when using LOAD_COOKIES_FOR_KEY instead, with that reflected in
1299   // TakeCommandSummary() as well.
1300   ExecuteLoads(CookieStoreCommand::LOAD);
1301   call1.WaitUntilDone();
1302   EXPECT_EQ(0u, call1.result());
1303   EXPECT_EQ("LOAD; ", TakeCommandSummary());
1304 
1305   ResultSavingCookieCallback<uint32_t> call2;
1306   cookie_monster_->DeleteCanonicalCookieAsync(*cookie, call2.MakeCallback());
1307   call2.WaitUntilDone();
1308   EXPECT_EQ(0u, call2.result());
1309   EXPECT_EQ("", TakeCommandSummary());
1310 }
1311 
TEST_F(DeferredCookieTaskTest,DeferredDeleteSessionCookies)1312 TEST_F(DeferredCookieTaskTest, DeferredDeleteSessionCookies) {
1313   ResultSavingCookieCallback<uint32_t> call1;
1314   cookie_monster_->DeleteSessionCookiesAsync(call1.MakeCallback());
1315   base::RunLoop().RunUntilIdle();
1316   EXPECT_FALSE(call1.was_run());
1317 
1318   ExecuteLoads(CookieStoreCommand::LOAD);
1319   call1.WaitUntilDone();
1320   EXPECT_EQ(0u, call1.result());
1321   EXPECT_EQ("LOAD; ", TakeCommandSummary());
1322 
1323   ResultSavingCookieCallback<uint32_t> call2;
1324   cookie_monster_->DeleteSessionCookiesAsync(call2.MakeCallback());
1325   call2.WaitUntilDone();
1326   EXPECT_EQ(0u, call2.result());
1327   EXPECT_EQ("", TakeCommandSummary());
1328 }
1329 
1330 // Verify that a series of queued tasks are executed in order upon loading of
1331 // the backing store and that new tasks received while the queued tasks are
1332 // being dispatched go to the end of the queue.
TEST_F(DeferredCookieTaskTest,DeferredTaskOrder)1333 TEST_F(DeferredCookieTaskTest, DeferredTaskOrder) {
1334   cookie_monster_->SetPersistSessionCookies(true);
1335   DeclareLoadedCookie(http_www_foo_.url(),
1336                       "X=1; path=/" + FutureCookieExpirationString(),
1337                       Time::Now() + base::Days(3));
1338 
1339   bool get_cookie_list_callback_was_run = false;
1340   GetCookieListCallback get_cookie_list_callback_deferred;
1341   ResultSavingCookieCallback<CookieAccessResult> set_cookies_callback;
1342   base::RunLoop run_loop;
1343   cookie_monster_->GetCookieListWithOptionsAsync(
1344       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1345       CookiePartitionKeyCollection(),
1346       base::BindLambdaForTesting(
1347           [&](const CookieAccessResultList& cookies,
1348               const CookieAccessResultList& excluded_list) {
1349             // This should complete before the set.
1350             get_cookie_list_callback_was_run = true;
1351             EXPECT_FALSE(set_cookies_callback.was_run());
1352             EXPECT_THAT(cookies, MatchesCookieLine("X=1"));
1353             // Can't use TakeCommandSummary here since ExecuteLoads is walking
1354             // through the data it takes.
1355             EXPECT_EQ("LOAD; LOAD_FOR_KEY:foo.com; ",
1356                       CommandSummary(persistent_store_->commands()));
1357 
1358             // Queue up a second get. It should see the result of the set queued
1359             // before it.
1360             cookie_monster_->GetCookieListWithOptionsAsync(
1361                 http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1362                 CookiePartitionKeyCollection(),
1363                 get_cookie_list_callback_deferred.MakeCallback());
1364 
1365             run_loop.Quit();
1366           }));
1367 
1368   cookie_monster_->SetCanonicalCookieAsync(
1369       CanonicalCookie::Create(http_www_foo_.url(), "A=B", base::Time::Now(),
1370                               absl::nullopt /* server_time */,
1371                               absl::nullopt /* cookie_partition_key */),
1372       http_www_foo_.url(), CookieOptions::MakeAllInclusive(),
1373       set_cookies_callback.MakeCallback());
1374 
1375   // Nothing happened yet, before loads are done.
1376   base::RunLoop().RunUntilIdle();
1377   EXPECT_FALSE(get_cookie_list_callback_was_run);
1378   EXPECT_FALSE(set_cookies_callback.was_run());
1379 
1380   ExecuteLoads(CookieStoreCommand::LOAD_COOKIES_FOR_KEY);
1381   run_loop.Run();
1382   EXPECT_EQ("LOAD; LOAD_FOR_KEY:foo.com; ADD; ", TakeCommandSummary());
1383   EXPECT_TRUE(get_cookie_list_callback_was_run);
1384   ASSERT_TRUE(set_cookies_callback.was_run());
1385   EXPECT_TRUE(set_cookies_callback.result().status.IsInclude());
1386 
1387   ASSERT_TRUE(get_cookie_list_callback_deferred.was_run());
1388   EXPECT_THAT(get_cookie_list_callback_deferred.cookies(),
1389               MatchesCookieLine("A=B; X=1"));
1390 }
1391 
TEST_F(CookieMonsterTest,TestCookieDeleteAll)1392 TEST_F(CookieMonsterTest, TestCookieDeleteAll) {
1393   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
1394   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
1395   CookieOptions options = CookieOptions::MakeAllInclusive();
1396 
1397   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), kValidCookieLine));
1398   EXPECT_EQ("A=B", GetCookies(cm.get(), http_www_foo_.url()));
1399 
1400   EXPECT_TRUE(CreateAndSetCookie(cm.get(), http_www_foo_.url(), "C=D; httponly",
1401                                  options));
1402   EXPECT_EQ("A=B; C=D",
1403             GetCookiesWithOptions(cm.get(), http_www_foo_.url(), options));
1404 
1405   EXPECT_EQ(2u, DeleteAll(cm.get()));
1406   EXPECT_EQ("", GetCookiesWithOptions(cm.get(), http_www_foo_.url(), options));
1407   EXPECT_EQ(0u, store->commands().size());
1408 
1409   // Create a persistent cookie.
1410   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(),
1411                         kValidCookieLine + FutureCookieExpirationString()));
1412   ASSERT_EQ(1u, store->commands().size());
1413   EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[0].type);
1414 
1415   EXPECT_EQ(1u, DeleteAll(cm.get()));  // sync_to_store = true.
1416   ASSERT_EQ(2u, store->commands().size());
1417   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type);
1418 
1419   EXPECT_EQ("", GetCookiesWithOptions(cm.get(), http_www_foo_.url(), options));
1420 
1421   // Create a Partitioned cookie.
1422   auto cookie_partition_key =
1423       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
1424   EXPECT_TRUE(SetCookie(
1425       cm.get(), https_www_foo_.url(),
1426       "__Host-" + std::string(kValidCookieLine) + "; partitioned; secure",
1427       cookie_partition_key));
1428   EXPECT_EQ(1u, DeleteAll(cm.get()));
1429   EXPECT_EQ("", GetCookiesWithOptions(
1430                     cm.get(), http_www_foo_.url(), options,
1431                     CookiePartitionKeyCollection(cookie_partition_key)));
1432   EXPECT_EQ(2u, store->commands().size());
1433 }
1434 
TEST_F(CookieMonsterTest,TestCookieDeleteAllCreatedInTimeRangeTimestamps)1435 TEST_F(CookieMonsterTest, TestCookieDeleteAllCreatedInTimeRangeTimestamps) {
1436   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1437 
1438   Time now = Time::Now();
1439 
1440   // Nothing has been added so nothing should be deleted.
1441   EXPECT_EQ(0u, DeleteAllCreatedInTimeRange(
1442                     cm.get(), TimeRange(now - base::Days(99), Time())));
1443 
1444   // Create 5 cookies with different creation dates.
1445   EXPECT_TRUE(
1446       SetCookieWithCreationTime(cm.get(), http_www_foo_.url(), "T-0=Now", now));
1447   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1448                                         "T-1=Yesterday", now - base::Days(1)));
1449   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1450                                         "T-2=DayBefore", now - base::Days(2)));
1451   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1452                                         "T-3=ThreeDays", now - base::Days(3)));
1453   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1454                                         "T-7=LastWeek", now - base::Days(7)));
1455 
1456   // Try to delete threedays and the daybefore.
1457   EXPECT_EQ(2u,
1458             DeleteAllCreatedInTimeRange(
1459                 cm.get(), TimeRange(now - base::Days(3), now - base::Days(1))));
1460 
1461   // Try to delete yesterday, also make sure that delete_end is not
1462   // inclusive.
1463   EXPECT_EQ(1u, DeleteAllCreatedInTimeRange(
1464                     cm.get(), TimeRange(now - base::Days(2), now)));
1465 
1466   // Make sure the delete_begin is inclusive.
1467   EXPECT_EQ(1u, DeleteAllCreatedInTimeRange(
1468                     cm.get(), TimeRange(now - base::Days(7), now)));
1469 
1470   // Delete the last (now) item.
1471   EXPECT_EQ(1u, DeleteAllCreatedInTimeRange(cm.get(), TimeRange()));
1472 
1473   // Really make sure everything is gone.
1474   EXPECT_EQ(0u, DeleteAll(cm.get()));
1475 
1476   // Test the same deletion process with partitioned cookies. Partitioned
1477   // cookies should behave the same way as unpartitioned cookies here, they are
1478   // just stored in a different data structure internally.
1479 
1480   EXPECT_TRUE(
1481       SetCookieWithCreationTime(cm.get(), http_www_foo_.url(), "T-0=Now", now,
1482                                 CookiePartitionKey::FromURLForTesting(
1483                                     GURL("https://toplevelsite0.com"))));
1484   EXPECT_TRUE(SetCookieWithCreationTime(
1485       cm.get(), https_www_foo_.url(), "T-1=Yesterday", now - base::Days(1),
1486       CookiePartitionKey::FromURLForTesting(
1487           GURL("https://toplevelsite1.com"))));
1488   EXPECT_TRUE(SetCookieWithCreationTime(
1489       cm.get(), http_www_foo_.url(), "T-2=DayBefore", now - base::Days(2),
1490       CookiePartitionKey::FromURLForTesting(
1491           GURL("https://toplevelsite1.com"))));
1492   EXPECT_TRUE(SetCookieWithCreationTime(
1493       cm.get(), http_www_foo_.url(), "T-3=ThreeDays", now - base::Days(3),
1494       CookiePartitionKey::FromURLForTesting(
1495           GURL("https://toplevelsite2.com"))));
1496   EXPECT_TRUE(SetCookieWithCreationTime(
1497       cm.get(), http_www_foo_.url(), "T-7=LastWeek", now - base::Days(7),
1498       CookiePartitionKey::FromURLForTesting(
1499           GURL("https://toplevelsite3.com"))));
1500 
1501   // Try to delete threedays and the daybefore.
1502   EXPECT_EQ(2u,
1503             DeleteAllCreatedInTimeRange(
1504                 cm.get(), TimeRange(now - base::Days(3), now - base::Days(1))));
1505 
1506   // Try to delete yesterday, also make sure that delete_end is not
1507   // inclusive.
1508   EXPECT_EQ(1u, DeleteAllCreatedInTimeRange(
1509                     cm.get(), TimeRange(now - base::Days(2), now)));
1510 
1511   // Make sure the delete_begin is inclusive.
1512   EXPECT_EQ(1u, DeleteAllCreatedInTimeRange(
1513                     cm.get(), TimeRange(now - base::Days(7), now)));
1514 
1515   // Delete the last (now) item.
1516   EXPECT_EQ(1u, DeleteAllCreatedInTimeRange(cm.get(), TimeRange()));
1517 
1518   // Really make sure everything is gone.
1519   EXPECT_EQ(0u, DeleteAll(cm.get()));
1520 }
1521 
TEST_F(CookieMonsterTest,TestCookieDeleteAllCreatedInTimeRangeTimestampsWithInfo)1522 TEST_F(CookieMonsterTest,
1523        TestCookieDeleteAllCreatedInTimeRangeTimestampsWithInfo) {
1524   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1525 
1526   Time now = Time::Now();
1527 
1528   CanonicalCookie test_cookie;
1529 
1530   // Nothing has been added so nothing should be deleted.
1531   EXPECT_EQ(0u,
1532             DeleteAllMatchingInfo(
1533                 cm.get(), CookieDeletionInfo(now - base::Days(99), Time())));
1534 
1535   // Create 5 cookies with different creation dates.
1536   EXPECT_TRUE(
1537       SetCookieWithCreationTime(cm.get(), http_www_foo_.url(), "T-0=Now", now));
1538   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1539                                         "T-1=Yesterday", now - base::Days(1)));
1540   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1541                                         "T-2=DayBefore", now - base::Days(2)));
1542   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1543                                         "T-3=ThreeDays", now - base::Days(3)));
1544   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
1545                                         "T-7=LastWeek", now - base::Days(7)));
1546 
1547   // Delete threedays and the daybefore.
1548   EXPECT_EQ(2u, DeleteAllMatchingInfo(cm.get(),
1549                                       CookieDeletionInfo(now - base::Days(3),
1550                                                          now - base::Days(1))));
1551 
1552   // Delete yesterday, also make sure that delete_end is not inclusive.
1553   EXPECT_EQ(1u, DeleteAllMatchingInfo(
1554                     cm.get(), CookieDeletionInfo(now - base::Days(2), now)));
1555 
1556   // Make sure the delete_begin is inclusive.
1557   EXPECT_EQ(1u, DeleteAllMatchingInfo(
1558                     cm.get(), CookieDeletionInfo(now - base::Days(7), now)));
1559 
1560   // Delete the last (now) item.
1561   EXPECT_EQ(1u, DeleteAllMatchingInfo(cm.get(), CookieDeletionInfo()));
1562 
1563   // Really make sure everything is gone.
1564   EXPECT_EQ(0u, DeleteAll(cm.get()));
1565 
1566   // Test the same deletion process with partitioned cookies. Partitioned
1567   // cookies should behave the same way as unpartitioned cookies here, they are
1568   // just stored in a different data structure internally.
1569 
1570   EXPECT_TRUE(
1571       SetCookieWithCreationTime(cm.get(), http_www_foo_.url(), "T-0=Now", now,
1572                                 CookiePartitionKey::FromURLForTesting(
1573                                     GURL("https://toplevelsite0.com"))));
1574   EXPECT_TRUE(SetCookieWithCreationTime(
1575       cm.get(), https_www_foo_.url(), "T-1=Yesterday", now - base::Days(1),
1576       CookiePartitionKey::FromURLForTesting(
1577           GURL("https://toplevelsite1.com"))));
1578   EXPECT_TRUE(SetCookieWithCreationTime(
1579       cm.get(), http_www_foo_.url(), "T-2=DayBefore", now - base::Days(2),
1580       CookiePartitionKey::FromURLForTesting(
1581           GURL("https://toplevelsite1.com"))));
1582   EXPECT_TRUE(SetCookieWithCreationTime(
1583       cm.get(), http_www_foo_.url(), "T-3=ThreeDays", now - base::Days(3),
1584       CookiePartitionKey::FromURLForTesting(
1585           GURL("https://toplevelsite2.com"))));
1586   EXPECT_TRUE(SetCookieWithCreationTime(
1587       cm.get(), http_www_foo_.url(), "T-7=LastWeek", now - base::Days(7),
1588       CookiePartitionKey::FromURLForTesting(
1589           GURL("https://toplevelsite3.com"))));
1590 
1591   // Delete threedays and the daybefore.
1592   EXPECT_EQ(2u, DeleteAllMatchingInfo(cm.get(),
1593                                       CookieDeletionInfo(now - base::Days(3),
1594                                                          now - base::Days(1))));
1595 
1596   // Delete yesterday, also make sure that delete_end is not inclusive.
1597   EXPECT_EQ(1u, DeleteAllMatchingInfo(
1598                     cm.get(), CookieDeletionInfo(now - base::Days(2), now)));
1599 
1600   // Make sure the delete_begin is inclusive.
1601   EXPECT_EQ(1u, DeleteAllMatchingInfo(
1602                     cm.get(), CookieDeletionInfo(now - base::Days(7), now)));
1603 
1604   // Delete the last (now) item.
1605   EXPECT_EQ(1u, DeleteAllMatchingInfo(cm.get(), CookieDeletionInfo()));
1606 
1607   // Really make sure everything is gone.
1608   EXPECT_EQ(0u, DeleteAll(cm.get()));
1609 }
1610 
TEST_F(CookieMonsterTest,TestCookieDeleteMatchingCookies)1611 TEST_F(CookieMonsterTest, TestCookieDeleteMatchingCookies) {
1612   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1613   Time now = Time::Now();
1614 
1615   // Nothing has been added so nothing should be deleted.
1616   EXPECT_EQ(0u, DeleteMatchingCookies(
1617                     cm.get(),
1618                     base::BindRepeating([](const net::CanonicalCookie& cookie) {
1619                       return true;
1620                     })));
1621 
1622   // Create 5 cookies with different domains and security status.
1623   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), GURL("https://a.com"),
1624                                         "a1=1;Secure", now));
1625   EXPECT_TRUE(
1626       SetCookieWithCreationTime(cm.get(), GURL("https://a.com"), "a2=2", now));
1627   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), GURL("https://b.com"),
1628                                         "b1=1;Secure", now));
1629   EXPECT_TRUE(
1630       SetCookieWithCreationTime(cm.get(), GURL("http://b.com"), "b2=2", now));
1631   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), GURL("https://c.com"),
1632                                         "c1=1;Secure", now));
1633 
1634   // Set a partitioned cookie.
1635   EXPECT_TRUE(SetCookieWithCreationTime(
1636       cm.get(), GURL("https://d.com"),
1637       "__Host-pc=123; path=/; secure; partitioned", now,
1638       CookiePartitionKey::FromURLForTesting(GURL("https://e.com"))));
1639 
1640   // Delete http cookies.
1641   EXPECT_EQ(2u, DeleteMatchingCookies(
1642                     cm.get(),
1643                     base::BindRepeating([](const net::CanonicalCookie& cookie) {
1644                       return !cookie.IsSecure();
1645                     })));
1646   EXPECT_THAT(GetAllCookies(cm.get()),
1647               ElementsAre(MatchesCookieNameDomain("a1", "a.com"),
1648                           MatchesCookieNameDomain("b1", "b.com"),
1649                           MatchesCookieNameDomain("c1", "c.com"),
1650                           MatchesCookieNameDomain("__Host-pc", "d.com")));
1651 
1652   // Delete remaining cookie for a.com.
1653   EXPECT_EQ(1u, DeleteMatchingCookies(
1654                     cm.get(),
1655                     base::BindRepeating([](const net::CanonicalCookie& cookie) {
1656                       return cookie.Domain() == "a.com";
1657                     })));
1658   EXPECT_THAT(GetAllCookies(cm.get()),
1659               ElementsAre(MatchesCookieNameDomain("b1", "b.com"),
1660                           MatchesCookieNameDomain("c1", "c.com"),
1661                           MatchesCookieNameDomain("__Host-pc", "d.com")));
1662 
1663   // Delete the partitioned cookie.
1664   EXPECT_EQ(1u, DeleteMatchingCookies(
1665                     cm.get(),
1666                     base::BindRepeating([](const net::CanonicalCookie& cookie) {
1667                       return cookie.IsPartitioned();
1668                     })));
1669 
1670   // Delete the last two item.
1671   EXPECT_EQ(2u, DeleteMatchingCookies(
1672                     cm.get(),
1673                     base::BindRepeating([](const net::CanonicalCookie& cookie) {
1674                       return true;
1675                     })));
1676 
1677   // Really make sure everything is gone.
1678   EXPECT_TRUE(GetAllCookies(cm.get()).empty());
1679 }
1680 
1681 static const base::TimeDelta kLastAccessThreshold = base::Milliseconds(200);
1682 static const base::TimeDelta kAccessDelay =
1683     kLastAccessThreshold + base::Milliseconds(20);
1684 
TEST_F(CookieMonsterTest,TestLastAccess)1685 TEST_F(CookieMonsterTest, TestLastAccess) {
1686   auto cm = std::make_unique<CookieMonster>(nullptr, kLastAccessThreshold,
1687                                             net::NetLog::Get());
1688 
1689   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "A=B"));
1690   const Time last_access_date(GetFirstCookieAccessDate(cm.get()));
1691 
1692   // Reading the cookie again immediately shouldn't update the access date,
1693   // since we're inside the threshold.
1694   EXPECT_EQ("A=B", GetCookies(cm.get(), http_www_foo_.url()));
1695   EXPECT_EQ(last_access_date, GetFirstCookieAccessDate(cm.get()));
1696 
1697   // Reading after a short wait will update the access date, if the cookie
1698   // is requested with options that would update the access date. First, test
1699   // that the flag's behavior is respected.
1700   base::PlatformThread::Sleep(kAccessDelay);
1701   CookieOptions options = CookieOptions::MakeAllInclusive();
1702   options.set_do_not_update_access_time();
1703   EXPECT_EQ("A=B",
1704             GetCookiesWithOptions(cm.get(), http_www_foo_.url(), options));
1705   EXPECT_EQ(last_access_date, GetFirstCookieAccessDate(cm.get()));
1706 
1707   // Getting all cookies for a URL doesn't update the accessed time either.
1708   CookieList cookies = GetAllCookiesForURL(cm.get(), http_www_foo_.url());
1709   auto it = cookies.begin();
1710   ASSERT_TRUE(it != cookies.end());
1711   EXPECT_EQ(http_www_foo_.host(), it->Domain());
1712   EXPECT_EQ("A", it->Name());
1713   EXPECT_EQ("B", it->Value());
1714   EXPECT_EQ(last_access_date, GetFirstCookieAccessDate(cm.get()));
1715   EXPECT_TRUE(++it == cookies.end());
1716 
1717   // If the flag isn't set, the last accessed time should be updated.
1718   options.set_update_access_time();
1719   EXPECT_EQ("A=B",
1720             GetCookiesWithOptions(cm.get(), http_www_foo_.url(), options));
1721   EXPECT_FALSE(last_access_date == GetFirstCookieAccessDate(cm.get()));
1722 }
1723 
TEST_F(CookieMonsterTest,TestHostGarbageCollection)1724 TEST_F(CookieMonsterTest, TestHostGarbageCollection) {
1725   TestHostGarbageCollectHelper();
1726 }
1727 
TEST_F(CookieMonsterTest,TestPriorityAwareGarbageCollectionNonSecure)1728 TEST_F(CookieMonsterTest, TestPriorityAwareGarbageCollectionNonSecure) {
1729   TestPriorityAwareGarbageCollectHelperNonSecure();
1730 }
1731 
TEST_F(CookieMonsterTest,TestPriorityAwareGarbageCollectionSecure)1732 TEST_F(CookieMonsterTest, TestPriorityAwareGarbageCollectionSecure) {
1733   TestPriorityAwareGarbageCollectHelperSecure();
1734 }
1735 
TEST_F(CookieMonsterTest,TestPriorityAwareGarbageCollectionMixed)1736 TEST_F(CookieMonsterTest, TestPriorityAwareGarbageCollectionMixed) {
1737   TestPriorityAwareGarbageCollectHelperMixed();
1738 }
1739 
TEST_F(CookieMonsterTest,TestPartitionedCookiesGarbageCollection_Memory)1740 TEST_F(CookieMonsterTest, TestPartitionedCookiesGarbageCollection_Memory) {
1741   // Limit should be 10 KB.
1742   DCHECK_EQ(1024u * 10u, CookieMonster::kPerPartitionDomainMaxCookieBytes);
1743 
1744   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1745   auto cookie_partition_key =
1746       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite1.com"));
1747 
1748   for (size_t i = 0; i < 41; ++i) {
1749     std::string cookie_value((10240 / 40) - (i < 10 ? 1 : 2), '0');
1750     std::string cookie =
1751         base::StrCat({base::NumberToString(i), "=", cookie_value});
1752     EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(),
1753                           cookie + "; secure; path=/; partitioned",
1754                           cookie_partition_key))
1755         << "Failed to set cookie " << i;
1756   }
1757 
1758   std::string cookies =
1759       this->GetCookies(cm.get(), https_www_foo_.url(),
1760                        CookiePartitionKeyCollection(cookie_partition_key));
1761 
1762   EXPECT_THAT(cookies, CookieStringIs(
1763                            testing::Not(testing::Contains(testing::Key("0")))));
1764   for (size_t i = 1; i < 41; ++i) {
1765     EXPECT_THAT(cookies, CookieStringIs(testing::Contains(
1766                              testing::Key(base::NumberToString(i)))))
1767         << "Failed to find cookie " << i;
1768   }
1769 }
1770 
TEST_F(CookieMonsterTest,TestPartitionedCookiesGarbageCollection_MaxCookies)1771 TEST_F(CookieMonsterTest, TestPartitionedCookiesGarbageCollection_MaxCookies) {
1772   // Partitioned cookies also limit domains to 180 cookies per partition.
1773   DCHECK_EQ(180u, CookieMonster::kPerPartitionDomainMaxCookies);
1774 
1775   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1776   auto cookie_partition_key =
1777       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
1778 
1779   for (size_t i = 0; i < 181; ++i) {
1780     std::string cookie = base::StrCat({base::NumberToString(i), "=0"});
1781     EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(),
1782                           cookie + "; secure; path=/; partitioned",
1783                           cookie_partition_key))
1784         << "Failed to set cookie " << i;
1785   }
1786 
1787   std::string cookies =
1788       this->GetCookies(cm.get(), https_www_foo_.url(),
1789                        CookiePartitionKeyCollection(cookie_partition_key));
1790   EXPECT_THAT(cookies, CookieStringIs(
1791                            testing::Not(testing::Contains(testing::Key("0")))));
1792   for (size_t i = 1; i < 181; ++i) {
1793     std::string cookie = base::StrCat({base::NumberToString(i), "=0"});
1794     EXPECT_THAT(cookies, CookieStringIs(testing::Contains(
1795                              testing::Key(base::NumberToString(i)))))
1796         << "Failed to find cookie " << i;
1797   }
1798 }
1799 
TEST_F(CookieMonsterTest,SetCookieableSchemes)1800 TEST_F(CookieMonsterTest, SetCookieableSchemes) {
1801   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1802 
1803   auto cm_foo = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1804 
1805   // Only cm_foo should allow foo:// cookies.
1806   std::vector<std::string> schemes;
1807   schemes.push_back("foo");
1808   ResultSavingCookieCallback<bool> cookie_scheme_callback;
1809   cm_foo->SetCookieableSchemes(schemes, cookie_scheme_callback.MakeCallback());
1810   cookie_scheme_callback.WaitUntilDone();
1811   EXPECT_TRUE(cookie_scheme_callback.result());
1812 
1813   GURL foo_url("foo://host/path");
1814   GURL http_url("http://host/path");
1815 
1816   base::Time now = base::Time::Now();
1817   absl::optional<base::Time> server_time = absl::nullopt;
1818   EXPECT_TRUE(
1819       CreateAndSetCookieReturnStatus(cm.get(), http_url, "x=1").IsInclude());
1820   EXPECT_TRUE(
1821       SetCanonicalCookieReturnAccessResult(
1822           cm.get(),
1823           CanonicalCookie::Create(http_url, "y=1", now, server_time,
1824                                   absl::nullopt /* cookie_partition_key */),
1825           http_url, false /*modify_httponly*/)
1826           .status.IsInclude());
1827 
1828   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), foo_url, "x=1")
1829                   .HasExactlyExclusionReasonsForTesting(
1830                       {CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME}));
1831   EXPECT_TRUE(
1832       SetCanonicalCookieReturnAccessResult(
1833           cm.get(),
1834           CanonicalCookie::Create(foo_url, "y=1", now, server_time,
1835                                   absl::nullopt /* cookie_partition_key */),
1836           foo_url, false /*modify_httponly*/)
1837           .status.HasExactlyExclusionReasonsForTesting(
1838               {CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME}));
1839 
1840   EXPECT_TRUE(
1841       CreateAndSetCookieReturnStatus(cm_foo.get(), foo_url, "x=1").IsInclude());
1842   EXPECT_TRUE(
1843       SetCanonicalCookieReturnAccessResult(
1844           cm_foo.get(),
1845           CanonicalCookie::Create(foo_url, "y=1", now, server_time,
1846                                   absl::nullopt /* cookie_partition_key */),
1847           foo_url, false /*modify_httponly*/)
1848           .status.IsInclude());
1849 
1850   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm_foo.get(), http_url, "x=1")
1851                   .HasExactlyExclusionReasonsForTesting(
1852                       {CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME}));
1853   EXPECT_TRUE(
1854       SetCanonicalCookieReturnAccessResult(
1855           cm_foo.get(),
1856           CanonicalCookie::Create(http_url, "y=1", now, server_time,
1857                                   absl::nullopt /* cookie_partition_key */),
1858           http_url, false /*modify_httponly*/)
1859           .status.HasExactlyExclusionReasonsForTesting(
1860               {CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME}));
1861 }
1862 
TEST_F(CookieMonsterTest,SetCookieableSchemes_StoreInitialized)1863 TEST_F(CookieMonsterTest, SetCookieableSchemes_StoreInitialized) {
1864   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
1865   // Initializes the cookie store.
1866   this->GetCookies(cm.get(), https_www_foo_.url(),
1867                    CookiePartitionKeyCollection());
1868 
1869   std::vector<std::string> schemes;
1870   schemes.push_back("foo");
1871   ResultSavingCookieCallback<bool> cookie_scheme_callback;
1872   cm->SetCookieableSchemes(schemes, cookie_scheme_callback.MakeCallback());
1873   cookie_scheme_callback.WaitUntilDone();
1874   EXPECT_FALSE(cookie_scheme_callback.result());
1875 
1876   base::Time now = base::Time::Now();
1877   absl::optional<base::Time> server_time = absl::nullopt;
1878   GURL foo_url("foo://host/path");
1879   EXPECT_TRUE(
1880       SetCanonicalCookieReturnAccessResult(
1881           cm.get(),
1882           CanonicalCookie::Create(foo_url, "y=1", now, server_time,
1883                                   absl::nullopt /* cookie_partition_key */),
1884           foo_url, false /*modify_httponly*/)
1885           .status.HasExactlyExclusionReasonsForTesting(
1886               {CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME}));
1887 }
1888 
TEST_F(CookieMonsterTest,GetAllCookiesForURL)1889 TEST_F(CookieMonsterTest, GetAllCookiesForURL) {
1890   auto cm = std::make_unique<CookieMonster>(nullptr, kLastAccessThreshold,
1891                                             net::NetLog::Get());
1892 
1893   // Create an httponly cookie.
1894   CookieOptions options = CookieOptions::MakeAllInclusive();
1895 
1896   EXPECT_TRUE(CreateAndSetCookie(cm.get(), http_www_foo_.url(), "A=B; httponly",
1897                                  options));
1898   EXPECT_TRUE(CreateAndSetCookie(cm.get(), http_www_foo_.url(),
1899                                  http_www_foo_.Format("C=D; domain=.%D"),
1900                                  options));
1901   EXPECT_TRUE(CreateAndSetCookie(
1902       cm.get(), https_www_foo_.url(),
1903       http_www_foo_.Format("E=F; domain=.%D; secure"), options));
1904 
1905   EXPECT_TRUE(CreateAndSetCookie(cm.get(), http_www_bar_.url(),
1906                                  http_www_bar_.Format("G=H; domain=.%D"),
1907                                  options));
1908 
1909   EXPECT_TRUE(CreateAndSetCookie(
1910       cm.get(), https_www_foo_.url(),
1911       https_www_foo_.Format("I=J; domain=.%D; secure; sameparty"), options));
1912 
1913   // Create partitioned cookies for the same site with some partition key.
1914   auto cookie_partition_key1 =
1915       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite1.com"));
1916   auto cookie_partition_key2 =
1917       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite2.com"));
1918   auto cookie_partition_key3 =
1919       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite3.com"));
1920   EXPECT_TRUE(CreateAndSetCookie(
1921       cm.get(), https_www_bar_.url(), "__Host-K=L; secure; path=/; partitioned",
1922       options, absl::nullopt, absl::nullopt, cookie_partition_key1));
1923   EXPECT_TRUE(CreateAndSetCookie(
1924       cm.get(), https_www_bar_.url(), "__Host-M=N; secure; path=/; partitioned",
1925       options, absl::nullopt, absl::nullopt, cookie_partition_key2));
1926   EXPECT_TRUE(CreateAndSetCookie(
1927       cm.get(), https_www_bar_.url(), "__Host-O=P; secure; path=/; partitioned",
1928       options, absl::nullopt, absl::nullopt, cookie_partition_key3));
1929 
1930   const Time last_access_date(GetFirstCookieAccessDate(cm.get()));
1931 
1932   base::PlatformThread::Sleep(kAccessDelay);
1933 
1934   // Check cookies for url.
1935   EXPECT_THAT(
1936       GetAllCookiesForURL(cm.get(), http_www_foo_.url()),
1937       ElementsAre(MatchesCookieNameDomain("A", http_www_foo_.host()),
1938                   MatchesCookieNameDomain("C", http_www_foo_.Format(".%D"))));
1939 
1940   // Check cookies for url excluding http-only cookies.
1941   CookieOptions exclude_httponly = options;
1942   exclude_httponly.set_exclude_httponly();
1943 
1944   EXPECT_THAT(
1945       GetAllCookiesForURLWithOptions(cm.get(), http_www_foo_.url(),
1946                                      exclude_httponly),
1947       ElementsAre(MatchesCookieNameDomain("C", http_www_foo_.Format(".%D"))));
1948 
1949   // Test secure cookies.
1950   EXPECT_THAT(
1951       GetAllCookiesForURL(cm.get(), https_www_foo_.url()),
1952       ElementsAre(MatchesCookieNameDomain("A", http_www_foo_.host()),
1953                   MatchesCookieNameDomain("C", http_www_foo_.Format(".%D")),
1954                   MatchesCookieNameDomain("E", http_www_foo_.Format(".%D")),
1955                   MatchesCookieNameDomain("I", http_www_foo_.Format(".%D"))));
1956 
1957   // Test reading partitioned cookies for a single partition.
1958   EXPECT_THAT(
1959       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
1960                           CookiePartitionKeyCollection(cookie_partition_key1)),
1961       ElementsAre(MatchesCookieNameDomain("G", https_www_bar_.Format(".%D")),
1962                   MatchesCookieNameDomain("__Host-K", https_www_bar_.host())));
1963   EXPECT_THAT(
1964       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
1965                           CookiePartitionKeyCollection(cookie_partition_key2)),
1966       ElementsAre(MatchesCookieNameDomain("G", https_www_bar_.Format(".%D")),
1967                   MatchesCookieNameDomain("__Host-M", https_www_bar_.host())));
1968 
1969   // Test reading partitioned cookies from multiple partitions.
1970   EXPECT_THAT(
1971       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
1972                           CookiePartitionKeyCollection(
1973                               {cookie_partition_key1, cookie_partition_key2})),
1974       ElementsAre(MatchesCookieNameDomain("G", https_www_bar_.Format(".%D")),
1975                   MatchesCookieNameDomain("__Host-K", https_www_bar_.host()),
1976                   MatchesCookieNameDomain("__Host-M", https_www_bar_.host())));
1977 
1978   // Test reading partitioned cookies from every partition.
1979   EXPECT_THAT(
1980       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
1981                           CookiePartitionKeyCollection::ContainsAll()),
1982       ElementsAre(MatchesCookieNameDomain("G", https_www_bar_.Format(".%D")),
1983                   MatchesCookieNameDomain("__Host-K", https_www_bar_.host()),
1984                   MatchesCookieNameDomain("__Host-M", https_www_bar_.host()),
1985                   MatchesCookieNameDomain("__Host-O", https_www_bar_.host())));
1986 
1987   // Test excluding partitioned cookies.
1988   EXPECT_THAT(
1989       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
1990                           CookiePartitionKeyCollection()),
1991       ElementsAre(MatchesCookieNameDomain("G", https_www_bar_.Format(".%D"))));
1992 
1993   // Reading after a short wait should not update the access date.
1994   EXPECT_EQ(last_access_date, GetFirstCookieAccessDate(cm.get()));
1995 }
1996 
TEST_F(CookieMonsterTest,GetExcludedCookiesForURL)1997 TEST_F(CookieMonsterTest, GetExcludedCookiesForURL) {
1998   auto cm = std::make_unique<CookieMonster>(nullptr, kLastAccessThreshold,
1999                                             net::NetLog::Get());
2000 
2001   // Create an httponly cookie.
2002   CookieOptions options = CookieOptions::MakeAllInclusive();
2003 
2004   EXPECT_TRUE(CreateAndSetCookie(cm.get(), http_www_foo_.url(), "A=B; httponly",
2005                                  options));
2006   EXPECT_TRUE(CreateAndSetCookie(cm.get(), http_www_foo_.url(),
2007                                  http_www_foo_.Format("C=D; domain=.%D"),
2008                                  options));
2009   EXPECT_TRUE(CreateAndSetCookie(
2010       cm.get(), https_www_foo_.url(),
2011       http_www_foo_.Format("E=F; domain=.%D; secure"), options));
2012 
2013   base::PlatformThread::Sleep(kAccessDelay);
2014 
2015   // Check that no cookies are sent when option is turned off
2016   CookieOptions do_not_return_excluded;
2017   do_not_return_excluded.unset_return_excluded_cookies();
2018 
2019   CookieAccessResultList excluded_cookies = GetExcludedCookiesForURLWithOptions(
2020       cm.get(), http_www_foo_.url(), do_not_return_excluded);
2021   auto iter = excluded_cookies.begin();
2022 
2023   EXPECT_TRUE(excluded_cookies.empty());
2024 
2025   // Checking that excluded cookies get sent with their statuses with http
2026   // request.
2027   excluded_cookies = GetExcludedCookiesForURL(cm.get(), http_www_foo_.url(),
2028                                               CookiePartitionKeyCollection());
2029   iter = excluded_cookies.begin();
2030 
2031   ASSERT_TRUE(iter != excluded_cookies.end());
2032   EXPECT_EQ(http_www_foo_.Format(".%D"), iter->cookie.Domain());
2033   EXPECT_EQ("E", iter->cookie.Name());
2034   EXPECT_TRUE(iter->access_result.status.HasExactlyExclusionReasonsForTesting(
2035       {CookieInclusionStatus::EXCLUDE_SECURE_ONLY}));
2036 
2037   ASSERT_TRUE(++iter == excluded_cookies.end());
2038 
2039   // Checking that excluded cookies get sent with their statuses with http-only.
2040   CookieOptions return_excluded;
2041   return_excluded.set_return_excluded_cookies();
2042   return_excluded.set_exclude_httponly();
2043   return_excluded.set_same_site_cookie_context(
2044       CookieOptions::SameSiteCookieContext(
2045           CookieOptions::SameSiteCookieContext::ContextType::SAME_SITE_STRICT));
2046 
2047   excluded_cookies = GetExcludedCookiesForURLWithOptions(
2048       cm.get(), http_www_foo_.url(), return_excluded);
2049   iter = excluded_cookies.begin();
2050 
2051   ASSERT_TRUE(iter != excluded_cookies.end());
2052   EXPECT_EQ(http_www_foo_.host(), iter->cookie.Domain());
2053   EXPECT_EQ("A", iter->cookie.Name());
2054   EXPECT_TRUE(iter->access_result.status.HasExactlyExclusionReasonsForTesting(
2055       {CookieInclusionStatus::EXCLUDE_HTTP_ONLY}));
2056 
2057   ASSERT_TRUE(++iter != excluded_cookies.end());
2058   EXPECT_EQ(http_www_foo_.Format(".%D"), iter->cookie.Domain());
2059   EXPECT_EQ("E", iter->cookie.Name());
2060   EXPECT_TRUE(iter->access_result.status.HasExactlyExclusionReasonsForTesting(
2061       {CookieInclusionStatus::EXCLUDE_SECURE_ONLY}));
2062 
2063   ASSERT_TRUE(++iter == excluded_cookies.end());
2064 
2065   // Check that no excluded cookies are sent with secure request
2066   excluded_cookies = GetExcludedCookiesForURL(cm.get(), https_www_foo_.url(),
2067                                               CookiePartitionKeyCollection());
2068   iter = excluded_cookies.begin();
2069 
2070   EXPECT_TRUE(excluded_cookies.empty());
2071 }
2072 
TEST_F(CookieMonsterTest,GetAllCookiesForURLPathMatching)2073 TEST_F(CookieMonsterTest, GetAllCookiesForURLPathMatching) {
2074   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2075 
2076   CookieOptions options = CookieOptions::MakeAllInclusive();
2077 
2078   EXPECT_TRUE(CreateAndSetCookie(cm.get(), www_foo_foo_.url(),
2079                                  "A=B; path=/foo;", options));
2080   EXPECT_TRUE(CreateAndSetCookie(cm.get(), www_foo_bar_.url(),
2081                                  "C=D; path=/bar;", options));
2082   EXPECT_TRUE(
2083       CreateAndSetCookie(cm.get(), http_www_foo_.url(), "E=F;", options));
2084 
2085   CookieList cookies = GetAllCookiesForURL(cm.get(), www_foo_foo_.url());
2086   auto it = cookies.begin();
2087 
2088   ASSERT_TRUE(it != cookies.end());
2089   EXPECT_EQ("A", it->Name());
2090   EXPECT_EQ("/foo", it->Path());
2091 
2092   ASSERT_TRUE(++it != cookies.end());
2093   EXPECT_EQ("E", it->Name());
2094   EXPECT_EQ("/", it->Path());
2095 
2096   ASSERT_TRUE(++it == cookies.end());
2097 
2098   cookies = GetAllCookiesForURL(cm.get(), www_foo_bar_.url());
2099   it = cookies.begin();
2100 
2101   ASSERT_TRUE(it != cookies.end());
2102   EXPECT_EQ("C", it->Name());
2103   EXPECT_EQ("/bar", it->Path());
2104 
2105   ASSERT_TRUE(++it != cookies.end());
2106   EXPECT_EQ("E", it->Name());
2107   EXPECT_EQ("/", it->Path());
2108 
2109   ASSERT_TRUE(++it == cookies.end());
2110 }
2111 
TEST_F(CookieMonsterTest,GetExcludedCookiesForURLPathMatching)2112 TEST_F(CookieMonsterTest, GetExcludedCookiesForURLPathMatching) {
2113   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2114 
2115   CookieOptions options = CookieOptions::MakeAllInclusive();
2116 
2117   EXPECT_TRUE(CreateAndSetCookie(cm.get(), www_foo_foo_.url(),
2118                                  "A=B; path=/foo;", options));
2119   EXPECT_TRUE(CreateAndSetCookie(cm.get(), www_foo_bar_.url(),
2120                                  "C=D; path=/bar;", options));
2121   EXPECT_TRUE(
2122       CreateAndSetCookie(cm.get(), http_www_foo_.url(), "E=F;", options));
2123 
2124   CookieAccessResultList excluded_cookies = GetExcludedCookiesForURL(
2125       cm.get(), www_foo_foo_.url(), CookiePartitionKeyCollection());
2126   auto it = excluded_cookies.begin();
2127 
2128   ASSERT_TRUE(it != excluded_cookies.end());
2129   EXPECT_EQ("C", it->cookie.Name());
2130   EXPECT_EQ("/bar", it->cookie.Path());
2131   EXPECT_TRUE(it->access_result.status.HasExactlyExclusionReasonsForTesting(
2132       {CookieInclusionStatus::EXCLUDE_NOT_ON_PATH}));
2133 
2134   ASSERT_TRUE(++it == excluded_cookies.end());
2135 
2136   excluded_cookies = GetExcludedCookiesForURL(cm.get(), www_foo_bar_.url(),
2137                                               CookiePartitionKeyCollection());
2138   it = excluded_cookies.begin();
2139 
2140   ASSERT_TRUE(it != excluded_cookies.end());
2141   EXPECT_EQ("A", it->cookie.Name());
2142   EXPECT_EQ("/foo", it->cookie.Path());
2143   EXPECT_TRUE(it->access_result.status.HasExactlyExclusionReasonsForTesting(
2144       {CookieInclusionStatus::EXCLUDE_NOT_ON_PATH}));
2145 
2146   ASSERT_TRUE(++it == excluded_cookies.end());
2147 }
2148 
TEST_F(CookieMonsterTest,CookieSorting)2149 TEST_F(CookieMonsterTest, CookieSorting) {
2150   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2151 
2152   base::Time system_time = base::Time::Now();
2153   for (const char* cookie_line :
2154        {"B=B1; path=/", "B=B2; path=/foo", "B=B3; path=/foo/bar",
2155         "A=A1; path=/", "A=A2; path=/foo", "A=A3; path=/foo/bar"}) {
2156     EXPECT_TRUE(SetCookieWithSystemTime(cm.get(), http_www_foo_.url(),
2157                                         cookie_line, system_time));
2158     system_time += base::Milliseconds(100);
2159   }
2160 
2161   // Re-set cookie which should not change sort order, as the creation date
2162   // will be retained, as per RFC 6265 5.3.11.3.
2163   EXPECT_TRUE(SetCookieWithSystemTime(cm.get(), http_www_foo_.url(),
2164                                       "B=B3; path=/foo/bar", system_time));
2165 
2166   CookieList cookies = GetAllCookies(cm.get());
2167   ASSERT_EQ(6u, cookies.size());
2168   EXPECT_EQ("B3", cookies[0].Value());
2169   EXPECT_EQ("A3", cookies[1].Value());
2170   EXPECT_EQ("B2", cookies[2].Value());
2171   EXPECT_EQ("A2", cookies[3].Value());
2172   EXPECT_EQ("B1", cookies[4].Value());
2173   EXPECT_EQ("A1", cookies[5].Value());
2174 }
2175 
TEST_F(CookieMonsterTest,InheritCreationDate)2176 TEST_F(CookieMonsterTest, InheritCreationDate) {
2177   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2178 
2179   base::Time the_not_so_distant_past(base::Time::Now() - base::Seconds(1000));
2180   EXPECT_TRUE(SetCookieWithCreationTime(cm.get(), http_www_foo_.url(),
2181                                         "Name=Value; path=/",
2182                                         the_not_so_distant_past));
2183 
2184   CookieList cookies = GetAllCookies(cm.get());
2185   ASSERT_EQ(1u, cookies.size());
2186   EXPECT_EQ(the_not_so_distant_past, cookies[0].CreationDate());
2187   base::Time last_update = cookies[0].LastUpdateDate();
2188 
2189   // Overwrite the cookie with the same value, and verify that the creation date
2190   // is inherited. The update date isn't inherited though.
2191   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "Name=Value; path=/"));
2192 
2193   cookies = GetAllCookies(cm.get());
2194   ASSERT_EQ(1u, cookies.size());
2195   EXPECT_EQ(the_not_so_distant_past, cookies[0].CreationDate());
2196   // If this is flakey you many need to manually set the last update time.
2197   EXPECT_LT(last_update, cookies[0].LastUpdateDate());
2198   last_update = cookies[0].LastUpdateDate();
2199 
2200   // New value => new creation date.
2201   EXPECT_TRUE(
2202       SetCookie(cm.get(), http_www_foo_.url(), "Name=NewValue; path=/"));
2203 
2204   cookies = GetAllCookies(cm.get());
2205   ASSERT_EQ(1u, cookies.size());
2206   EXPECT_NE(the_not_so_distant_past, cookies[0].CreationDate());
2207   // If this is flakey you many need to manually set the last update time.
2208   EXPECT_LT(last_update, cookies[0].LastUpdateDate());
2209 }
2210 
2211 // Check that GetAllCookiesForURL() does not return expired cookies and deletes
2212 // them.
TEST_F(CookieMonsterTest,DeleteExpiredCookiesOnGet)2213 TEST_F(CookieMonsterTest, DeleteExpiredCookiesOnGet) {
2214   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2215 
2216   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "A=B;"));
2217 
2218   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "C=D;"));
2219 
2220   CookieList cookies = GetAllCookiesForURL(cm.get(), http_www_foo_.url());
2221   EXPECT_EQ(2u, cookies.size());
2222 
2223   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(),
2224                         "C=D; expires=Thu, 01-Jan-1970 00:00:00 GMT"));
2225 
2226   cookies = GetAllCookiesForURL(cm.get(), http_www_foo_.url());
2227   EXPECT_EQ(1u, cookies.size());
2228 
2229   // Test partitioned cookies. They should exhibit the same behavior but are
2230   // stored in a different data structure internally.
2231   auto cookie_partition_key =
2232       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
2233 
2234   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2235                         "__Host-A=B; secure; path=/; partitioned",
2236                         cookie_partition_key));
2237   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2238                         "__Host-C=D; secure; path=/; partitioned",
2239                         cookie_partition_key));
2240 
2241   cookies =
2242       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
2243                           CookiePartitionKeyCollection(cookie_partition_key));
2244   EXPECT_EQ(2u, cookies.size());
2245 
2246   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2247                         "__Host-C=D; secure; path=/; partitioned; expires=Thu, "
2248                         "01-Jan-1970 00:00:00 GMT",
2249                         cookie_partition_key));
2250 
2251   cookies =
2252       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
2253                           CookiePartitionKeyCollection(cookie_partition_key));
2254   EXPECT_EQ(1u, cookies.size());
2255 }
2256 
2257 // Test that cookie expiration works correctly when a cookie expires because
2258 // time elapses.
TEST_F(CookieMonsterTest,DeleteExpiredCookiesAfterTimeElapsed)2259 TEST_F(CookieMonsterTest, DeleteExpiredCookiesAfterTimeElapsed) {
2260   auto cm = std::make_unique<CookieMonster>(
2261       /*store=*/nullptr, net::NetLog::Get());
2262 
2263   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2264                         "__Host-A=B; secure; path=/",
2265                         /*cookie_partition_key=*/absl::nullopt));
2266   // Set a cookie with a Max-Age. Since we only parse integers for this
2267   // attribute, 1 second is the minimum allowable time.
2268   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2269                         "__Host-C=D; secure; path=/; max-age=1",
2270                         /*cookie_partition_key=*/absl::nullopt));
2271 
2272   CookieList cookies = GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
2273                                            CookiePartitionKeyCollection());
2274   EXPECT_EQ(2u, cookies.size());
2275 
2276   // Sleep for entire Max-Age of the second cookie.
2277   base::PlatformThread::Sleep(base::Seconds(1));
2278 
2279   cookies = GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
2280                                 CookiePartitionKeyCollection());
2281   EXPECT_EQ(1u, cookies.size());
2282   EXPECT_EQ("__Host-A", cookies[0].Name());
2283 }
2284 
TEST_F(CookieMonsterTest,DeleteExpiredPartitionedCookiesAfterTimeElapsed)2285 TEST_F(CookieMonsterTest, DeleteExpiredPartitionedCookiesAfterTimeElapsed) {
2286   auto cm = std::make_unique<CookieMonster>(
2287       /*store=*/nullptr, net::NetLog::Get());
2288   auto cookie_partition_key =
2289       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
2290 
2291   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2292                         "__Host-A=B; secure; path=/; partitioned",
2293                         cookie_partition_key));
2294   // Set a cookie with a Max-Age. Since we only parse integers for this
2295   // attribute, 1 second is the minimum allowable time.
2296   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2297                         "__Host-C=D; secure; path=/; partitioned; max-age=1",
2298                         cookie_partition_key));
2299 
2300   CookieList cookies =
2301       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
2302                           CookiePartitionKeyCollection(cookie_partition_key));
2303   EXPECT_EQ(2u, cookies.size());
2304 
2305   // Sleep for entire Max-Age of the second cookie.
2306   base::PlatformThread::Sleep(base::Seconds(1));
2307 
2308   cookies =
2309       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
2310                           CookiePartitionKeyCollection(cookie_partition_key));
2311   EXPECT_EQ(1u, cookies.size());
2312   EXPECT_EQ("__Host-A", cookies[0].Name());
2313 }
2314 
TEST_F(CookieMonsterTest,DeleteExpiredAfterTimeElapsed_GetAllCookies)2315 TEST_F(CookieMonsterTest, DeleteExpiredAfterTimeElapsed_GetAllCookies) {
2316   auto cm = std::make_unique<CookieMonster>(
2317       /*store=*/nullptr, net::NetLog::Get());
2318 
2319   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2320                         "__Host-A=B; secure; path=/",
2321                         /*cookie_partition_key=*/absl::nullopt));
2322   // Set a cookie with a Max-Age. Since we only parse integers for this
2323   // attribute, 1 second is the minimum allowable time.
2324   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2325                         "__Host-C=D; secure; path=/; max-age=1",
2326                         /*cookie_partition_key=*/absl::nullopt));
2327 
2328   GetAllCookiesCallback get_cookies_callback1;
2329   cm->GetAllCookiesAsync(get_cookies_callback1.MakeCallback());
2330   get_cookies_callback1.WaitUntilDone();
2331   ASSERT_EQ(2u, get_cookies_callback1.cookies().size());
2332 
2333   // Sleep for entire Max-Age of the second cookie.
2334   base::PlatformThread::Sleep(base::Seconds(1));
2335 
2336   GetAllCookiesCallback get_cookies_callback2;
2337   cm->GetAllCookiesAsync(get_cookies_callback2.MakeCallback());
2338   get_cookies_callback2.WaitUntilDone();
2339 
2340   ASSERT_EQ(1u, get_cookies_callback2.cookies().size());
2341   EXPECT_EQ("__Host-A", get_cookies_callback2.cookies()[0].Name());
2342 }
2343 
TEST_F(CookieMonsterTest,DeleteExpiredPartitionedCookiesAfterTimeElapsed_GetAllCookies)2344 TEST_F(CookieMonsterTest,
2345        DeleteExpiredPartitionedCookiesAfterTimeElapsed_GetAllCookies) {
2346   auto cm = std::make_unique<CookieMonster>(
2347       /*store=*/nullptr, net::NetLog::Get());
2348   auto cookie_partition_key =
2349       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
2350 
2351   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2352                         "__Host-A=B; secure; path=/; partitioned",
2353                         cookie_partition_key));
2354   // Set a cookie with a Max-Age. Since we only parse integers for this
2355   // attribute, 1 second is the minimum allowable time.
2356   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2357                         "__Host-C=D; secure; path=/; max-age=1; partitioned",
2358                         cookie_partition_key));
2359 
2360   GetAllCookiesCallback get_cookies_callback1;
2361   cm->GetAllCookiesAsync(get_cookies_callback1.MakeCallback());
2362   get_cookies_callback1.WaitUntilDone();
2363   ASSERT_EQ(2u, get_cookies_callback1.cookies().size());
2364 
2365   // Sleep for entire Max-Age of the second cookie.
2366   base::PlatformThread::Sleep(base::Seconds(1));
2367 
2368   GetAllCookiesCallback get_cookies_callback2;
2369   cm->GetAllCookiesAsync(get_cookies_callback2.MakeCallback());
2370   get_cookies_callback2.WaitUntilDone();
2371 
2372   ASSERT_EQ(1u, get_cookies_callback2.cookies().size());
2373   EXPECT_EQ("__Host-A", get_cookies_callback2.cookies()[0].Name());
2374 }
2375 
TEST_F(CookieMonsterTest,DeletePartitionedCookie)2376 TEST_F(CookieMonsterTest, DeletePartitionedCookie) {
2377   auto cm = std::make_unique<CookieMonster>(
2378       /*store=*/nullptr, net::NetLog::Get());
2379   auto cookie_partition_key =
2380       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
2381 
2382   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2383                         "__Host-A=B; secure; path=/; partitioned",
2384                         cookie_partition_key));
2385   // Set another partitioned and an unpartitioned cookie and make sure they are
2386   // unaffected.
2387   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2388                         "__Host-C=D; secure; path=/; partitioned",
2389                         cookie_partition_key));
2390   EXPECT_TRUE(SetCookie(cm.get(), https_www_bar_.url(),
2391                         "__Host-E=F; secure; path=/", absl::nullopt));
2392 
2393   auto cookie = CanonicalCookie::Create(
2394       https_www_bar_.url(), "__Host-A=B; secure; path=/; partitioned",
2395       /*creation_time=*/Time::Now(), /*server_time=*/absl::nullopt,
2396       cookie_partition_key);
2397   ASSERT_TRUE(cookie);
2398 
2399   ResultSavingCookieCallback<unsigned int> delete_callback;
2400   cm->DeleteCanonicalCookieAsync(*cookie, delete_callback.MakeCallback());
2401   delete_callback.WaitUntilDone();
2402 
2403   CookieList cookies =
2404       GetAllCookiesForURL(cm.get(), https_www_bar_.url(),
2405                           CookiePartitionKeyCollection(cookie_partition_key));
2406   EXPECT_EQ(2u, cookies.size());
2407   EXPECT_EQ(cookies[0].Name(), "__Host-C");
2408   EXPECT_EQ(cookies[1].Name(), "__Host-E");
2409 }
2410 
2411 // Tests importing from a persistent cookie store that contains duplicate
2412 // equivalent cookies. This situation should be handled by removing the
2413 // duplicate cookie (both from the in-memory cache, and from the backing store).
2414 //
2415 // This is a regression test for: http://crbug.com/17855.
TEST_F(CookieMonsterTest,DontImportDuplicateCookies)2416 TEST_F(CookieMonsterTest, DontImportDuplicateCookies) {
2417   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
2418 
2419   // We will fill some initial cookies into the PersistentCookieStore,
2420   // to simulate a database with 4 duplicates.  Note that we need to
2421   // be careful not to have any duplicate creation times at all (as it's a
2422   // violation of a CookieMonster invariant) even if Time::Now() doesn't
2423   // move between calls.
2424   std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies;
2425 
2426   // Insert 4 cookies with name "X" on path "/", with varying creation
2427   // dates. We expect only the most recent one to be preserved following
2428   // the import.
2429 
2430   AddCookieToList(GURL("http://www.foo.com"),
2431                   "X=1; path=/" + FutureCookieExpirationString(),
2432                   Time::Now() + base::Days(3), &initial_cookies);
2433 
2434   AddCookieToList(GURL("http://www.foo.com"),
2435                   "X=2; path=/" + FutureCookieExpirationString(),
2436                   Time::Now() + base::Days(1), &initial_cookies);
2437 
2438   // ===> This one is the WINNER (biggest creation time).  <====
2439   AddCookieToList(GURL("http://www.foo.com"),
2440                   "X=3; path=/" + FutureCookieExpirationString(),
2441                   Time::Now() + base::Days(4), &initial_cookies);
2442 
2443   AddCookieToList(GURL("http://www.foo.com"),
2444                   "X=4; path=/" + FutureCookieExpirationString(), Time::Now(),
2445                   &initial_cookies);
2446 
2447   // Insert 2 cookies with name "X" on path "/2", with varying creation
2448   // dates. We expect only the most recent one to be preserved the import.
2449 
2450   // ===> This one is the WINNER (biggest creation time).  <====
2451   AddCookieToList(GURL("http://www.foo.com"),
2452                   "X=a1; path=/2" + FutureCookieExpirationString(),
2453                   Time::Now() + base::Days(9), &initial_cookies);
2454 
2455   AddCookieToList(GURL("http://www.foo.com"),
2456                   "X=a2; path=/2" + FutureCookieExpirationString(),
2457                   Time::Now() + base::Days(2), &initial_cookies);
2458 
2459   // Insert 1 cookie with name "Y" on path "/".
2460   AddCookieToList(GURL("http://www.foo.com"),
2461                   "Y=a; path=/" + FutureCookieExpirationString(),
2462                   Time::Now() + base::Days(10), &initial_cookies);
2463 
2464   // Inject our initial cookies into the mock PersistentCookieStore.
2465   store->SetLoadExpectation(true, std::move(initial_cookies));
2466 
2467   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2468 
2469   // Verify that duplicates were not imported for path "/".
2470   // (If this had failed, GetCookies() would have also returned X=1, X=2, X=4).
2471   EXPECT_EQ("X=3; Y=a", GetCookies(cm.get(), GURL("http://www.foo.com/")));
2472 
2473   // Verify that same-named cookie on a different path ("/x2") didn't get
2474   // messed up.
2475   EXPECT_EQ("X=a1; X=3; Y=a",
2476             GetCookies(cm.get(), GURL("http://www.foo.com/2/x")));
2477 
2478   // Verify that the PersistentCookieStore was told to kill its 4 duplicates.
2479   ASSERT_EQ(4u, store->commands().size());
2480   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[0].type);
2481   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type);
2482   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[2].type);
2483   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[3].type);
2484 }
2485 
TEST_F(CookieMonsterTest,DontImportDuplicateCookies_PartitionedCookies)2486 TEST_F(CookieMonsterTest, DontImportDuplicateCookies_PartitionedCookies) {
2487   std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies;
2488 
2489   auto cookie_partition_key =
2490       CookiePartitionKey::FromURLForTesting(GURL("https://www.foo.com"));
2491   GURL cookie_url("https://www.bar.com");
2492 
2493   // Insert 3 partitioned cookies with same name, partition key, and path.
2494 
2495   // ===> This one is the WINNER (biggest creation time).  <====
2496   auto cc = CanonicalCookie::Create(
2497       cookie_url, "__Host-Z=a; Secure; Path=/; Partitioned; Max-Age=3456000",
2498       Time::Now() + base::Days(2), absl::nullopt, cookie_partition_key);
2499   initial_cookies.push_back(std::move(cc));
2500 
2501   cc = CanonicalCookie::Create(
2502       cookie_url, "__Host-Z=b; Secure; Path=/; Partitioned; Max-Age=3456000",
2503       Time::Now(), absl::nullopt, cookie_partition_key);
2504   initial_cookies.push_back(std::move(cc));
2505 
2506   cc = CanonicalCookie::Create(
2507       cookie_url, "__Host-Z=c; Secure; Path=/; Partitioned; Max-Age=3456000",
2508       Time::Now() + base::Days(1), absl::nullopt, cookie_partition_key);
2509   initial_cookies.push_back(std::move(cc));
2510 
2511   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
2512   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2513 
2514   store->SetLoadExpectation(true, std::move(initial_cookies));
2515 
2516   EXPECT_EQ("__Host-Z=a",
2517             GetCookies(cm.get(), GURL("https://www.bar.com/"),
2518                        CookiePartitionKeyCollection(cookie_partition_key)));
2519 
2520   // Verify that the PersistentCookieStore was told to kill the 2
2521   // duplicates.
2522   ASSERT_EQ(2u, store->commands().size());
2523   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[0].type);
2524   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type);
2525 }
2526 
2527 // Tests importing from a persistent cookie store that contains cookies
2528 // with duplicate creation times.  This is OK now, but it still interacts
2529 // with the de-duplication algorithm.
2530 //
2531 // This is a regression test for: http://crbug.com/43188.
TEST_F(CookieMonsterTest,ImportDuplicateCreationTimes)2532 TEST_F(CookieMonsterTest, ImportDuplicateCreationTimes) {
2533   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
2534 
2535   Time now(Time::Now());
2536   Time earlier(now - base::Days(1));
2537 
2538   // Insert 8 cookies, four with the current time as creation times, and
2539   // four with the earlier time as creation times.  We should only get
2540   // two cookies remaining, but which two (other than that there should
2541   // be one from each set) will be random.
2542   std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies;
2543   AddCookieToList(GURL("http://www.foo.com"), "X=1; path=/", now,
2544                   &initial_cookies);
2545   AddCookieToList(GURL("http://www.foo.com"), "X=2; path=/", now,
2546                   &initial_cookies);
2547   AddCookieToList(GURL("http://www.foo.com"), "X=3; path=/", now,
2548                   &initial_cookies);
2549   AddCookieToList(GURL("http://www.foo.com"), "X=4; path=/", now,
2550                   &initial_cookies);
2551 
2552   AddCookieToList(GURL("http://www.foo.com"), "Y=1; path=/", earlier,
2553                   &initial_cookies);
2554   AddCookieToList(GURL("http://www.foo.com"), "Y=2; path=/", earlier,
2555                   &initial_cookies);
2556   AddCookieToList(GURL("http://www.foo.com"), "Y=3; path=/", earlier,
2557                   &initial_cookies);
2558   AddCookieToList(GURL("http://www.foo.com"), "Y=4; path=/", earlier,
2559                   &initial_cookies);
2560 
2561   // Inject our initial cookies into the mock PersistentCookieStore.
2562   store->SetLoadExpectation(true, std::move(initial_cookies));
2563 
2564   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2565 
2566   CookieList list(GetAllCookies(cm.get()));
2567   EXPECT_EQ(2U, list.size());
2568   // Confirm that we have one of each.
2569   std::string name1(list[0].Name());
2570   std::string name2(list[1].Name());
2571   EXPECT_TRUE(name1 == "X" || name2 == "X");
2572   EXPECT_TRUE(name1 == "Y" || name2 == "Y");
2573   EXPECT_NE(name1, name2);
2574 }
2575 
TEST_F(CookieMonsterTest,ImportDuplicateCreationTimes_PartitionedCookies)2576 TEST_F(CookieMonsterTest, ImportDuplicateCreationTimes_PartitionedCookies) {
2577   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
2578 
2579   Time now(Time::Now());
2580   Time earlier(now - base::Days(1));
2581 
2582   GURL cookie_url("https://www.foo.com");
2583   auto cookie_partition_key =
2584       CookiePartitionKey::FromURLForTesting(GURL("https://www.bar.com"));
2585 
2586   // Insert 6 cookies, four with the current time as creation times, and
2587   // four with the earlier time as creation times.  We should only get
2588   // two cookies remaining, but which two (other than that there should
2589   // be one from each set) will be random.
2590 
2591   std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies;
2592   auto cc = CanonicalCookie::Create(
2593       cookie_url, "__Host-X=1; Secure; Path=/; Partitioned; Max-Age=3456000",
2594       now, absl::nullopt, cookie_partition_key);
2595   initial_cookies.push_back(std::move(cc));
2596   cc = CanonicalCookie::Create(
2597       cookie_url, "__Host-X=2; Secure; Path=/; Partitioned; Max-Age=3456000",
2598       now, absl::nullopt, cookie_partition_key);
2599   initial_cookies.push_back(std::move(cc));
2600   cc = CanonicalCookie::Create(
2601       cookie_url, "__Host-X=3; Secure; Path=/; Partitioned; Max-Age=3456000",
2602       now, absl::nullopt, cookie_partition_key);
2603   initial_cookies.push_back(std::move(cc));
2604 
2605   cc = CanonicalCookie::Create(
2606       cookie_url, "__Host-Y=1; Secure; Path=/; Partitioned; Max-Age=3456000",
2607       earlier, absl::nullopt, cookie_partition_key);
2608   initial_cookies.push_back(std::move(cc));
2609   cc = CanonicalCookie::Create(
2610       cookie_url, "__Host-Y=2; Secure; Path=/; Partitioned; Max-Age=3456000",
2611       earlier, absl::nullopt, cookie_partition_key);
2612   initial_cookies.push_back(std::move(cc));
2613   cc = CanonicalCookie::Create(
2614       cookie_url, "__Host-Y=3; Secure; Path=/; Partitioned; Max-Age=3456000",
2615       earlier, absl::nullopt, cookie_partition_key);
2616   initial_cookies.push_back(std::move(cc));
2617 
2618   // Inject our initial cookies into the mock PersistentCookieStore.
2619   store->SetLoadExpectation(true, std::move(initial_cookies));
2620 
2621   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2622 
2623   CookieList list(GetAllCookies(cm.get()));
2624   EXPECT_EQ(2U, list.size());
2625   // Confirm that we have one of each.
2626   std::string name1(list[0].Name());
2627   std::string name2(list[1].Name());
2628   EXPECT_TRUE(name1 == "__Host-X" || name2 == "__Host-X");
2629   EXPECT_TRUE(name1 == "__Host-Y" || name2 == "__Host-Y");
2630   EXPECT_NE(name1, name2);
2631 }
2632 
TEST_F(CookieMonsterTest,PredicateSeesAllCookies)2633 TEST_F(CookieMonsterTest, PredicateSeesAllCookies) {
2634   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2635 
2636   const base::Time now = PopulateCmForPredicateCheck(cm.get());
2637   // We test that we can see all cookies with |delete_info|. This includes
2638   // host, http_only, host secure, and all domain cookies.
2639   CookieDeletionInfo delete_info(base::Time(), now);
2640   delete_info.value_for_testing = "A";
2641 
2642   EXPECT_EQ(9u, DeleteAllMatchingInfo(cm.get(), std::move(delete_info)));
2643 
2644   EXPECT_EQ("dom_2=B; dom_3=C; host_3=C",
2645             GetCookies(cm.get(), GURL(kTopLevelDomainPlus3)));
2646   EXPECT_EQ("dom_2=B; host_2=B; sec_host=B",
2647             GetCookies(cm.get(), GURL(kTopLevelDomainPlus2Secure)));
2648   EXPECT_EQ("", GetCookies(cm.get(), GURL(kTopLevelDomainPlus1)));
2649   EXPECT_EQ("dom_path_2=B; host_path_2=B; dom_2=B; host_2=B; sec_host=B",
2650             GetCookies(cm.get(), GURL(kTopLevelDomainPlus2Secure +
2651                                       std::string("/dir1/dir2/xxx"))));
2652   EXPECT_EQ("dom_2=B; host_2=B; sec_host=B; __Host-pc_2=B",
2653             GetCookies(cm.get(), GURL(kTopLevelDomainPlus2Secure),
2654                        CookiePartitionKeyCollection(
2655                            CookiePartitionKey::FromURLForTesting(
2656                                GURL(kTopLevelDomainPlus1)))));
2657 }
2658 
2659 // Mainly a test of GetEffectiveDomain, or more specifically, of the
2660 // expected behavior of GetEffectiveDomain within the CookieMonster.
TEST_F(CookieMonsterTest,GetKey)2661 TEST_F(CookieMonsterTest, GetKey) {
2662   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2663 
2664   // This test is really only interesting if GetKey() actually does something.
2665   EXPECT_EQ("foo.com", cm->GetKey("www.foo.com"));
2666   EXPECT_EQ("google.izzie", cm->GetKey("www.google.izzie"));
2667   EXPECT_EQ("google.izzie", cm->GetKey(".google.izzie"));
2668   EXPECT_EQ("bbc.co.uk", cm->GetKey("bbc.co.uk"));
2669   EXPECT_EQ("bbc.co.uk", cm->GetKey("a.b.c.d.bbc.co.uk"));
2670   EXPECT_EQ("apple.com", cm->GetKey("a.b.c.d.apple.com"));
2671   EXPECT_EQ("apple.izzie", cm->GetKey("a.b.c.d.apple.izzie"));
2672 
2673   // Cases where the effective domain is null, so we use the host
2674   // as the key.
2675   EXPECT_EQ("co.uk", cm->GetKey("co.uk"));
2676   const std::string extension_name("iehocdgbbocmkdidlbnnfbmbinnahbae");
2677   EXPECT_EQ(extension_name, cm->GetKey(extension_name));
2678   EXPECT_EQ("com", cm->GetKey("com"));
2679   EXPECT_EQ("hostalias", cm->GetKey("hostalias"));
2680   EXPECT_EQ("localhost", cm->GetKey("localhost"));
2681 }
2682 
2683 // Test that cookies transfer from/to the backing store correctly.
2684 // TODO(crbug.com/1225444): Include partitioned cookies in this test when we
2685 // start saving them in the persistent store.
TEST_F(CookieMonsterTest,BackingStoreCommunication)2686 TEST_F(CookieMonsterTest, BackingStoreCommunication) {
2687   // Store details for cookies transforming through the backing store interface.
2688 
2689   base::Time current(base::Time::Now());
2690   auto store = base::MakeRefCounted<MockSimplePersistentCookieStore>();
2691   base::Time expires(base::Time::Now() + base::Seconds(100));
2692 
2693   const CookiesInputInfo input_info[] = {
2694       {GURL("https://a.b.foo.com"), "a", "1", "a.b.foo.com", "/path/to/cookie",
2695        expires, true /* secure */, false, CookieSameSite::NO_RESTRICTION,
2696        COOKIE_PRIORITY_DEFAULT, false},
2697       {GURL("https://www.foo.com"), "b", "2", ".foo.com", "/path/from/cookie",
2698        expires + base::Seconds(10), true, true, CookieSameSite::NO_RESTRICTION,
2699        COOKIE_PRIORITY_DEFAULT, true},
2700       {GURL("https://foo.com"), "c", "3", "foo.com", "/another/path/to/cookie",
2701        base::Time::Now() + base::Seconds(100), false, false,
2702        CookieSameSite::STRICT_MODE, COOKIE_PRIORITY_DEFAULT, false}};
2703   const int INPUT_DELETE = 1;
2704 
2705   // Create new cookies and flush them to the store.
2706   {
2707     auto cmout =
2708         std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2709     for (const auto& cookie : input_info) {
2710       EXPECT_TRUE(SetCanonicalCookie(
2711           cmout.get(),
2712           CanonicalCookie::CreateUnsafeCookieForTesting(
2713               cookie.name, cookie.value, cookie.domain, cookie.path,
2714               base::Time(), cookie.expiration_time, base::Time(), base::Time(),
2715               cookie.secure, cookie.http_only, cookie.same_site,
2716               cookie.priority, cookie.same_party),
2717           cookie.url, true /*modify_httponly*/));
2718     }
2719 
2720     EXPECT_TRUE(FindAndDeleteCookie(cmout.get(),
2721                                     input_info[INPUT_DELETE].domain,
2722                                     input_info[INPUT_DELETE].name));
2723   }
2724 
2725   // Create a new cookie monster and make sure that everything is correct
2726   {
2727     auto cmin =
2728         std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2729     CookieList cookies(GetAllCookies(cmin.get()));
2730     ASSERT_EQ(2u, cookies.size());
2731     // Ordering is path length, then creation time.  So second cookie
2732     // will come first, and we need to swap them.
2733     std::swap(cookies[0], cookies[1]);
2734     for (int output_index = 0; output_index < 2; output_index++) {
2735       int input_index = output_index * 2;
2736       const CookiesInputInfo* input = &input_info[input_index];
2737       const CanonicalCookie* output = &cookies[output_index];
2738 
2739       EXPECT_EQ(input->name, output->Name());
2740       EXPECT_EQ(input->value, output->Value());
2741       EXPECT_EQ(input->url.host(), output->Domain());
2742       EXPECT_EQ(input->path, output->Path());
2743       EXPECT_LE(current.ToInternalValue(),
2744                 output->CreationDate().ToInternalValue());
2745       EXPECT_EQ(input->secure, output->IsSecure());
2746       EXPECT_EQ(input->http_only, output->IsHttpOnly());
2747       EXPECT_EQ(input->same_site, output->SameSite());
2748       EXPECT_TRUE(output->IsPersistent());
2749       EXPECT_EQ(input->expiration_time.ToInternalValue(),
2750                 output->ExpiryDate().ToInternalValue());
2751     }
2752   }
2753 }
2754 
TEST_F(CookieMonsterTest,RestoreDifferentCookieSameCreationTime)2755 TEST_F(CookieMonsterTest, RestoreDifferentCookieSameCreationTime) {
2756   // Test that we can restore different cookies with duplicate creation times.
2757   base::Time current(base::Time::Now());
2758   scoped_refptr<MockPersistentCookieStore> store =
2759       base::MakeRefCounted<MockPersistentCookieStore>();
2760 
2761   {
2762     CookieMonster cmout(store.get(), net::NetLog::Get());
2763     GURL url("http://www.example.com/");
2764     EXPECT_TRUE(
2765         SetCookieWithCreationTime(&cmout, url, "A=1; max-age=600", current));
2766     EXPECT_TRUE(
2767         SetCookieWithCreationTime(&cmout, url, "B=2; max-age=600", current));
2768   }
2769 
2770   // Play back the cookies into store 2.
2771   scoped_refptr<MockPersistentCookieStore> store2 =
2772       base::MakeRefCounted<MockPersistentCookieStore>();
2773   std::vector<std::unique_ptr<CanonicalCookie>> load_expectation;
2774   EXPECT_EQ(2u, store->commands().size());
2775   for (const CookieStoreCommand& command : store->commands()) {
2776     ASSERT_EQ(command.type, CookieStoreCommand::ADD);
2777     load_expectation.push_back(
2778         std::make_unique<CanonicalCookie>(command.cookie));
2779   }
2780   store2->SetLoadExpectation(true, std::move(load_expectation));
2781 
2782   // Now read them in. Should get two cookies, not one.
2783   {
2784     CookieMonster cmin(store2.get(), net::NetLog::Get());
2785     CookieList cookies(GetAllCookies(&cmin));
2786     ASSERT_EQ(2u, cookies.size());
2787   }
2788 }
2789 
TEST_F(CookieMonsterTest,CookieListOrdering)2790 TEST_F(CookieMonsterTest, CookieListOrdering) {
2791   // Put a random set of cookies into a monster and make sure
2792   // they're returned in the right order.
2793   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
2794 
2795   EXPECT_TRUE(
2796       SetCookie(cm.get(), GURL("http://d.c.b.a.foo.com/aa/x.html"), "c=1"));
2797   EXPECT_TRUE(SetCookie(cm.get(), GURL("http://b.a.foo.com/aa/bb/cc/x.html"),
2798                         "d=1; domain=b.a.foo.com"));
2799   EXPECT_TRUE(SetCookie(cm.get(), GURL("http://b.a.foo.com/aa/bb/cc/x.html"),
2800                         "a=4; domain=b.a.foo.com"));
2801   EXPECT_TRUE(SetCookie(cm.get(), GURL("http://c.b.a.foo.com/aa/bb/cc/x.html"),
2802                         "e=1; domain=c.b.a.foo.com"));
2803   EXPECT_TRUE(
2804       SetCookie(cm.get(), GURL("http://d.c.b.a.foo.com/aa/bb/x.html"), "b=1"));
2805   EXPECT_TRUE(SetCookie(cm.get(), GURL("http://news.bbc.co.uk/midpath/x.html"),
2806                         "g=10"));
2807   {
2808     unsigned int i = 0;
2809     CookieList cookies(GetAllCookiesForURL(
2810         cm.get(), GURL("http://d.c.b.a.foo.com/aa/bb/cc/dd")));
2811     ASSERT_EQ(5u, cookies.size());
2812     EXPECT_EQ("d", cookies[i++].Name());
2813     EXPECT_EQ("a", cookies[i++].Name());
2814     EXPECT_EQ("e", cookies[i++].Name());
2815     EXPECT_EQ("b", cookies[i++].Name());
2816     EXPECT_EQ("c", cookies[i++].Name());
2817   }
2818 
2819   {
2820     unsigned int i = 0;
2821     CookieList cookies(GetAllCookies(cm.get()));
2822     ASSERT_EQ(6u, cookies.size());
2823     EXPECT_EQ("d", cookies[i++].Name());
2824     EXPECT_EQ("a", cookies[i++].Name());
2825     EXPECT_EQ("e", cookies[i++].Name());
2826     EXPECT_EQ("g", cookies[i++].Name());
2827     EXPECT_EQ("b", cookies[i++].Name());
2828     EXPECT_EQ("c", cookies[i++].Name());
2829   }
2830 }
2831 
2832 // These garbage collection tests and CookieMonstertest.TestGCTimes (in
2833 // cookie_monster_perftest.cc) are somewhat complementary.  These tests probe
2834 // for whether garbage collection always happens when it should (i.e. that we
2835 // actually get rid of cookies when we should).  The perftest is probing for
2836 // whether garbage collection happens when it shouldn't.  See comments
2837 // before that test for more details.
2838 
2839 // Check to make sure that a whole lot of recent cookies doesn't get rid of
2840 // anything after garbage collection is checked for.
TEST_F(CookieMonsterTest,GarbageCollectionKeepsRecentEphemeralCookies)2841 TEST_F(CookieMonsterTest, GarbageCollectionKeepsRecentEphemeralCookies) {
2842   std::unique_ptr<CookieMonster> cm(
2843       CreateMonsterForGC(CookieMonster::kMaxCookies * 2 /* num_cookies */));
2844   EXPECT_EQ(CookieMonster::kMaxCookies * 2, GetAllCookies(cm.get()).size());
2845   // Will trigger GC.
2846   SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2");
2847   EXPECT_EQ(CookieMonster::kMaxCookies * 2 + 1, GetAllCookies(cm.get()).size());
2848 }
2849 
2850 // A whole lot of recent cookies; GC shouldn't happen.
TEST_F(CookieMonsterTest,GarbageCollectionKeepsRecentCookies)2851 TEST_F(CookieMonsterTest, GarbageCollectionKeepsRecentCookies) {
2852   std::unique_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC(
2853       CookieMonster::kMaxCookies * 2 /* num_cookies */, 0 /* num_old_cookies */,
2854       0, 0, CookieMonster::kSafeFromGlobalPurgeDays * 2);
2855   EXPECT_EQ(CookieMonster::kMaxCookies * 2, GetAllCookies(cm.get()).size());
2856   // Will trigger GC.
2857   SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2");
2858   EXPECT_EQ(CookieMonster::kMaxCookies * 2 + 1, GetAllCookies(cm.get()).size());
2859 }
2860 
2861 // Test case where there are more than kMaxCookies - kPurgeCookies recent
2862 // cookies. All old cookies should be garbage collected, all recent cookies
2863 // kept.
TEST_F(CookieMonsterTest,GarbageCollectionKeepsOnlyRecentCookies)2864 TEST_F(CookieMonsterTest, GarbageCollectionKeepsOnlyRecentCookies) {
2865   std::unique_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC(
2866       CookieMonster::kMaxCookies * 2 /* num_cookies */,
2867       CookieMonster::kMaxCookies / 2 /* num_old_cookies */, 0, 0,
2868       CookieMonster::kSafeFromGlobalPurgeDays * 2);
2869   EXPECT_EQ(CookieMonster::kMaxCookies * 2, GetAllCookies(cm.get()).size());
2870   // Will trigger GC.
2871   SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2");
2872   EXPECT_EQ(CookieMonster::kMaxCookies * 2 - CookieMonster::kMaxCookies / 2 + 1,
2873             GetAllCookies(cm.get()).size());
2874 }
2875 
2876 // Test case where there are exactly kMaxCookies - kPurgeCookies recent cookies.
2877 // All old cookies should be deleted.
TEST_F(CookieMonsterTest,GarbageCollectionExactlyAllOldCookiesDeleted)2878 TEST_F(CookieMonsterTest, GarbageCollectionExactlyAllOldCookiesDeleted) {
2879   std::unique_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC(
2880       CookieMonster::kMaxCookies * 2 /* num_cookies */,
2881       CookieMonster::kMaxCookies + CookieMonster::kPurgeCookies +
2882           1 /* num_old_cookies */,
2883       0, 0, CookieMonster::kSafeFromGlobalPurgeDays * 2);
2884   EXPECT_EQ(CookieMonster::kMaxCookies * 2, GetAllCookies(cm.get()).size());
2885   // Will trigger GC.
2886   SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2");
2887   EXPECT_EQ(CookieMonster::kMaxCookies - CookieMonster::kPurgeCookies,
2888             GetAllCookies(cm.get()).size());
2889 }
2890 
2891 // Test case where there are less than kMaxCookies - kPurgeCookies recent
2892 // cookies. Enough old cookies should be deleted to reach kMaxCookies -
2893 // kPurgeCookies total cookies, but no more. Some old cookies should be kept.
TEST_F(CookieMonsterTest,GarbageCollectionTriggers5)2894 TEST_F(CookieMonsterTest, GarbageCollectionTriggers5) {
2895   std::unique_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC(
2896       CookieMonster::kMaxCookies * 2 /* num_cookies */,
2897       CookieMonster::kMaxCookies * 3 / 2 /* num_old_cookies */, 0, 0,
2898       CookieMonster::kSafeFromGlobalPurgeDays * 2);
2899   EXPECT_EQ(CookieMonster::kMaxCookies * 2, GetAllCookies(cm.get()).size());
2900   // Will trigger GC.
2901   SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2");
2902   EXPECT_EQ(CookieMonster::kMaxCookies - CookieMonster::kPurgeCookies,
2903             GetAllCookies(cm.get()).size());
2904 }
2905 
2906 // Tests garbage collection when there are only secure cookies.
2907 // See https://crbug/730000
TEST_F(CookieMonsterTest,GarbageCollectWithSecureCookiesOnly)2908 TEST_F(CookieMonsterTest, GarbageCollectWithSecureCookiesOnly) {
2909   // Create a CookieMonster at its cookie limit. A bit confusing, but the second
2910   // number is a subset of the first number.
2911   std::unique_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC(
2912       CookieMonster::kMaxCookies /* num_secure_cookies */,
2913       CookieMonster::kMaxCookies /* num_old_secure_cookies */,
2914       0 /* num_non_secure_cookies */, 0 /* num_old_non_secure_cookies */,
2915       CookieMonster::kSafeFromGlobalPurgeDays * 2 /* days_old */);
2916   EXPECT_EQ(CookieMonster::kMaxCookies, GetAllCookies(cm.get()).size());
2917 
2918   // Trigger purge with a secure cookie (So there are still no insecure
2919   // cookies).
2920   SetCookie(cm.get(), GURL("https://newdomain.com"), "b=2; Secure");
2921   EXPECT_EQ(CookieMonster::kMaxCookies - CookieMonster::kPurgeCookies,
2922             GetAllCookies(cm.get()).size());
2923 }
2924 
2925 // Tests that if the main load event happens before the loaded event for a
2926 // particular key, the tasks for that key run first.
TEST_F(CookieMonsterTest,WhileLoadingLoadCompletesBeforeKeyLoadCompletes)2927 TEST_F(CookieMonsterTest, WhileLoadingLoadCompletesBeforeKeyLoadCompletes) {
2928   const GURL kUrl = GURL(kTopLevelDomainPlus1);
2929 
2930   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
2931   store->set_store_load_commands(true);
2932   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2933 
2934   auto cookie = CanonicalCookie::Create(
2935       kUrl, "a=b", base::Time::Now(), absl::nullopt /* server_time */,
2936       absl::nullopt /* cookie_partition_key */);
2937   ResultSavingCookieCallback<CookieAccessResult> set_cookie_callback;
2938   cm->SetCanonicalCookieAsync(std::move(cookie), kUrl,
2939                               CookieOptions::MakeAllInclusive(),
2940                               set_cookie_callback.MakeCallback());
2941 
2942   GetAllCookiesCallback get_cookies_callback1;
2943   cm->GetAllCookiesAsync(get_cookies_callback1.MakeCallback());
2944 
2945   // Two load events should have been queued.
2946   ASSERT_EQ(2u, store->commands().size());
2947   ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type);
2948   ASSERT_EQ(CookieStoreCommand::LOAD_COOKIES_FOR_KEY,
2949             store->commands()[1].type);
2950 
2951   // The main load completes first (With no cookies).
2952   store->TakeCallbackAt(0).Run(std::vector<std::unique_ptr<CanonicalCookie>>());
2953 
2954   // The tasks should run in order, and the get should see the cookies.
2955 
2956   set_cookie_callback.WaitUntilDone();
2957   EXPECT_TRUE(set_cookie_callback.result().status.IsInclude());
2958 
2959   get_cookies_callback1.WaitUntilDone();
2960   EXPECT_EQ(1u, get_cookies_callback1.cookies().size());
2961 
2962   // The loaded for key event completes late, with not cookies (Since they
2963   // were already loaded).
2964   store->TakeCallbackAt(1).Run(std::vector<std::unique_ptr<CanonicalCookie>>());
2965 
2966   // The just set cookie should still be in the store.
2967   GetAllCookiesCallback get_cookies_callback2;
2968   cm->GetAllCookiesAsync(get_cookies_callback2.MakeCallback());
2969   get_cookies_callback2.WaitUntilDone();
2970   EXPECT_EQ(1u, get_cookies_callback2.cookies().size());
2971 }
2972 
2973 // Tests that case that DeleteAll is waiting for load to complete, and then a
2974 // get is queued. The get should wait to run until after all the cookies are
2975 // retrieved, and should return nothing, since all cookies were just deleted.
TEST_F(CookieMonsterTest,WhileLoadingDeleteAllGetForURL)2976 TEST_F(CookieMonsterTest, WhileLoadingDeleteAllGetForURL) {
2977   const GURL kUrl = GURL(kTopLevelDomainPlus1);
2978 
2979   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
2980   store->set_store_load_commands(true);
2981   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
2982 
2983   ResultSavingCookieCallback<uint32_t> delete_callback;
2984   cm->DeleteAllAsync(delete_callback.MakeCallback());
2985 
2986   GetCookieListCallback get_cookie_list_callback;
2987   cm->GetCookieListWithOptionsAsync(kUrl, CookieOptions::MakeAllInclusive(),
2988                                     CookiePartitionKeyCollection(),
2989                                     get_cookie_list_callback.MakeCallback());
2990 
2991   // Only the main load should have been queued.
2992   ASSERT_EQ(1u, store->commands().size());
2993   ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type);
2994 
2995   std::vector<std::unique_ptr<CanonicalCookie>> cookies;
2996   // When passed to the CookieMonster, it takes ownership of the pointed to
2997   // cookies.
2998   cookies.push_back(CanonicalCookie::Create(
2999       kUrl, "a=b", base::Time::Now(), absl::nullopt /* server_time */,
3000       absl::nullopt /* cookie_partition_key */));
3001   ASSERT_TRUE(cookies[0]);
3002   store->TakeCallbackAt(0).Run(std::move(cookies));
3003 
3004   delete_callback.WaitUntilDone();
3005   EXPECT_EQ(1u, delete_callback.result());
3006 
3007   get_cookie_list_callback.WaitUntilDone();
3008   EXPECT_EQ(0u, get_cookie_list_callback.cookies().size());
3009 }
3010 
3011 // Tests that a set cookie call sandwiched between two get all cookies, all
3012 // before load completes, affects the first but not the second. The set should
3013 // also not trigger a LoadCookiesForKey (As that could complete only after the
3014 // main load for the store).
TEST_F(CookieMonsterTest,WhileLoadingGetAllSetGetAll)3015 TEST_F(CookieMonsterTest, WhileLoadingGetAllSetGetAll) {
3016   const GURL kUrl = GURL(kTopLevelDomainPlus1);
3017 
3018   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3019   store->set_store_load_commands(true);
3020   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3021 
3022   GetAllCookiesCallback get_cookies_callback1;
3023   cm->GetAllCookiesAsync(get_cookies_callback1.MakeCallback());
3024 
3025   auto cookie = CanonicalCookie::Create(
3026       kUrl, "a=b", base::Time::Now(), absl::nullopt /* server_time */,
3027       absl::nullopt /* cookie_partition_key */);
3028   ResultSavingCookieCallback<CookieAccessResult> set_cookie_callback;
3029   cm->SetCanonicalCookieAsync(std::move(cookie), kUrl,
3030                               CookieOptions::MakeAllInclusive(),
3031                               set_cookie_callback.MakeCallback());
3032 
3033   GetAllCookiesCallback get_cookies_callback2;
3034   cm->GetAllCookiesAsync(get_cookies_callback2.MakeCallback());
3035 
3036   // Only the main load should have been queued.
3037   ASSERT_EQ(1u, store->commands().size());
3038   ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type);
3039 
3040   // The load completes (With no cookies).
3041   store->TakeCallbackAt(0).Run(std::vector<std::unique_ptr<CanonicalCookie>>());
3042 
3043   get_cookies_callback1.WaitUntilDone();
3044   EXPECT_EQ(0u, get_cookies_callback1.cookies().size());
3045 
3046   set_cookie_callback.WaitUntilDone();
3047   EXPECT_TRUE(set_cookie_callback.result().status.IsInclude());
3048 
3049   get_cookies_callback2.WaitUntilDone();
3050   EXPECT_EQ(1u, get_cookies_callback2.cookies().size());
3051 }
3052 
3053 namespace {
3054 
RunClosureOnAllCookiesReceived(base::OnceClosure closure,const CookieList & cookie_list)3055 void RunClosureOnAllCookiesReceived(base::OnceClosure closure,
3056                                     const CookieList& cookie_list) {
3057   std::move(closure).Run();
3058 }
3059 
3060 }  // namespace
3061 
3062 // Tests that if a single cookie task is queued as a result of a task performed
3063 // on all cookies when loading completes, it will be run after any already
3064 // queued tasks.
TEST_F(CookieMonsterTest,CheckOrderOfCookieTaskQueueWhenLoadingCompletes)3065 TEST_F(CookieMonsterTest, CheckOrderOfCookieTaskQueueWhenLoadingCompletes) {
3066   const GURL kUrl = GURL(kTopLevelDomainPlus1);
3067 
3068   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3069   store->set_store_load_commands(true);
3070   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3071 
3072   // Get all cookies task that queues a task to set a cookie when executed.
3073   auto cookie = CanonicalCookie::Create(
3074       kUrl, "a=b", base::Time::Now(), absl::nullopt /* server_time */,
3075       absl::nullopt /* cookie_partition_key */);
3076   ResultSavingCookieCallback<CookieAccessResult> set_cookie_callback;
3077   cm->GetAllCookiesAsync(base::BindOnce(
3078       &RunClosureOnAllCookiesReceived,
3079       base::BindOnce(&CookieStore::SetCanonicalCookieAsync,
3080                      base::Unretained(cm.get()), std::move(cookie), kUrl,
3081                      CookieOptions::MakeAllInclusive(),
3082                      set_cookie_callback.MakeCallback(), absl::nullopt)));
3083 
3084   // Get cookie task. Queued before the delete task is executed, so should not
3085   // see the set cookie.
3086   GetAllCookiesCallback get_cookies_callback1;
3087   cm->GetAllCookiesAsync(get_cookies_callback1.MakeCallback());
3088 
3089   // Only the main load should have been queued.
3090   ASSERT_EQ(1u, store->commands().size());
3091   ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type);
3092 
3093   // The load completes.
3094   store->TakeCallbackAt(0).Run(std::vector<std::unique_ptr<CanonicalCookie>>());
3095 
3096   // The get cookies call should see no cookies set.
3097   get_cookies_callback1.WaitUntilDone();
3098   EXPECT_EQ(0u, get_cookies_callback1.cookies().size());
3099 
3100   set_cookie_callback.WaitUntilDone();
3101   EXPECT_TRUE(set_cookie_callback.result().status.IsInclude());
3102 
3103   // A subsequent get cookies call should see the new cookie.
3104   GetAllCookiesCallback get_cookies_callback2;
3105   cm->GetAllCookiesAsync(get_cookies_callback2.MakeCallback());
3106   get_cookies_callback2.WaitUntilDone();
3107   EXPECT_EQ(1u, get_cookies_callback2.cookies().size());
3108 }
3109 
3110 // Test that FlushStore() is forwarded to the store and callbacks are posted.
TEST_F(CookieMonsterTest,FlushStore)3111 TEST_F(CookieMonsterTest, FlushStore) {
3112   auto counter = base::MakeRefCounted<CallbackCounter>();
3113   auto store = base::MakeRefCounted<FlushablePersistentStore>();
3114   auto cm = std::make_unique<CookieMonster>(store, net::NetLog::Get());
3115 
3116   ASSERT_EQ(0, store->flush_count());
3117   ASSERT_EQ(0, counter->callback_count());
3118 
3119   // Before initialization, FlushStore() should just run the callback.
3120   cm->FlushStore(base::BindOnce(&CallbackCounter::Callback, counter));
3121   base::RunLoop().RunUntilIdle();
3122 
3123   ASSERT_EQ(0, store->flush_count());
3124   ASSERT_EQ(1, counter->callback_count());
3125 
3126   // NULL callback is safe.
3127   cm->FlushStore(base::OnceClosure());
3128   base::RunLoop().RunUntilIdle();
3129 
3130   ASSERT_EQ(0, store->flush_count());
3131   ASSERT_EQ(1, counter->callback_count());
3132 
3133   // After initialization, FlushStore() should delegate to the store.
3134   GetAllCookies(cm.get());  // Force init.
3135   cm->FlushStore(base::BindOnce(&CallbackCounter::Callback, counter));
3136   base::RunLoop().RunUntilIdle();
3137 
3138   ASSERT_EQ(1, store->flush_count());
3139   ASSERT_EQ(2, counter->callback_count());
3140 
3141   // NULL callback is still safe.
3142   cm->FlushStore(base::DoNothing());
3143   base::RunLoop().RunUntilIdle();
3144 
3145   ASSERT_EQ(2, store->flush_count());
3146   ASSERT_EQ(2, counter->callback_count());
3147 
3148   // If there's no backing store, FlushStore() is always a safe no-op.
3149   cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
3150   GetAllCookies(cm.get());  // Force init.
3151   cm->FlushStore(base::DoNothing());
3152   base::RunLoop().RunUntilIdle();
3153 
3154   ASSERT_EQ(2, counter->callback_count());
3155 
3156   cm->FlushStore(base::BindOnce(&CallbackCounter::Callback, counter));
3157   base::RunLoop().RunUntilIdle();
3158 
3159   ASSERT_EQ(3, counter->callback_count());
3160 }
3161 
TEST_F(CookieMonsterTest,SetAllCookies)3162 TEST_F(CookieMonsterTest, SetAllCookies) {
3163   auto store = base::MakeRefCounted<FlushablePersistentStore>();
3164   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3165   cm->SetPersistSessionCookies(true);
3166 
3167   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "U=V; path=/"));
3168   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "W=X; path=/foo"));
3169   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "Y=Z; path=/"));
3170 
3171   CookieList list;
3172   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
3173       "A", "B", "." + http_www_foo_.url().host(), "/", base::Time::Now(),
3174       base::Time(), base::Time(), base::Time(), false, false,
3175       CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false));
3176   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
3177       "C", "D", "." + http_www_foo_.url().host(), "/bar", base::Time::Now(),
3178       base::Time(), base::Time(), base::Time(), false, false,
3179       CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false));
3180   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
3181       "W", "X", "." + http_www_foo_.url().host(), "/", base::Time::Now(),
3182       base::Time(), base::Time(), base::Time(), false, false,
3183       CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false));
3184   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
3185       "__Host-Y", "Z", https_www_foo_.url().host(), "/", base::Time::Now(),
3186       base::Time(), base::Time(), base::Time(), true, false,
3187       CookieSameSite::NO_RESTRICTION, CookiePriority::COOKIE_PRIORITY_DEFAULT,
3188       false,
3189       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"))));
3190   // Expired cookie, should not be stored.
3191   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
3192       "expired", "foobar", https_www_foo_.url().host(), "/",
3193       base::Time::Now() - base::Days(1), base::Time::Now() - base::Days(2),
3194       base::Time(), base::Time(), /*secure=*/true, /*httponly=*/false,
3195       CookieSameSite::NO_RESTRICTION, CookiePriority::COOKIE_PRIORITY_DEFAULT,
3196       /*same_party=*/false));
3197 
3198   // SetAllCookies must not flush.
3199   ASSERT_EQ(0, store->flush_count());
3200   EXPECT_TRUE(SetAllCookies(cm.get(), list));
3201   EXPECT_EQ(0, store->flush_count());
3202 
3203   CookieList cookies = GetAllCookies(cm.get());
3204   size_t expected_size = 4;  // "A", "W" and "Y". "U" is gone.
3205   EXPECT_EQ(expected_size, cookies.size());
3206   auto it = cookies.begin();
3207 
3208   ASSERT_TRUE(it != cookies.end());
3209   EXPECT_EQ("C", it->Name());
3210   EXPECT_EQ("D", it->Value());
3211   EXPECT_EQ("/bar", it->Path());  // The path has been updated.
3212 
3213   ASSERT_TRUE(++it != cookies.end());
3214   EXPECT_EQ("A", it->Name());
3215   EXPECT_EQ("B", it->Value());
3216 
3217   ASSERT_TRUE(++it != cookies.end());
3218   EXPECT_EQ("W", it->Name());
3219   EXPECT_EQ("X", it->Value());
3220 
3221   ASSERT_TRUE(++it != cookies.end());
3222   EXPECT_EQ("__Host-Y", it->Name());
3223   EXPECT_EQ("Z", it->Value());
3224 
3225   cm = nullptr;
3226   auto entries = net_log_.GetEntries();
3227   size_t pos = ExpectLogContainsSomewhere(
3228       entries, 0, NetLogEventType::COOKIE_STORE_ALIVE, NetLogEventPhase::BEGIN);
3229   pos = ExpectLogContainsSomewhere(
3230       entries, pos, NetLogEventType::COOKIE_STORE_SESSION_PERSISTENCE,
3231       NetLogEventPhase::NONE);
3232   pos = ExpectLogContainsSomewhere(entries, pos,
3233                                    NetLogEventType::COOKIE_STORE_COOKIE_ADDED,
3234                                    NetLogEventPhase::NONE);
3235   ExpectLogContainsSomewhere(entries, pos, NetLogEventType::COOKIE_STORE_ALIVE,
3236                              NetLogEventPhase::END);
3237 }
3238 
3239 // Check that DeleteAll does flush (as a quick check that flush_count() works).
TEST_F(CookieMonsterTest,DeleteAll)3240 TEST_F(CookieMonsterTest, DeleteAll) {
3241   auto store = base::MakeRefCounted<FlushablePersistentStore>();
3242   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3243   cm->SetPersistSessionCookies(true);
3244 
3245   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "X=Y; path=/"));
3246 
3247   ASSERT_EQ(0, store->flush_count());
3248   EXPECT_EQ(1u, DeleteAll(cm.get()));
3249   EXPECT_EQ(1, store->flush_count());
3250 
3251   cm = nullptr;
3252   auto entries = net_log_.GetEntries();
3253   size_t pos = ExpectLogContainsSomewhere(
3254       entries, 0, NetLogEventType::COOKIE_STORE_ALIVE, NetLogEventPhase::BEGIN);
3255   pos = ExpectLogContainsSomewhere(
3256       entries, pos, NetLogEventType::COOKIE_STORE_SESSION_PERSISTENCE,
3257       NetLogEventPhase::NONE);
3258   pos = ExpectLogContainsSomewhere(entries, pos,
3259                                    NetLogEventType::COOKIE_STORE_COOKIE_ADDED,
3260                                    NetLogEventPhase::NONE);
3261   pos = ExpectLogContainsSomewhere(entries, pos,
3262                                    NetLogEventType::COOKIE_STORE_COOKIE_DELETED,
3263                                    NetLogEventPhase::NONE);
3264   ExpectLogContainsSomewhere(entries, pos, NetLogEventType::COOKIE_STORE_ALIVE,
3265                              NetLogEventPhase::END);
3266 }
3267 
TEST_F(CookieMonsterTest,HistogramCheck)3268 TEST_F(CookieMonsterTest, HistogramCheck) {
3269   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
3270 
3271   // Should match call in InitializeHistograms, but doesn't really matter
3272   // since the histogram should have been initialized by the CM construction
3273   // above.
3274   base::HistogramBase* expired_histogram = base::Histogram::FactoryGet(
3275       "Cookie.ExpirationDurationMinutesSecure", 1, 10 * 365 * 24 * 60, 50,
3276       base::Histogram::kUmaTargetedHistogramFlag);
3277 
3278   std::unique_ptr<base::HistogramSamples> samples1(
3279       expired_histogram->SnapshotSamples());
3280   auto cookie = CanonicalCookie::CreateUnsafeCookieForTesting(
3281       "a", "b", "a.url", "/", base::Time(),
3282       base::Time::Now() + base::Minutes(59), base::Time(), base::Time(), true,
3283       false, CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, false);
3284   GURL source_url = cookie_util::SimulatedCookieSource(*cookie, "https");
3285   ASSERT_TRUE(SetCanonicalCookie(cm.get(), std::move(cookie), source_url,
3286                                  true /*modify_httponly*/));
3287 
3288   std::unique_ptr<base::HistogramSamples> samples2(
3289       expired_histogram->SnapshotSamples());
3290   EXPECT_EQ(samples1->TotalCount() + 1, samples2->TotalCount());
3291 
3292   // kValidCookieLine creates a session cookie.
3293   ASSERT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), kValidCookieLine));
3294 
3295   std::unique_ptr<base::HistogramSamples> samples3(
3296       expired_histogram->SnapshotSamples());
3297   EXPECT_EQ(samples2->TotalCount(), samples3->TotalCount());
3298 }
3299 
TEST_F(CookieMonsterTest,InvalidExpiryTime)3300 TEST_F(CookieMonsterTest, InvalidExpiryTime) {
3301   std::string cookie_line =
3302       std::string(kValidCookieLine) + "; expires=Blarg arg arg";
3303   std::unique_ptr<CanonicalCookie> cookie(
3304       CanonicalCookie::Create(http_www_foo_.url(), cookie_line, Time::Now(),
3305                               absl::nullopt /* server_time */,
3306                               absl::nullopt /* cookie_partition_key */));
3307   ASSERT_FALSE(cookie->IsPersistent());
3308 }
3309 
3310 // Test that CookieMonster writes session cookies into the underlying
3311 // CookieStore if the "persist session cookies" option is on.
TEST_F(CookieMonsterTest,PersistSessionCookies)3312 TEST_F(CookieMonsterTest, PersistSessionCookies) {
3313   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3314   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3315   cm->SetPersistSessionCookies(true);
3316 
3317   // All cookies set with SetCookie are session cookies.
3318   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "A=B"));
3319   EXPECT_EQ("A=B", GetCookies(cm.get(), http_www_foo_.url()));
3320 
3321   // The cookie was written to the backing store.
3322   EXPECT_EQ(1u, store->commands().size());
3323   EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[0].type);
3324   EXPECT_EQ("A", store->commands()[0].cookie.Name());
3325   EXPECT_EQ("B", store->commands()[0].cookie.Value());
3326 
3327   // Modify the cookie.
3328   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "A=C"));
3329   EXPECT_EQ("A=C", GetCookies(cm.get(), http_www_foo_.url()));
3330   EXPECT_EQ(3u, store->commands().size());
3331   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type);
3332   EXPECT_EQ("A", store->commands()[1].cookie.Name());
3333   EXPECT_EQ("B", store->commands()[1].cookie.Value());
3334   EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[2].type);
3335   EXPECT_EQ("A", store->commands()[2].cookie.Name());
3336   EXPECT_EQ("C", store->commands()[2].cookie.Value());
3337 
3338   // Delete the cookie. Using .host() here since it's a host and not domain
3339   // cookie.
3340   EXPECT_TRUE(FindAndDeleteCookie(cm.get(), http_www_foo_.host(), "A"));
3341   EXPECT_EQ("", GetCookies(cm.get(), http_www_foo_.url()));
3342   ASSERT_EQ(4u, store->commands().size());
3343   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[3].type);
3344   EXPECT_EQ("A", store->commands()[3].cookie.Name());
3345   EXPECT_EQ("C", store->commands()[3].cookie.Value());
3346 }
3347 
3348 // Test the commands sent to the persistent cookie store.
TEST_F(CookieMonsterTest,PersisentCookieStorageTest)3349 TEST_F(CookieMonsterTest, PersisentCookieStorageTest) {
3350   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3351   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3352 
3353   // Add a cookie.
3354   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(),
3355                         "A=B" + FutureCookieExpirationString()));
3356   this->MatchCookieLines("A=B", GetCookies(cm.get(), http_www_foo_.url()));
3357   ASSERT_EQ(1u, store->commands().size());
3358   EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[0].type);
3359   // Remove it.
3360   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "A=B; max-age=0"));
3361   this->MatchCookieLines(std::string(),
3362                          GetCookies(cm.get(), http_www_foo_.url()));
3363   ASSERT_EQ(2u, store->commands().size());
3364   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type);
3365 
3366   // Add a cookie.
3367   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(),
3368                         "A=B" + FutureCookieExpirationString()));
3369   this->MatchCookieLines("A=B", GetCookies(cm.get(), http_www_foo_.url()));
3370   ASSERT_EQ(3u, store->commands().size());
3371   EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[2].type);
3372   // Overwrite it.
3373   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(),
3374                         "A=Foo" + FutureCookieExpirationString()));
3375   this->MatchCookieLines("A=Foo", GetCookies(cm.get(), http_www_foo_.url()));
3376   ASSERT_EQ(5u, store->commands().size());
3377   EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[3].type);
3378   EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[4].type);
3379 
3380   // Create some non-persistent cookies and check that they don't go to the
3381   // persistent storage.
3382   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "B=Bar"));
3383   this->MatchCookieLines("A=Foo; B=Bar",
3384                          GetCookies(cm.get(), http_www_foo_.url()));
3385   EXPECT_EQ(5u, store->commands().size());
3386 }
3387 
3388 // Test to assure that cookies with control characters are purged appropriately.
3389 // See http://crbug.com/238041 for background.
TEST_F(CookieMonsterTest,ControlCharacterPurge)3390 TEST_F(CookieMonsterTest, ControlCharacterPurge) {
3391   const Time now1(Time::Now());
3392   const Time now2(Time::Now() + base::Seconds(1));
3393   const Time now3(Time::Now() + base::Seconds(2));
3394   const Time now4(Time::Now() + base::Seconds(3));
3395   const Time later(now1 + base::Days(1));
3396   const GURL url("https://host/path");
3397   const std::string domain("host");
3398   const std::string path("/path");
3399 
3400   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3401 
3402   std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies;
3403 
3404   AddCookieToList(url, "foo=bar; path=" + path, now1, &initial_cookies);
3405 
3406   // We have to manually build these cookies because they contain control
3407   // characters, and our cookie line parser rejects control characters.
3408   std::unique_ptr<CanonicalCookie> cc =
3409       CanonicalCookie::CreateUnsafeCookieForTesting(
3410           "baz",
3411           "\x05"
3412           "boo",
3413           "." + domain, path, now2, later, base::Time(), base::Time(),
3414           true /* secure */, false /* httponly */,
3415           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT,
3416           false /* sameparty */);
3417   initial_cookies.push_back(std::move(cc));
3418 
3419   std::unique_ptr<CanonicalCookie> cc2 =
3420       CanonicalCookie::CreateUnsafeCookieForTesting(
3421           "baz",
3422           "\x7F"
3423           "boo",
3424           "." + domain, path, now3, later, base::Time(), base::Time(),
3425           true /* secure */, false /* httponly */,
3426           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT,
3427           false /* sameparty */);
3428   initial_cookies.push_back(std::move(cc2));
3429 
3430   // Partitioned cookies with control characters should not be loaded.
3431   auto cookie_partition_key =
3432       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
3433   std::unique_ptr<CanonicalCookie> cc3 =
3434       CanonicalCookie::CreateUnsafeCookieForTesting(
3435           "__Host-baz",
3436           "\x7F"
3437           "boo",
3438           domain, "/", now3, later, base::Time(), base::Time(),
3439           true /* secure */, false /* httponly */,
3440           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT,
3441           false /* sameparty */, cookie_partition_key);
3442   initial_cookies.push_back(std::move(cc3));
3443 
3444   AddCookieToList(url, "hello=world; path=" + path, now4, &initial_cookies);
3445 
3446   // Inject our initial cookies into the mock PersistentCookieStore.
3447   store->SetLoadExpectation(true, std::move(initial_cookies));
3448 
3449   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3450 
3451   EXPECT_EQ("foo=bar; hello=world",
3452             GetCookies(cm.get(), url,
3453                        CookiePartitionKeyCollection(cookie_partition_key)));
3454 }
3455 
3456 // Test that cookie source schemes are histogrammed correctly.
TEST_F(CookieMonsterTest,CookieSourceHistogram)3457 TEST_F(CookieMonsterTest, CookieSourceHistogram) {
3458   base::HistogramTester histograms;
3459   const std::string cookie_source_histogram = "Cookie.CookieSourceScheme";
3460 
3461   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3462   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3463 
3464   histograms.ExpectTotalCount(cookie_source_histogram, 0);
3465 
3466   // Set a secure cookie on a cryptographic scheme.
3467   EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(), "A=B; path=/; Secure"));
3468   histograms.ExpectTotalCount(cookie_source_histogram, 1);
3469   histograms.ExpectBucketCount(
3470       cookie_source_histogram,
3471       CookieMonster::CookieSource::kSecureCookieCryptographicScheme, 1);
3472 
3473   // Set a non-secure cookie on a cryptographic scheme.
3474   EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(), "C=D; path=/;"));
3475   histograms.ExpectTotalCount(cookie_source_histogram, 2);
3476   histograms.ExpectBucketCount(
3477       cookie_source_histogram,
3478       CookieMonster::CookieSource::kNonsecureCookieCryptographicScheme, 1);
3479 
3480   // Set a secure cookie on a non-cryptographic scheme.
3481   EXPECT_FALSE(SetCookie(cm.get(), http_www_foo_.url(), "D=E; path=/; Secure"));
3482   histograms.ExpectTotalCount(cookie_source_histogram, 2);
3483   histograms.ExpectBucketCount(
3484       cookie_source_histogram,
3485       CookieMonster::CookieSource::kSecureCookieNoncryptographicScheme, 0);
3486 
3487   // Overwrite a secure cookie (set by a cryptographic scheme) on a
3488   // non-cryptographic scheme.
3489   EXPECT_FALSE(SetCookie(cm.get(), http_www_foo_.url(), "A=B; path=/; Secure"));
3490   histograms.ExpectTotalCount(cookie_source_histogram, 2);
3491   histograms.ExpectBucketCount(
3492       cookie_source_histogram,
3493       CookieMonster::CookieSource::kSecureCookieCryptographicScheme, 1);
3494   histograms.ExpectBucketCount(
3495       cookie_source_histogram,
3496       CookieMonster::CookieSource::kSecureCookieNoncryptographicScheme, 0);
3497 
3498   // Test that attempting to clear a secure cookie on a http:// URL does
3499   // nothing.
3500   EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(), "F=G; path=/; Secure"));
3501   histograms.ExpectTotalCount(cookie_source_histogram, 3);
3502   std::string cookies1 = GetCookies(cm.get(), https_www_foo_.url());
3503   EXPECT_NE(std::string::npos, cookies1.find("F=G"));
3504   EXPECT_FALSE(SetCookie(cm.get(), http_www_foo_.url(),
3505                          "F=G; path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT"));
3506   std::string cookies2 = GetCookies(cm.get(), https_www_foo_.url());
3507   EXPECT_NE(std::string::npos, cookies2.find("F=G"));
3508   histograms.ExpectTotalCount(cookie_source_histogram, 3);
3509 
3510   // Set a non-secure cookie on a non-cryptographic scheme.
3511   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "H=I; path=/"));
3512   histograms.ExpectTotalCount(cookie_source_histogram, 4);
3513   histograms.ExpectBucketCount(
3514       cookie_source_histogram,
3515       CookieMonster::CookieSource::kNonsecureCookieNoncryptographicScheme, 1);
3516 }
3517 
3518 // Test that inserting the first cookie for a key and deleting the last cookie
3519 // for a key correctly reflected in the Cookie.NumKeys histogram.
TEST_F(CookieMonsterTest,NumKeysHistogram)3520 TEST_F(CookieMonsterTest, NumKeysHistogram) {
3521   const char kHistogramName[] = "Cookie.NumKeys";
3522 
3523   // Test loading cookies from store.
3524   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3525   std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies;
3526   initial_cookies.push_back(CanonicalCookie::Create(
3527       GURL("http://domain1.test"), "A=1", base::Time::Now(),
3528       absl::nullopt /* server_time */,
3529       absl::nullopt /* cookie_partition_key */));
3530   initial_cookies.push_back(CanonicalCookie::Create(
3531       GURL("http://domain2.test"), "A=1", base::Time::Now(),
3532       absl::nullopt /* server_time */,
3533       absl::nullopt /* cookie_partition_key */));
3534   initial_cookies.push_back(CanonicalCookie::Create(
3535       GURL("http://sub.domain2.test"), "A=1", base::Time::Now(),
3536       absl::nullopt /* server_time */,
3537       absl::nullopt /* cookie_partition_key */));
3538   initial_cookies.push_back(CanonicalCookie::Create(
3539       GURL("http://domain3.test"), "A=1", base::Time::Now(),
3540       absl::nullopt /* server_time */,
3541       absl::nullopt /* cookie_partition_key */));
3542   initial_cookies.push_back(CanonicalCookie::Create(
3543       GURL("http://domain3.test"), "B=1", base::Time::Now(),
3544       absl::nullopt /* server_time */,
3545       absl::nullopt /* cookie_partition_key */));
3546   store->SetLoadExpectation(true /* return_value */,
3547                             std::move(initial_cookies));
3548   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3549   {
3550     base::HistogramTester histogram_tester;
3551     // Access the cookies to trigger loading from the persistent store.
3552     EXPECT_EQ(5u, this->GetAllCookies(cm.get()).size());
3553     EXPECT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3554     // There should be 3 keys: "domain1.test", "domain2.test", and
3555     // "domain3.test".
3556     histogram_tester.ExpectUniqueSample(kHistogramName, 3 /* sample */,
3557                                         1 /* count */);
3558   }
3559 
3560   // Test adding cookies for already existing key.
3561   {
3562     base::HistogramTester histogram_tester;
3563     EXPECT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain1.test"),
3564                                    "B=1", CookieOptions::MakeAllInclusive()));
3565     EXPECT_TRUE(CreateAndSetCookie(cm.get(), GURL("http://sub.domain1.test"),
3566                                    "B=1", CookieOptions::MakeAllInclusive()));
3567     EXPECT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3568     histogram_tester.ExpectUniqueSample(kHistogramName, 3 /* sample */,
3569                                         1 /* count */);
3570   }
3571 
3572   // Test adding a cookie for a new key.
3573   {
3574     base::HistogramTester histogram_tester;
3575     EXPECT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain4.test"),
3576                                    "A=1", CookieOptions::MakeAllInclusive()));
3577     EXPECT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3578     histogram_tester.ExpectUniqueSample(kHistogramName, 4 /* sample */,
3579                                         1 /* count */);
3580   }
3581 
3582   // Test overwriting the only cookie for a key. (Deletes and inserts, so the
3583   // total doesn't change.)
3584   {
3585     base::HistogramTester histogram_tester;
3586     EXPECT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain4.test"),
3587                                    "A=2", CookieOptions::MakeAllInclusive()));
3588     EXPECT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3589     histogram_tester.ExpectUniqueSample(kHistogramName, 4 /* sample */,
3590                                         1 /* count */);
3591   }
3592 
3593   // Test deleting cookie for a key with more than one cookie.
3594   {
3595     base::HistogramTester histogram_tester;
3596     EXPECT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain2.test"),
3597                                    "A=1; Max-Age=0",
3598                                    CookieOptions::MakeAllInclusive()));
3599     EXPECT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3600     histogram_tester.ExpectUniqueSample(kHistogramName, 4 /* sample */,
3601                                         1 /* count */);
3602   }
3603 
3604   // Test deleting cookie for a key with only one cookie.
3605   {
3606     base::HistogramTester histogram_tester;
3607     EXPECT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain4.test"),
3608                                    "A=1; Max-Age=0",
3609                                    CookieOptions::MakeAllInclusive()));
3610     EXPECT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3611     histogram_tester.ExpectUniqueSample(kHistogramName, 3 /* sample */,
3612                                         1 /* count */);
3613   }
3614 }
3615 
TEST_F(CookieMonsterTest,MaxSameSiteNoneCookiesPerKey)3616 TEST_F(CookieMonsterTest, MaxSameSiteNoneCookiesPerKey) {
3617   const char kHistogramName[] = "Cookie.MaxSameSiteNoneCookiesPerKey";
3618 
3619   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3620   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3621   ASSERT_EQ(0u, GetAllCookies(cm.get()).size());
3622 
3623   {  // Only SameSite cookies should not log a sample.
3624     base::HistogramTester histogram_tester;
3625 
3626     ASSERT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain1.test"),
3627                                    "A=1;SameSite=Lax",
3628                                    CookieOptions::MakeAllInclusive()));
3629     ASSERT_EQ(1u, GetAllCookies(cm.get()).size());
3630     ASSERT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3631     histogram_tester.ExpectUniqueSample(kHistogramName, 0 /* sample */,
3632                                         1 /* count */);
3633   }
3634 
3635   {  // SameSite=None cookie should log a sample.
3636     base::HistogramTester histogram_tester;
3637 
3638     ASSERT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain1.test"),
3639                                    "B=2;SameSite=None;Secure",
3640                                    CookieOptions::MakeAllInclusive()));
3641     ASSERT_EQ(2u, GetAllCookies(cm.get()).size());
3642     ASSERT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3643     histogram_tester.ExpectUniqueSample(kHistogramName, 1 /* sample */,
3644                                         1 /* count */);
3645   }
3646 
3647   {  // Should log the maximum number of SameSite=None cookies.
3648     base::HistogramTester histogram_tester;
3649 
3650     ASSERT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain2.test"),
3651                                    "A=1;SameSite=None;Secure",
3652                                    CookieOptions::MakeAllInclusive()));
3653     ASSERT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain2.test"),
3654                                    "B=2;SameSite=None;Secure",
3655                                    CookieOptions::MakeAllInclusive()));
3656     ASSERT_TRUE(CreateAndSetCookie(cm.get(), GURL("https://domain3.test"),
3657                                    "A=1;SameSite=None;Secure",
3658                                    CookieOptions::MakeAllInclusive()));
3659     ASSERT_EQ(5u, GetAllCookies(cm.get()).size());
3660     ASSERT_TRUE(cm->DoRecordPeriodicStatsForTesting());
3661     histogram_tester.ExpectUniqueSample(kHistogramName, 2 /* sample */,
3662                                         1 /* count */);
3663   }
3664 }
3665 
3666 // Test that localhost URLs can set and get secure cookies, even if
3667 // non-cryptographic.
TEST_F(CookieMonsterTest,SecureCookieLocalhost)3668 TEST_F(CookieMonsterTest, SecureCookieLocalhost) {
3669   auto cm = std::make_unique<CookieMonster>(nullptr, nullptr);
3670 
3671   GURL insecure_localhost("http://localhost");
3672   GURL secure_localhost("https://localhost");
3673 
3674   // Insecure localhost can set secure cookie, and warning is attached to
3675   // status.
3676   {
3677     auto cookie = CanonicalCookie::Create(
3678         insecure_localhost, "from_insecure_localhost=1; Secure",
3679         base::Time::Now(), absl::nullopt /* server_time */,
3680         absl::nullopt /* cookie_partition_key */);
3681     ASSERT_TRUE(cookie);
3682     CookieInclusionStatus status =
3683         SetCanonicalCookieReturnAccessResult(cm.get(), std::move(cookie),
3684                                              insecure_localhost,
3685                                              true /* can_modify_httponly */)
3686             .status;
3687     EXPECT_TRUE(status.IsInclude());
3688     EXPECT_TRUE(status.HasExactlyWarningReasonsForTesting(
3689         {CookieInclusionStatus::WARN_SECURE_ACCESS_GRANTED_NON_CRYPTOGRAPHIC}));
3690   }
3691   // Secure localhost can set secure cookie, and warning is not attached to
3692   // status.
3693   {
3694     auto cookie = CanonicalCookie::Create(
3695         insecure_localhost, "from_secure_localhost=1; Secure",
3696         base::Time::Now(), absl::nullopt /* server_time */,
3697         absl::nullopt /* cookie_partition_key */);
3698     ASSERT_TRUE(cookie);
3699     CookieInclusionStatus status =
3700         SetCanonicalCookieReturnAccessResult(cm.get(), std::move(cookie),
3701                                              secure_localhost,
3702                                              true /* can_modify_httponly */)
3703             .status;
3704     EXPECT_EQ(CookieInclusionStatus(), status);
3705   }
3706 
3707   // Insecure localhost can get secure cookies, and warning is attached to
3708   // status.
3709   {
3710     GetCookieListCallback callback;
3711     cm->GetCookieListWithOptionsAsync(
3712         insecure_localhost, CookieOptions::MakeAllInclusive(),
3713         CookiePartitionKeyCollection(), callback.MakeCallback());
3714     callback.WaitUntilDone();
3715     EXPECT_EQ(2u, callback.cookies_with_access_results().size());
3716     for (const auto& cookie_item : callback.cookies_with_access_results()) {
3717       EXPECT_TRUE(cookie_item.cookie.IsSecure());
3718       EXPECT_TRUE(cookie_item.access_result.status.IsInclude());
3719       EXPECT_TRUE(
3720           cookie_item.access_result.status.HasExactlyWarningReasonsForTesting(
3721               {CookieInclusionStatus::
3722                    WARN_SECURE_ACCESS_GRANTED_NON_CRYPTOGRAPHIC}));
3723     }
3724   }
3725   // Secure localhost can get secure cookies, and warning is not attached to
3726   // status.
3727   {
3728     GetCookieListCallback callback;
3729     cm->GetCookieListWithOptionsAsync(
3730         secure_localhost, CookieOptions::MakeAllInclusive(),
3731         CookiePartitionKeyCollection(), callback.MakeCallback());
3732     callback.WaitUntilDone();
3733     EXPECT_EQ(2u, callback.cookies_with_access_results().size());
3734     for (const auto& cookie_item : callback.cookies_with_access_results()) {
3735       EXPECT_TRUE(cookie_item.cookie.IsSecure());
3736       EXPECT_EQ(CookieInclusionStatus(), cookie_item.access_result.status);
3737     }
3738   }
3739 }
3740 
TEST_F(CookieMonsterTest,MaybeDeleteEquivalentCookieAndUpdateStatus)3741 TEST_F(CookieMonsterTest, MaybeDeleteEquivalentCookieAndUpdateStatus) {
3742   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3743   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3744 
3745   // Set a secure, httponly cookie from a secure origin
3746   auto preexisting_cookie = CanonicalCookie::Create(
3747       https_www_foo_.url(), "A=B;Secure;HttpOnly", base::Time::Now(),
3748       absl::nullopt /* server_time */,
3749       absl::nullopt /* cookie_partition_key */);
3750   CookieAccessResult access_result = SetCanonicalCookieReturnAccessResult(
3751       cm.get(), std::move(preexisting_cookie), https_www_foo_.url(),
3752       true /* can_modify_httponly */);
3753   ASSERT_TRUE(access_result.status.IsInclude());
3754 
3755   // Set a new cookie with a different name. Should work because cookies with
3756   // different names are not considered equivalent nor "equivalent for secure
3757   // cookie matching".
3758   // Same origin:
3759   EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(), "B=A;"));
3760   // Different scheme, same domain:
3761   EXPECT_TRUE(SetCookie(cm.get(), http_www_foo_.url(), "C=A;"));
3762 
3763   // Set a non-Secure cookie from an insecure origin that is
3764   // equivalent to the pre-existing Secure cookie.
3765   auto bad_cookie =
3766       CanonicalCookie::Create(http_www_foo_.url(), "A=D", base::Time::Now(),
3767                               absl::nullopt /* server_time */,
3768                               absl::nullopt /* cookie_partition_key */);
3769   // Allow modifying HttpOnly, so that we don't skip preexisting cookies for
3770   // being HttpOnly.
3771   access_result = SetCanonicalCookieReturnAccessResult(
3772       cm.get(), std::move(bad_cookie), http_www_foo_.url(),
3773       true /* can_modify_httponly */);
3774   EXPECT_TRUE(access_result.status.HasExactlyExclusionReasonsForTesting(
3775       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
3776   // The preexisting cookie should still be there.
3777   EXPECT_THAT(GetCookiesWithOptions(cm.get(), https_www_foo_.url(),
3778                                     CookieOptions::MakeAllInclusive()),
3779               ::testing::HasSubstr("A=B"));
3780 
3781   auto entries = net_log_.GetEntries();
3782   size_t skipped_secure_netlog_index = ExpectLogContainsSomewhere(
3783       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_SECURE,
3784       NetLogEventPhase::NONE);
3785   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
3786       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_HTTPONLY));
3787   ExpectLogContainsSomewhereAfter(
3788       entries, skipped_secure_netlog_index,
3789       NetLogEventType::COOKIE_STORE_COOKIE_PRESERVED_SKIPPED_SECURE,
3790       NetLogEventPhase::NONE);
3791 
3792   net_log_.Clear();
3793 
3794   // Set a non-secure cookie from an insecure origin that matches the name of an
3795   // already existing cookie but is not equivalent. This should fail since it's
3796   // trying to shadow a secure cookie.
3797   bad_cookie = CanonicalCookie::Create(
3798       http_www_foo_.url(), "A=E; path=/some/path", base::Time::Now(),
3799       absl::nullopt /* server_time */,
3800       absl::nullopt /* cookie_partition_key */);
3801   // Allow modifying HttpOnly, so that we don't skip preexisting cookies for
3802   // being HttpOnly.
3803   access_result = SetCanonicalCookieReturnAccessResult(
3804       cm.get(), std::move(bad_cookie), http_www_foo_.url(),
3805       true /* can_modify_httponly */);
3806   EXPECT_TRUE(access_result.status.HasExactlyExclusionReasonsForTesting(
3807       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
3808   // The preexisting cookie should still be there.
3809   EXPECT_THAT(GetCookiesWithOptions(cm.get(), https_www_foo_.url(),
3810                                     CookieOptions::MakeAllInclusive()),
3811               ::testing::HasSubstr("A=B"));
3812 
3813   entries = net_log_.GetEntries();
3814   skipped_secure_netlog_index = ExpectLogContainsSomewhere(
3815       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_SECURE,
3816       NetLogEventPhase::NONE);
3817   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
3818       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_HTTPONLY));
3819   // There wasn't actually a strictly equivalent cookie that we would have
3820   // deleted.
3821   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
3822       entries, skipped_secure_netlog_index,
3823       NetLogEventType::COOKIE_STORE_COOKIE_PRESERVED_SKIPPED_SECURE));
3824 
3825   net_log_.Clear();
3826 
3827   // Test skipping equivalent cookie for HttpOnly only.
3828   bad_cookie = CanonicalCookie::Create(
3829       https_www_foo_.url(), "A=E; Secure", base::Time::Now(),
3830       absl::nullopt /* server_time */,
3831       absl::nullopt /* cookie_partition_key */);
3832   access_result = SetCanonicalCookieReturnAccessResult(
3833       cm.get(), std::move(bad_cookie), https_www_foo_.url(),
3834       false /* can_modify_httponly */);
3835   EXPECT_TRUE(access_result.status.HasExactlyExclusionReasonsForTesting(
3836       {CookieInclusionStatus::EXCLUDE_OVERWRITE_HTTP_ONLY}));
3837 
3838   entries = net_log_.GetEntries();
3839   ExpectLogContainsSomewhere(
3840       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_HTTPONLY,
3841       NetLogEventPhase::NONE);
3842   EXPECT_FALSE(LogContainsEntryWithTypeAfter(
3843       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_SECURE));
3844 }
3845 
TEST_F(CookieMonsterTest,MaybeDeleteEquivalentCookieAndUpdateStatus_PartitionedCookies)3846 TEST_F(CookieMonsterTest,
3847        MaybeDeleteEquivalentCookieAndUpdateStatus_PartitionedCookies) {
3848   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3849   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3850 
3851   // Test adding two cookies with the same name, domain, and path but different
3852   // partition keys.
3853   auto cookie_partition_key1 =
3854       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite1.com"));
3855 
3856   auto preexisting_cookie = CanonicalCookie::Create(
3857       https_www_foo_.url(), "__Host-A=B; Secure; Path=/; Partitioned; HttpOnly",
3858       base::Time::Now(), absl::nullopt /* server_time */,
3859       cookie_partition_key1 /* cookie_partition_key */);
3860   CookieAccessResult access_result = SetCanonicalCookieReturnAccessResult(
3861       cm.get(), std::move(preexisting_cookie), https_www_foo_.url(),
3862       true /* can_modify_httponly */);
3863   ASSERT_TRUE(access_result.status.IsInclude());
3864 
3865   // Should be able to set a cookie with a different partition key.
3866   EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(),
3867                         "__Host-A=C; Secure; Path=/; Partitioned",
3868                         CookiePartitionKey::FromURLForTesting(
3869                             GURL("https://toplevelsite2.com"))));
3870 
3871   // Should not overwrite HttpOnly cookie.
3872   auto bad_cookie = CanonicalCookie::Create(
3873       https_www_foo_.url(), "__Host-A=D; Secure; Path=/; Partitioned",
3874       base::Time::Now(), absl::nullopt /* server_time */,
3875       cookie_partition_key1);
3876   access_result = SetCanonicalCookieReturnAccessResult(
3877       cm.get(), std::move(bad_cookie), https_www_foo_.url(),
3878       false /* can_modify_httponly */);
3879   EXPECT_TRUE(access_result.status.HasExactlyExclusionReasonsForTesting(
3880       {CookieInclusionStatus::EXCLUDE_OVERWRITE_HTTP_ONLY}));
3881   EXPECT_THAT(
3882       GetCookiesWithOptions(
3883           cm.get(), https_www_foo_.url(), CookieOptions::MakeAllInclusive(),
3884           CookiePartitionKeyCollection(cookie_partition_key1)),
3885       ::testing::HasSubstr("A=B"));
3886 }
3887 
3888 // Test skipping a cookie in MaybeDeleteEquivalentCookieAndUpdateStatus for
3889 // multiple reasons (Secure and HttpOnly).
TEST_F(CookieMonsterTest,SkipDontOverwriteForMultipleReasons)3890 TEST_F(CookieMonsterTest, SkipDontOverwriteForMultipleReasons) {
3891   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3892   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3893 
3894   // Set a secure, httponly cookie from a secure origin
3895   auto preexisting_cookie = CanonicalCookie::Create(
3896       https_www_foo_.url(), "A=B;Secure;HttpOnly", base::Time::Now(),
3897       absl::nullopt /* server_time */,
3898       absl::nullopt /* cookie_partition_key */);
3899   CookieAccessResult access_result = SetCanonicalCookieReturnAccessResult(
3900       cm.get(), std::move(preexisting_cookie), https_www_foo_.url(),
3901       true /* can_modify_httponly */);
3902   ASSERT_TRUE(access_result.status.IsInclude());
3903 
3904   // Attempt to set a new cookie with the same name that is not Secure or
3905   // Httponly from an insecure scheme.
3906   auto cookie =
3907       CanonicalCookie::Create(http_www_foo_.url(), "A=B", base::Time::Now(),
3908                               absl::nullopt /* server_time */,
3909                               absl::nullopt /* cookie_partition_key */);
3910   access_result = SetCanonicalCookieReturnAccessResult(
3911       cm.get(), std::move(cookie), http_www_foo_.url(),
3912       false /* can_modify_httponly */);
3913   EXPECT_TRUE(access_result.status.HasExactlyExclusionReasonsForTesting(
3914       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE,
3915        CookieInclusionStatus::EXCLUDE_OVERWRITE_HTTP_ONLY}));
3916 
3917   auto entries = net_log_.GetEntries();
3918   ExpectLogContainsSomewhere(
3919       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_SECURE,
3920       NetLogEventPhase::NONE);
3921   ExpectLogContainsSomewhere(
3922       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_HTTPONLY,
3923       NetLogEventPhase::NONE);
3924 }
3925 
3926 // Test that when we check for equivalent cookies, we don't remove any if the
3927 // cookie should not be set.
TEST_F(CookieMonsterTest,DontDeleteEquivalentCookieIfSetIsRejected)3928 TEST_F(CookieMonsterTest, DontDeleteEquivalentCookieIfSetIsRejected) {
3929   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
3930   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
3931 
3932   auto preexisting_cookie = CanonicalCookie::Create(
3933       http_www_foo_.url(), "cookie=foo", base::Time::Now(),
3934       absl::nullopt /* server_time */,
3935       absl::nullopt /* cookie_partition_key */);
3936   CookieAccessResult access_result = SetCanonicalCookieReturnAccessResult(
3937       cm.get(), std::move(preexisting_cookie), http_www_foo_.url(),
3938       false /* can_modify_httponly */);
3939   ASSERT_TRUE(access_result.status.IsInclude());
3940 
3941   auto bad_cookie = CanonicalCookie::Create(
3942       http_www_foo_.url(), "cookie=bar;secure", base::Time::Now(),
3943       absl::nullopt /* server_time */,
3944       absl::nullopt /* cookie_partition_key */);
3945   CookieAccessResult access_result2 = SetCanonicalCookieReturnAccessResult(
3946       cm.get(), std::move(bad_cookie), http_www_foo_.url(),
3947       false /* can_modify_httponly */);
3948   EXPECT_TRUE(access_result2.status.HasExactlyExclusionReasonsForTesting(
3949       {CookieInclusionStatus::EXCLUDE_SECURE_ONLY}));
3950 
3951   // Check that the original cookie is still there.
3952   EXPECT_EQ("cookie=foo", GetCookies(cm.get(), https_www_foo_.url()));
3953 }
3954 
TEST_F(CookieMonsterTest,SetSecureCookies)3955 TEST_F(CookieMonsterTest, SetSecureCookies) {
3956   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
3957 
3958   GURL http_url("http://www.foo.com");
3959   GURL http_superdomain_url("http://foo.com");
3960   GURL https_url("https://www.foo.com");
3961   GURL https_foo_url("https://www.foo.com/foo");
3962   GURL http_foo_url("http://www.foo.com/foo");
3963 
3964   // A non-secure cookie can be created from either a URL with a secure or
3965   // insecure scheme.
3966   EXPECT_TRUE(
3967       CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=C;").IsInclude());
3968   EXPECT_TRUE(
3969       CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B;").IsInclude());
3970 
3971   // A secure cookie cannot be set from a URL with an insecure scheme.
3972   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=B; Secure")
3973                   .HasExactlyExclusionReasonsForTesting(
3974                       {CookieInclusionStatus::EXCLUDE_SECURE_ONLY}));
3975 
3976   // A secure cookie can be set from a URL with a secure scheme.
3977   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")
3978                   .IsInclude());
3979 
3980   // If a non-secure cookie is created from a URL with an insecure scheme, and a
3981   // secure cookie with the same name already exists, do not update the cookie.
3982   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")
3983                   .IsInclude());
3984   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=C;")
3985                   .HasExactlyExclusionReasonsForTesting(
3986                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
3987 
3988   // If a non-secure cookie is created from a URL with an secure scheme, and a
3989   // secure cookie with the same name already exists, update the cookie.
3990   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")
3991                   .IsInclude());
3992   EXPECT_TRUE(
3993       CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=C;").IsInclude());
3994 
3995   // If a non-secure cookie is created from a URL with an insecure scheme, and
3996   // a secure cookie with the same name already exists, do not update the cookie
3997   // if the new cookie's path matches the existing cookie's path.
3998   //
3999   // With an existing cookie whose path is '/', a cookie with the same name
4000   // cannot be set on the same domain, regardless of path:
4001   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")
4002                   .IsInclude());
4003   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=C; path=/")
4004                   .HasExactlyExclusionReasonsForTesting(
4005                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4006   EXPECT_TRUE(
4007       CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=C; path=/my/path")
4008           .HasExactlyExclusionReasonsForTesting(
4009               {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4010 
4011   // But if the existing cookie has a path somewhere under the root, cookies
4012   // with the same name may be set for paths which don't overlap the existing
4013   // cookie.
4014   EXPECT_TRUE(
4015       SetCookie(cm.get(), https_url, "WITH_PATH=B; Secure; path=/my/path"));
4016   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "WITH_PATH=C")
4017                   .IsInclude());
4018   EXPECT_TRUE(
4019       CreateAndSetCookieReturnStatus(cm.get(), http_url, "WITH_PATH=C; path=/")
4020           .IsInclude());
4021   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url,
4022                                              "WITH_PATH=C; path=/your/path")
4023                   .IsInclude());
4024   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url,
4025                                              "WITH_PATH=C; path=/my/path")
4026                   .HasExactlyExclusionReasonsForTesting(
4027                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4028   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url,
4029                                              "WITH_PATH=C; path=/my/path/sub")
4030                   .HasExactlyExclusionReasonsForTesting(
4031                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4032 
4033   DeleteAll(cm.get());
4034 
4035   // If a secure cookie is set on top of an existing insecure cookie but with a
4036   // different path, both are retained.
4037   EXPECT_TRUE(
4038       CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=B; path=/foo")
4039           .IsInclude());
4040   EXPECT_TRUE(
4041       CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=C; Secure; path=/")
4042           .IsInclude());
4043 
4044   // Querying from an insecure url gets only the insecure cookie, but querying
4045   // from a secure url returns both.
4046   EXPECT_EQ("A=B", GetCookies(cm.get(), http_foo_url));
4047   EXPECT_THAT(GetCookies(cm.get(), https_foo_url), testing::HasSubstr("A=B"));
4048   EXPECT_THAT(GetCookies(cm.get(), https_foo_url), testing::HasSubstr("A=C"));
4049 
4050   // Attempting to set an insecure cookie (from an insecure scheme) that domain-
4051   // matches and path-matches the secure cookie fails i.e. the secure cookie is
4052   // left alone...
4053   EXPECT_TRUE(
4054       CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=D; path=/foo")
4055           .HasExactlyExclusionReasonsForTesting(
4056               {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4057   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=D; path=/")
4058                   .HasExactlyExclusionReasonsForTesting(
4059                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4060   EXPECT_THAT(GetCookies(cm.get(), https_foo_url), testing::HasSubstr("A=C"));
4061 
4062   // ...but the original insecure cookie is still retained.
4063   EXPECT_THAT(GetCookies(cm.get(), https_foo_url), testing::HasSubstr("A=B"));
4064   EXPECT_THAT(GetCookies(cm.get(), https_foo_url),
4065               testing::Not(testing::HasSubstr("A=D")));
4066 
4067   // Deleting the secure cookie leaves only the original insecure cookie.
4068   EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4069                   cm.get(), https_url,
4070                   "A=C; path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT")
4071                   .IsInclude());
4072   EXPECT_EQ("A=B", GetCookies(cm.get(), https_foo_url));
4073 
4074   // If a non-secure cookie is created from a URL with an insecure scheme, and
4075   // a secure cookie with the same name already exists, if the domain strings
4076   // domain-match, do not update the cookie.
4077   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")
4078                   .IsInclude());
4079   EXPECT_TRUE(
4080       CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=C; domain=foo.com")
4081           .HasExactlyExclusionReasonsForTesting(
4082               {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4083   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url,
4084                                              "A=C; domain=www.foo.com")
4085                   .HasExactlyExclusionReasonsForTesting(
4086                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4087 
4088   // Since A=B was set above with no domain string, set a different cookie here
4089   // so the insecure examples aren't trying to overwrite the one above.
4090   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url,
4091                                              "B=C; Secure; domain=foo.com")
4092                   .IsInclude());
4093   EXPECT_TRUE(
4094       CreateAndSetCookieReturnStatus(cm.get(), http_url, "B=D; domain=foo.com")
4095           .HasExactlyExclusionReasonsForTesting(
4096               {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4097   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "B=D")
4098                   .HasExactlyExclusionReasonsForTesting(
4099                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4100   EXPECT_TRUE(
4101       CreateAndSetCookieReturnStatus(cm.get(), http_superdomain_url, "B=D")
4102           .HasExactlyExclusionReasonsForTesting(
4103               {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}));
4104 
4105   // Verify that if an httponly version of the cookie exists, adding a Secure
4106   // version of the cookie still does not overwrite it.
4107   CookieOptions include_httponly = CookieOptions::MakeAllInclusive();
4108   EXPECT_TRUE(CreateAndSetCookie(cm.get(), https_url, "C=D; httponly",
4109                                  include_httponly));
4110   // Note that the lack of an explicit options object below uses the default,
4111   // which in this case includes "exclude_httponly = true".
4112   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "C=E; Secure")
4113                   .HasExactlyExclusionReasonsForTesting(
4114                       {CookieInclusionStatus::EXCLUDE_OVERWRITE_HTTP_ONLY}));
4115 
4116   auto entries = net_log_.GetEntries();
4117   ExpectLogContainsSomewhere(
4118       entries, 0, NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_HTTPONLY,
4119       NetLogEventPhase::NONE);
4120 }
4121 
TEST_F(CookieMonsterTest,SetSamePartyCookies)4122 TEST_F(CookieMonsterTest, SetSamePartyCookies) {
4123   CookieMonster cm(nullptr, net::NetLog::Get());
4124   GURL http_url("http://www.foo.com");
4125   GURL http_superdomain_url("http://foo.com");
4126   GURL https_url("https://www.foo.com");
4127   GURL https_foo_url("https://www.foo.com/foo");
4128   GURL http_foo_url("http://www.foo.com/foo");
4129 
4130   // A non-SameParty cookie can be created from either a URL with a secure or
4131   // insecure scheme.
4132   EXPECT_TRUE(
4133       CreateAndSetCookieReturnStatus(&cm, http_url, "A=C;").IsInclude());
4134   EXPECT_TRUE(
4135       CreateAndSetCookieReturnStatus(&cm, https_url, "A=B;").IsInclude());
4136 
4137   // A SameParty cookie cannot be set without the Secure attribute.
4138   EXPECT_THAT(CreateAndSetCookieReturnStatus(&cm, https_url, "A=B; SameParty"),
4139               CookieInclusionStatus::MakeFromReasonsForTesting(
4140                   {CookieInclusionStatus::EXCLUDE_INVALID_SAMEPARTY}));
4141 
4142   // A SameParty cookie can be set from a URL with a secure scheme.
4143   EXPECT_TRUE(
4144       CreateAndSetCookieReturnStatus(&cm, https_url, "A=B; Secure; SameParty")
4145           .IsInclude());
4146 
4147   // If a non-SameParty cookie is created from a URL with an secure scheme, and
4148   // a SameParty cookie with the same name already exists, update the cookie.
4149   EXPECT_TRUE(
4150       CreateAndSetCookieReturnStatus(&cm, https_url, "A=B; Secure; SameParty")
4151           .IsInclude());
4152   EXPECT_TRUE(CreateAndSetCookieReturnStatus(&cm, https_url, "A=C; Secure;")
4153                   .IsInclude());
4154 
4155   DeleteAll(&cm);
4156 
4157   // If a SameParty cookie is set on top of an existing non-SameParty cookie but
4158   // with a different path, both are retained.
4159   EXPECT_TRUE(
4160       CreateAndSetCookieReturnStatus(&cm, https_url, "A=B; path=/foo; Secure")
4161           .IsInclude());
4162   EXPECT_TRUE(CreateAndSetCookieReturnStatus(&cm, https_url,
4163                                              "A=C; Secure; path=/; SameParty")
4164                   .IsInclude());
4165 }
4166 
4167 // Tests the behavior of "Leave Secure Cookies Alone" in
4168 // MaybeDeleteEquivalentCookieAndUpdateStatus().
4169 // Check domain-match criterion: If either cookie domain matches the other,
4170 // don't set the insecure cookie.
TEST_F(CookieMonsterTest,LeaveSecureCookiesAlone_DomainMatch)4171 TEST_F(CookieMonsterTest, LeaveSecureCookiesAlone_DomainMatch) {
4172   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
4173 
4174   // These domains will domain-match each other.
4175   const char* kRegistrableDomain = "foo.com";
4176   const char* kSuperdomain = "a.foo.com";
4177   const char* kDomain = "b.a.foo.com";
4178   const char* kSubdomain = "c.b.a.foo.com";
4179   // This domain does not match any, aside from the registrable domain.
4180   const char* kAnotherDomain = "z.foo.com";
4181 
4182   for (const char* preexisting_cookie_host :
4183        {kRegistrableDomain, kSuperdomain, kDomain, kSubdomain}) {
4184     GURL preexisting_cookie_url(
4185         base::StrCat({url::kHttpsScheme, url::kStandardSchemeSeparator,
4186                       preexisting_cookie_host}));
4187     for (const char* new_cookie_host :
4188          {kRegistrableDomain, kSuperdomain, kDomain, kSubdomain}) {
4189       GURL https_url(base::StrCat(
4190           {url::kHttpsScheme, url::kStandardSchemeSeparator, new_cookie_host}));
4191       GURL http_url(base::StrCat(
4192           {url::kHttpScheme, url::kStandardSchemeSeparator, new_cookie_host}));
4193 
4194       // Preexisting Secure host and domain cookies.
4195       EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4196                       cm.get(), preexisting_cookie_url, "A=0; Secure")
4197                       .IsInclude());
4198       EXPECT_TRUE(
4199           CreateAndSetCookieReturnStatus(
4200               cm.get(), preexisting_cookie_url,
4201               base::StrCat({"B=0; Secure; Domain=", preexisting_cookie_host}))
4202               .IsInclude());
4203 
4204       // Don't set insecure cookie from an insecure URL if equivalent secure
4205       // cookie exists.
4206       EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=1")
4207                       .HasExactlyExclusionReasonsForTesting(
4208                           {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}))
4209           << "Insecure host cookie from " << http_url
4210           << " should not be set if equivalent secure host cookie from "
4211           << preexisting_cookie_url << " exists.";
4212       EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4213                       cm.get(), http_url,
4214                       base::StrCat({"A=2; Domain=", new_cookie_host}))
4215                       .HasExactlyExclusionReasonsForTesting(
4216                           {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}))
4217           << "Insecure domain cookie from " << http_url
4218           << " should not be set if equivalent secure host cookie from "
4219           << preexisting_cookie_url << " exists.";
4220       EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), http_url, "B=1")
4221                       .HasExactlyExclusionReasonsForTesting(
4222                           {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}))
4223           << "Insecure host cookie from " << http_url
4224           << " should not be set if equivalent secure domain cookie from "
4225           << preexisting_cookie_url << " exists.";
4226       EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4227                       cm.get(), http_url,
4228                       base::StrCat({"B=2; Domain=", new_cookie_host}))
4229                       .HasExactlyExclusionReasonsForTesting(
4230                           {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE}))
4231           << "Insecure domain cookie from " << http_url
4232           << " should not be set if equivalent secure domain cookie from "
4233           << preexisting_cookie_url << " exists.";
4234 
4235       // Allow setting insecure cookie from a secure URL even if equivalent
4236       // secure cookie exists.
4237       EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=3;")
4238                       .IsInclude())
4239           << "Insecure host cookie from " << https_url
4240           << " can be set even if equivalent secure host cookie from "
4241           << preexisting_cookie_url << " exists.";
4242       EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4243                       cm.get(), https_url,
4244                       base::StrCat({"A=4; Domain=", new_cookie_host}))
4245                       .IsInclude())
4246           << "Insecure domain cookie from " << https_url
4247           << " can be set even if equivalent secure host cookie from "
4248           << preexisting_cookie_url << " exists.";
4249       EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "B=3;")
4250                       .IsInclude())
4251           << "Insecure host cookie from " << https_url
4252           << " can be set even if equivalent secure domain cookie from "
4253           << preexisting_cookie_url << " exists.";
4254       EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4255                       cm.get(), https_url,
4256                       base::StrCat({"B=4; Domain=", new_cookie_host}))
4257                       .IsInclude())
4258           << "Insecure domain cookie from " << https_url
4259           << " can be set even if equivalent secure domain cookie from "
4260           << preexisting_cookie_url << " exists.";
4261 
4262       DeleteAll(cm.get());
4263     }
4264   }
4265 
4266   // Test non-domain-matching case. These sets should all be allowed because the
4267   // cookie is not equivalent.
4268   GURL nonmatching_https_url(base::StrCat(
4269       {url::kHttpsScheme, url::kStandardSchemeSeparator, kAnotherDomain}));
4270 
4271   for (const char* host : {kSuperdomain, kDomain, kSubdomain}) {
4272     GURL https_url(
4273         base::StrCat({url::kHttpsScheme, url::kStandardSchemeSeparator, host}));
4274     GURL http_url(
4275         base::StrCat({url::kHttpScheme, url::kStandardSchemeSeparator, host}));
4276 
4277     // Preexisting Secure host and domain cookies.
4278     EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), nonmatching_https_url,
4279                                                "A=0; Secure")
4280                     .IsInclude());
4281     EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4282                     cm.get(), nonmatching_https_url,
4283                     base::StrCat({"B=0; Secure; Domain=", kAnotherDomain}))
4284                     .IsInclude());
4285 
4286     // New cookie from insecure URL is set.
4287     EXPECT_TRUE(
4288         CreateAndSetCookieReturnStatus(cm.get(), http_url, "A=1;").IsInclude())
4289         << "Insecure host cookie from " << http_url
4290         << " can be set even if equivalent secure host cookie from "
4291         << nonmatching_https_url << " exists.";
4292     EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4293                     cm.get(), http_url, base::StrCat({"A=2; Domain=", host}))
4294                     .IsInclude())
4295         << "Insecure domain cookie from " << http_url
4296         << " can be set even if equivalent secure host cookie from "
4297         << nonmatching_https_url << " exists.";
4298     EXPECT_TRUE(
4299         CreateAndSetCookieReturnStatus(cm.get(), http_url, "B=1;").IsInclude())
4300         << "Insecure host cookie from " << http_url
4301         << " can be set even if equivalent secure domain cookie from "
4302         << nonmatching_https_url << " exists.";
4303     EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4304                     cm.get(), http_url, base::StrCat({"B=2; Domain=", host}))
4305                     .IsInclude())
4306         << "Insecure domain cookie from " << http_url
4307         << " can be set even if equivalent secure domain cookie from "
4308         << nonmatching_https_url << " exists.";
4309 
4310     // New cookie from secure URL is set.
4311     EXPECT_TRUE(
4312         CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=3;").IsInclude())
4313         << "Insecure host cookie from " << https_url
4314         << " can be set even if equivalent secure host cookie from "
4315         << nonmatching_https_url << " exists.";
4316     EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4317                     cm.get(), https_url, base::StrCat({"A=4; Domain=", host}))
4318                     .IsInclude())
4319         << "Insecure domain cookie from " << https_url
4320         << " can be set even if equivalent secure host cookie from "
4321         << nonmatching_https_url << " exists.";
4322     EXPECT_TRUE(
4323         CreateAndSetCookieReturnStatus(cm.get(), https_url, "B=3;").IsInclude())
4324         << "Insecure host cookie from " << https_url
4325         << " can be set even if equivalent secure host cookie from "
4326         << nonmatching_https_url << " exists.";
4327     EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4328                     cm.get(), https_url, base::StrCat({"B=4; Domain=", host}))
4329                     .IsInclude())
4330         << "Insecure domain cookie from " << https_url
4331         << " can be set even if equivalent secure host cookie from "
4332         << nonmatching_https_url << " exists.";
4333 
4334     DeleteAll(cm.get());
4335   }
4336 }
4337 
4338 // Tests the behavior of "Leave Secure Cookies Alone" in
4339 // MaybeDeleteEquivalentCookieAndUpdateStatus().
4340 // Check path-match criterion: If the new cookie is for the same path or a
4341 // subdirectory of the preexisting cookie's path, don't set the new cookie.
TEST_F(CookieMonsterTest,LeaveSecureCookiesAlone_PathMatch)4342 TEST_F(CookieMonsterTest, LeaveSecureCookiesAlone_PathMatch) {
4343   auto cm = std::make_unique<CookieMonster>(nullptr, net::NetLog::Get());
4344 
4345   // A path that is later in this list will path-match all the paths before it.
4346   const char* kPaths[] = {"/", "/1", "/1/2", "/1/2/3"};
4347   // This path does not match any, aside from the root path.
4348   const char* kOtherDirectory = "/9";
4349 
4350   for (int preexisting_cookie_path_index = 0; preexisting_cookie_path_index < 4;
4351        ++preexisting_cookie_path_index) {
4352     const char* preexisting_cookie_path = kPaths[preexisting_cookie_path_index];
4353     GURL preexisting_cookie_url(
4354         base::StrCat({url::kHttpsScheme, url::kStandardSchemeSeparator,
4355                       "a.foo.com", preexisting_cookie_path}));
4356     for (int new_cookie_path_index = 0; new_cookie_path_index < 4;
4357          ++new_cookie_path_index) {
4358       const char* new_cookie_path = kPaths[new_cookie_path_index];
4359       bool should_path_match =
4360           new_cookie_path_index >= preexisting_cookie_path_index;
4361       GURL https_url(
4362           base::StrCat({url::kHttpsScheme, url::kStandardSchemeSeparator,
4363                         "a.foo.com", new_cookie_path}));
4364       GURL http_url(
4365           base::StrCat({url::kHttpScheme, url::kStandardSchemeSeparator,
4366                         "a.foo.com", new_cookie_path}));
4367 
4368       // Preexisting Secure cookie.
4369       EXPECT_TRUE(
4370           CreateAndSetCookieReturnStatus(
4371               cm.get(), preexisting_cookie_url,
4372               base::StrCat({"A=0; Secure; Path=", preexisting_cookie_path}))
4373               .IsInclude());
4374 
4375       // Don't set insecure cookie from an insecure URL if equivalent secure
4376       // cookie exists.
4377       CookieInclusionStatus set = CreateAndSetCookieReturnStatus(
4378           cm.get(), http_url, base::StrCat({"A=1; Path=", new_cookie_path}));
4379       EXPECT_TRUE(should_path_match
4380                       ? set.HasExactlyExclusionReasonsForTesting(
4381                             {CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE})
4382                       : set.IsInclude())
4383           << "Insecure cookie from " << http_url << " should "
4384           << (should_path_match ? "not " : "")
4385           << "be set if equivalent secure cookie from "
4386           << preexisting_cookie_url << " exists.";
4387 
4388       // Allow setting insecure cookie from a secure URL even if equivalent
4389       // secure cookie exists.
4390       EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4391                       cm.get(), https_url,
4392                       base::StrCat({"A=2; Path=", new_cookie_path}))
4393                       .IsInclude())
4394           << "Insecure cookie from " << http_url
4395           << " can be set even if equivalent secure cookie from "
4396           << preexisting_cookie_url << " exists.";
4397 
4398       DeleteAll(cm.get());
4399     }
4400   }
4401 
4402   // Test non-matching-path case. These sets should all be allowed because the
4403   // cookie is not equivalent.
4404   GURL nonmatching_https_url(
4405       base::StrCat({url::kHttpsScheme, url::kStandardSchemeSeparator,
4406                     "a.foo.com", kOtherDirectory}));
4407 
4408   for (int new_cookie_path_index = 1; new_cookie_path_index < 4;
4409        ++new_cookie_path_index) {
4410     const char* new_cookie_path = kPaths[new_cookie_path_index];
4411     GURL https_url(base::StrCat(
4412         {url::kHttpsScheme, url::kStandardSchemeSeparator, new_cookie_path}));
4413     GURL http_url(base::StrCat(
4414         {url::kHttpScheme, url::kStandardSchemeSeparator, new_cookie_path}));
4415 
4416     // Preexisting Secure cookie.
4417     EXPECT_TRUE(CreateAndSetCookieReturnStatus(
4418                     cm.get(), nonmatching_https_url,
4419                     base::StrCat({"A=0; Secure; Path=", kOtherDirectory}))
4420                     .IsInclude());
4421 
4422     // New cookie from insecure URL is set.
4423     EXPECT_TRUE(
4424         CreateAndSetCookieReturnStatus(
4425             cm.get(), http_url, base::StrCat({"A=1; Path=", new_cookie_path}))
4426             .IsInclude())
4427         << "Insecure cookie from " << http_url
4428         << " can be set even if equivalent secure cookie from "
4429         << nonmatching_https_url << " exists.";
4430 
4431     // New cookie from secure URL is set.
4432     EXPECT_TRUE(
4433         CreateAndSetCookieReturnStatus(
4434             cm.get(), https_url, base::StrCat({"A=1; Path=", new_cookie_path}))
4435             .IsInclude())
4436         << "Insecure cookie from " << https_url
4437         << " can be set even if equivalent secure cookie from "
4438         << nonmatching_https_url << " exists.";
4439   }
4440 }
4441 
4442 // Tests for behavior for strict secure cookies.
TEST_F(CookieMonsterTest,EvictSecureCookies)4443 TEST_F(CookieMonsterTest, EvictSecureCookies) {
4444   // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint.
4445   DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies);
4446   DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies -
4447                       CookieMonster::kDomainPurgeCookies);
4448   DCHECK_EQ(3300U, CookieMonster::kMaxCookies);
4449   DCHECK_EQ(30, CookieMonster::kSafeFromGlobalPurgeDays);
4450 
4451   // If secure cookies for one domain hit the per domain limit (180), a
4452   // non-secure cookie will not evict them (and, in fact, the non-secure cookie
4453   // will be removed right after creation).
4454   const CookiesEntry test1[] = {{180U, true}, {1U, false}};
4455   TestSecureCookieEviction(test1, 150U, 0U, nullptr);
4456 
4457   // If non-secure cookies for one domain hit the per domain limit (180), the
4458   // creation of secure cookies will evict the non-secure cookies first, making
4459   // room for the secure cookies.
4460   const CookiesEntry test2[] = {{180U, false}, {20U, true}};
4461   TestSecureCookieEviction(test2, 20U, 149U, nullptr);
4462 
4463   // If secure cookies for one domain go past the per domain limit (180), they
4464   // will be evicted as normal by the per domain purge amount (30) down to a
4465   // lower amount (150), and then will continue to create the remaining cookies
4466   // (19 more to 169).
4467   const CookiesEntry test3[] = {{200U, true}};
4468   TestSecureCookieEviction(test3, 169U, 0U, nullptr);
4469 
4470   // If a non-secure cookie is created, and a number of secure cookies exceeds
4471   // the per domain limit (18), the total cookies will be evicted down to a
4472   // lower amount (150), enforcing the eviction of the non-secure cookie, and
4473   // the remaining secure cookies will be created (another 19 to 169).
4474   const CookiesEntry test4[] = {{1U, false}, {199U, true}};
4475   TestSecureCookieEviction(test4, 169U, 0U, nullptr);
4476 
4477   // If an even number of non-secure and secure cookies are created below the
4478   // per-domain limit (180), all will be created and none evicted.
4479   const CookiesEntry test5[] = {{75U, false}, {75U, true}};
4480   TestSecureCookieEviction(test5, 75U, 75U, nullptr);
4481 
4482   // If the same number of secure and non-secure cookies are created (50 each)
4483   // below the per domain limit (180), and then another set of secure cookies
4484   // are created to bring the total above the per-domain limit, all secure
4485   // cookies will be retained, and the non-secure cookies will be culled down
4486   // to the limit.
4487   const CookiesEntry test6[] = {{50U, true}, {50U, false}, {81U, true}};
4488   TestSecureCookieEviction(test6, 131U, 19U, nullptr);
4489 
4490   // If the same number of non-secure and secure cookies are created (50 each)
4491   // below the per domain limit (180), and then another set of non-secure
4492   // cookies are created to bring the total above the per-domain limit, all
4493   // secure cookies will be retained, and the non-secure cookies will be culled
4494   // down to the limit.
4495   const CookiesEntry test7[] = {{50U, false}, {50U, true}, {81U, false}};
4496   TestSecureCookieEviction(test7, 50U, 100U, nullptr);
4497 
4498   // If the same number of non-secure and secure cookies are created (50 each)
4499   // below the per domain limit (180), and then another set of non-secure
4500   // cookies are created to bring the total above the per-domain limit, all
4501   // secure cookies will be retained, and the non-secure cookies will be culled
4502   // down to the limit, then the remaining non-secure cookies will be created
4503   // (9).
4504   const CookiesEntry test8[] = {{50U, false}, {50U, true}, {90U, false}};
4505   TestSecureCookieEviction(test8, 50U, 109U, nullptr);
4506 
4507   // If a number of non-secure cookies are created on other hosts (20) and are
4508   // past the global 'safe' date, and then the number of non-secure cookies for
4509   // a single domain are brought to the per-domain limit (180), followed by
4510   // another set of secure cookies on that same domain (20), all the secure
4511   // cookies for that domain should be retained, while the non-secure should be
4512   // culled down to the per-domain limit. The non-secure cookies for other
4513   // domains should remain untouched.
4514   const CookiesEntry test9[] = {{180U, false}, {20U, true}};
4515   const AltHosts test9_alt_hosts(0, 20);
4516   TestSecureCookieEviction(test9, 20U, 169U, &test9_alt_hosts);
4517 
4518   // If a number of secure cookies are created on other hosts and hit the global
4519   // cookie limit (3300) and are past the global 'safe' date, and then a single
4520   // non-secure cookie is created now, the secure cookies are removed so that
4521   // the global total number of cookies is at the global purge goal (3000), but
4522   // the non-secure cookie is not evicted since it is too young.
4523   const CookiesEntry test10[] = {{1U, false}};
4524   const AltHosts test10_alt_hosts(3300, 0);
4525   TestSecureCookieEviction(test10, 2999U, 1U, &test10_alt_hosts);
4526 
4527   // If a number of non-secure cookies are created on other hosts and hit the
4528   // global cookie limit (3300) and are past the global 'safe' date, and then a
4529   // single non-secure cookie is created now, the non-secure cookies are removed
4530   // so that the global total number of cookies is at the global purge goal
4531   // (3000).
4532   const CookiesEntry test11[] = {{1U, false}};
4533   const AltHosts test11_alt_hosts(0, 3300);
4534   TestSecureCookieEviction(test11, 0U, 3000U, &test11_alt_hosts);
4535 
4536   // If a number of non-secure cookies are created on other hosts and hit the
4537   // global cookie limit (3300) and are past the global 'safe' date, and then a
4538   // single ecure cookie is created now, the non-secure cookies are removed so
4539   // that the global total number of cookies is at the global purge goal (3000),
4540   // but the secure cookie is not evicted.
4541   const CookiesEntry test12[] = {{1U, true}};
4542   const AltHosts test12_alt_hosts(0, 3300);
4543   TestSecureCookieEviction(test12, 1U, 2999U, &test12_alt_hosts);
4544 
4545   // If a total number of secure and non-secure cookies are created on other
4546   // hosts and hit the global cookie limit (3300) and are past the global 'safe'
4547   // date, and then a single non-secure cookie is created now, the global
4548   // non-secure cookies are removed so that the global total number of cookies
4549   // is at the global purge goal (3000), but the secure cookies are not evicted.
4550   const CookiesEntry test13[] = {{1U, false}};
4551   const AltHosts test13_alt_hosts(1500, 1800);
4552   TestSecureCookieEviction(test13, 1500U, 1500, &test13_alt_hosts);
4553 
4554   // If a total number of secure and non-secure cookies are created on other
4555   // hosts and hit the global cookie limit (3300) and are past the global 'safe'
4556   // date, and then a single secure cookie is created now, the global non-secure
4557   // cookies are removed so that the global total number of cookies is at the
4558   // global purge goal (3000), but the secure cookies are not evicted.
4559   const CookiesEntry test14[] = {{1U, true}};
4560   const AltHosts test14_alt_hosts(1500, 1800);
4561   TestSecureCookieEviction(test14, 1501U, 1499, &test14_alt_hosts);
4562 }
4563 
4564 // Tests that strict secure cookies doesn't trip equivalent cookie checks
4565 // accidentally. Regression test for https://crbug.com/569943.
TEST_F(CookieMonsterTest,EquivalentCookies)4566 TEST_F(CookieMonsterTest, EquivalentCookies) {
4567   auto cm = std::make_unique<CookieMonster>(nullptr, nullptr);
4568   GURL http_url("http://www.foo.com");
4569   GURL http_superdomain_url("http://foo.com");
4570   GURL https_url("https://www.foo.com");
4571 
4572   // Tests that non-equivalent cookies because of the path attribute can be set
4573   // successfully.
4574   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")
4575                   .IsInclude());
4576   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url,
4577                                              "A=C; path=/some/other/path")
4578                   .IsInclude());
4579   EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; path=/some/other/path"));
4580 
4581   // Tests that non-equivalent cookies because of the domain attribute can be
4582   // set successfully.
4583   EXPECT_TRUE(CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=B; Secure")
4584                   .IsInclude());
4585   EXPECT_TRUE(
4586       CreateAndSetCookieReturnStatus(cm.get(), https_url, "A=C; domain=foo.com")
4587           .IsInclude());
4588   EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; domain=foo.com"));
4589 }
4590 
TEST_F(CookieMonsterTest,SetCanonicalCookieDoesNotBlockForLoadAll)4591 TEST_F(CookieMonsterTest, SetCanonicalCookieDoesNotBlockForLoadAll) {
4592   scoped_refptr<MockPersistentCookieStore> persistent_store =
4593       base::MakeRefCounted<MockPersistentCookieStore>();
4594   // Collect load commands so we have control over their execution.
4595   persistent_store->set_store_load_commands(true);
4596   CookieMonster cm(persistent_store.get(), nullptr);
4597 
4598   // Start of a canonical cookie set.
4599   ResultSavingCookieCallback<CookieAccessResult> callback_set;
4600   GURL cookie_url("http://a.com/");
4601   cm.SetCanonicalCookieAsync(
4602       CanonicalCookie::Create(cookie_url, "A=B", base::Time::Now(),
4603                               absl::nullopt /* server_time */,
4604                               absl::nullopt /* cookie_partition_key */),
4605       cookie_url, CookieOptions::MakeAllInclusive(),
4606       callback_set.MakeCallback());
4607 
4608   // Get cookies for a different URL.
4609   GetCookieListCallback callback_get;
4610   cm.GetCookieListWithOptionsAsync(
4611       GURL("http://b.com/"), CookieOptions::MakeAllInclusive(),
4612       CookiePartitionKeyCollection(), callback_get.MakeCallback());
4613 
4614   // Now go through the store commands, and execute individual loads.
4615   const auto& commands = persistent_store->commands();
4616   for (size_t i = 0; i < commands.size(); ++i) {
4617     if (commands[i].type == CookieStoreCommand::LOAD_COOKIES_FOR_KEY)
4618       persistent_store->TakeCallbackAt(i).Run(
4619           std::vector<std::unique_ptr<CanonicalCookie>>());
4620   }
4621 
4622   // This should be enough for both individual commands.
4623   callback_set.WaitUntilDone();
4624   callback_get.WaitUntilDone();
4625 
4626   // Now execute full-store loads as well.
4627   for (size_t i = 0; i < commands.size(); ++i) {
4628     if (commands[i].type == CookieStoreCommand::LOAD)
4629       persistent_store->TakeCallbackAt(i).Run(
4630           std::vector<std::unique_ptr<CanonicalCookie>>());
4631   }
4632 }
4633 
TEST_F(CookieMonsterTest,DeleteDuplicateCTime)4634 TEST_F(CookieMonsterTest, DeleteDuplicateCTime) {
4635   const char* const kNames[] = {"A", "B", "C"};
4636 
4637   // Tests that DeleteCanonicalCookie properly distinguishes different cookies
4638   // (e.g. different name or path) with identical ctime on same domain.
4639   // This gets tested a few times with different deletion target, to make sure
4640   // that the implementation doesn't just happen to pick the right one because
4641   // of implementation details.
4642   for (const auto* name : kNames) {
4643     CookieMonster cm(nullptr, nullptr);
4644     Time now = Time::Now();
4645     GURL url("http://www.example.com");
4646 
4647     for (size_t i = 0; i < std::size(kNames); ++i) {
4648       std::string cookie_string =
4649           base::StrCat({kNames[i], "=", base::NumberToString(i)});
4650       EXPECT_TRUE(SetCookieWithCreationTime(&cm, url, cookie_string, now));
4651     }
4652 
4653     // Delete the run'th cookie.
4654     CookieList all_cookies = GetAllCookiesForURLWithOptions(
4655         &cm, url, CookieOptions::MakeAllInclusive());
4656     ASSERT_EQ(all_cookies.size(), std::size(kNames));
4657     for (size_t i = 0; i < std::size(kNames); ++i) {
4658       const CanonicalCookie& cookie = all_cookies[i];
4659       if (cookie.Name() == name) {
4660         EXPECT_TRUE(DeleteCanonicalCookie(&cm, cookie));
4661       }
4662     }
4663 
4664     // Check that the right cookie got removed.
4665     all_cookies = GetAllCookiesForURLWithOptions(
4666         &cm, url, CookieOptions::MakeAllInclusive());
4667     ASSERT_EQ(all_cookies.size(), std::size(kNames) - 1);
4668     for (size_t i = 0; i < std::size(kNames) - 1; ++i) {
4669       const CanonicalCookie& cookie = all_cookies[i];
4670       EXPECT_NE(cookie.Name(), name);
4671     }
4672   }
4673 }
4674 
TEST_F(CookieMonsterTest,DeleteCookieWithInheritedTimestamps)4675 TEST_F(CookieMonsterTest, DeleteCookieWithInheritedTimestamps) {
4676   Time t1 = Time::Now();
4677   Time t2 = t1 + base::Seconds(1);
4678   GURL url("http://www.example.com");
4679   std::string cookie_line = "foo=bar";
4680   CookieOptions options = CookieOptions::MakeAllInclusive();
4681   absl::optional<base::Time> server_time = absl::nullopt;
4682   absl::optional<CookiePartitionKey> partition_key = absl::nullopt;
4683   CookieMonster cm(nullptr, nullptr);
4684 
4685   // Write a cookie created at |t1|.
4686   auto cookie =
4687       CanonicalCookie::Create(url, cookie_line, t1, server_time, partition_key);
4688   ResultSavingCookieCallback<CookieAccessResult> set_callback_1;
4689   cm.SetCanonicalCookieAsync(std::move(cookie), url, options,
4690                              set_callback_1.MakeCallback());
4691   set_callback_1.WaitUntilDone();
4692 
4693   // Overwrite the cookie at |t2|.
4694   cookie =
4695       CanonicalCookie::Create(url, cookie_line, t2, server_time, partition_key);
4696   ResultSavingCookieCallback<CookieAccessResult> set_callback_2;
4697   cm.SetCanonicalCookieAsync(std::move(cookie), url, options,
4698                              set_callback_2.MakeCallback());
4699   set_callback_2.WaitUntilDone();
4700 
4701   // The second cookie overwrites the first one but it will inherit the creation
4702   // timestamp |t1|. Test that deleting the new cookie still works.
4703   cookie =
4704       CanonicalCookie::Create(url, cookie_line, t2, server_time, partition_key);
4705   ResultSavingCookieCallback<unsigned int> delete_callback;
4706   cm.DeleteCanonicalCookieAsync(*cookie, delete_callback.MakeCallback());
4707   delete_callback.WaitUntilDone();
4708   EXPECT_EQ(1U, delete_callback.result());
4709 }
4710 
TEST_F(CookieMonsterTest,RejectCreatedSameSiteCookieOnSet)4711 TEST_F(CookieMonsterTest, RejectCreatedSameSiteCookieOnSet) {
4712   GURL url("http://www.example.com");
4713   std::string cookie_line = "foo=bar; SameSite=Lax";
4714 
4715   CookieMonster cm(nullptr, nullptr);
4716   CookieOptions env_cross_site;
4717   env_cross_site.set_same_site_cookie_context(
4718       CookieOptions::SameSiteCookieContext(
4719           CookieOptions::SameSiteCookieContext::ContextType::CROSS_SITE));
4720 
4721   CookieInclusionStatus status;
4722   // Cookie can be created successfully; SameSite is not checked on Creation.
4723   auto cookie = CanonicalCookie::Create(
4724       url, cookie_line, base::Time::Now(), absl::nullopt /* server_time */,
4725       absl::nullopt /* cookie_partition_key */, &status);
4726   ASSERT_TRUE(cookie != nullptr);
4727   ASSERT_TRUE(status.IsInclude());
4728 
4729   // ... but the environment is checked on set, so this may be rejected then.
4730   ResultSavingCookieCallback<CookieAccessResult> callback;
4731   cm.SetCanonicalCookieAsync(std::move(cookie), url, env_cross_site,
4732                              callback.MakeCallback());
4733   callback.WaitUntilDone();
4734   EXPECT_TRUE(callback.result().status.HasExactlyExclusionReasonsForTesting(
4735       {CookieInclusionStatus::EXCLUDE_SAMESITE_LAX}));
4736 }
4737 
TEST_F(CookieMonsterTest,RejectCreatedSecureCookieOnSet)4738 TEST_F(CookieMonsterTest, RejectCreatedSecureCookieOnSet) {
4739   GURL http_url("http://www.example.com");
4740   std::string cookie_line = "foo=bar; Secure";
4741 
4742   CookieMonster cm(nullptr, nullptr);
4743   CookieInclusionStatus status;
4744   // Cookie can be created successfully from an any url. Secure is not checked
4745   // on Create.
4746   auto cookie = CanonicalCookie::Create(
4747       http_url, cookie_line, base::Time::Now(), absl::nullopt /* server_time */,
4748       absl::nullopt /* cookie_partition_key */, &status);
4749 
4750   ASSERT_TRUE(cookie != nullptr);
4751   ASSERT_TRUE(status.IsInclude());
4752 
4753   // Cookie is rejected when attempting to set from a non-secure scheme.
4754   ResultSavingCookieCallback<CookieAccessResult> callback;
4755   cm.SetCanonicalCookieAsync(std::move(cookie), http_url,
4756                              CookieOptions::MakeAllInclusive(),
4757                              callback.MakeCallback());
4758   callback.WaitUntilDone();
4759   EXPECT_TRUE(callback.result().status.HasExactlyExclusionReasonsForTesting(
4760       {CookieInclusionStatus::EXCLUDE_SECURE_ONLY}));
4761 }
4762 
TEST_F(CookieMonsterTest,RejectCreatedHttpOnlyCookieOnSet)4763 TEST_F(CookieMonsterTest, RejectCreatedHttpOnlyCookieOnSet) {
4764   GURL url("http://www.example.com");
4765   std::string cookie_line = "foo=bar; HttpOnly";
4766 
4767   CookieMonster cm(nullptr, nullptr);
4768   CookieInclusionStatus status;
4769   // Cookie can be created successfully; HttpOnly is not checked on Create.
4770   auto cookie = CanonicalCookie::Create(
4771       url, cookie_line, base::Time::Now(), absl::nullopt /* server_time */,
4772       absl::nullopt /* cookie_partition_key */, &status);
4773 
4774   ASSERT_TRUE(cookie != nullptr);
4775   ASSERT_TRUE(status.IsInclude());
4776 
4777   // Cookie is rejected when attempting to set with a CookieOptions that does
4778   // not allow httponly.
4779   CookieOptions options_no_httponly;
4780   options_no_httponly.set_same_site_cookie_context(
4781       CookieOptions::SameSiteCookieContext(
4782           CookieOptions::SameSiteCookieContext::ContextType::SAME_SITE_STRICT));
4783   options_no_httponly.set_exclude_httponly();  // Default, but make it explicit.
4784   ResultSavingCookieCallback<CookieAccessResult> callback;
4785   cm.SetCanonicalCookieAsync(std::move(cookie), url, options_no_httponly,
4786                              callback.MakeCallback());
4787   callback.WaitUntilDone();
4788   EXPECT_TRUE(callback.result().status.HasExactlyExclusionReasonsForTesting(
4789       {CookieInclusionStatus::EXCLUDE_HTTP_ONLY}));
4790 }
4791 
4792 // Test that SameSite=None requires Secure.
TEST_F(CookieMonsterTest,CookiesWithoutSameSiteMustBeSecure)4793 TEST_F(CookieMonsterTest, CookiesWithoutSameSiteMustBeSecure) {
4794   const base::TimeDelta kLongAge = kLaxAllowUnsafeMaxAge * 4;
4795   const base::TimeDelta kShortAge = kLaxAllowUnsafeMaxAge / 4;
4796 
4797   struct TestCase {
4798     bool is_url_secure;
4799     std::string cookie_line;
4800     CookieInclusionStatus expected_set_cookie_result;
4801     // Only makes sense to check if result is INCLUDE:
4802     CookieEffectiveSameSite expected_effective_samesite =
4803         CookieEffectiveSameSite::NO_RESTRICTION;
4804     base::TimeDelta creation_time_delta = base::TimeDelta();
4805   } test_cases[] = {
4806       // Feature enabled:
4807       // Cookie set from a secure URL with SameSite enabled is not rejected.
4808       {true, "A=B; SameSite=Lax", CookieInclusionStatus(),
4809        CookieEffectiveSameSite::LAX_MODE},
4810       // Cookie set from a secure URL which is defaulted into Lax is not
4811       // rejected.
4812       {true, "A=B",  // recently-set session cookie.
4813        CookieInclusionStatus(), CookieEffectiveSameSite::LAX_MODE_ALLOW_UNSAFE,
4814        kShortAge},
4815       {true, "A=B",  // not-recently-set session cookie.
4816        CookieInclusionStatus(), CookieEffectiveSameSite::LAX_MODE, kLongAge},
4817       // Cookie set from a secure URL with SameSite=None and Secure is set.
4818       {true, "A=B; SameSite=None; Secure", CookieInclusionStatus(),
4819        CookieEffectiveSameSite::NO_RESTRICTION},
4820       // Cookie set from a secure URL with SameSite=None but not specifying
4821       // Secure is rejected.
4822       {true, "A=B; SameSite=None",
4823        CookieInclusionStatus(
4824            CookieInclusionStatus::EXCLUDE_SAMESITE_NONE_INSECURE,
4825            CookieInclusionStatus::WARN_SAMESITE_NONE_INSECURE)},
4826       // Cookie set from an insecure URL which defaults into LAX_MODE is not
4827       // rejected.
4828       {false, "A=B",  // recently-set session cookie.
4829        CookieInclusionStatus(), CookieEffectiveSameSite::LAX_MODE_ALLOW_UNSAFE,
4830        kShortAge},
4831       {false, "A=B",  // not-recently-set session cookie.
4832        CookieInclusionStatus(), CookieEffectiveSameSite::LAX_MODE, kLongAge},
4833       {false, "A=B; Max-Age=1000000",  // recently-set persistent cookie.
4834        CookieInclusionStatus(), CookieEffectiveSameSite::LAX_MODE_ALLOW_UNSAFE,
4835        kShortAge},
4836       {false,
4837        "A=B; Max-Age=1000000",  // not-recently-set persistent cookie.
4838        CookieInclusionStatus(), CookieEffectiveSameSite::LAX_MODE, kLongAge},
4839   };
4840 
4841   auto cm = std::make_unique<CookieMonster>(nullptr, nullptr);
4842   GURL secure_url("https://www.example1.test");
4843   GURL insecure_url("http://www.example2.test");
4844 
4845   int length = sizeof(test_cases) / sizeof(test_cases[0]);
4846   for (int i = 0; i < length; ++i) {
4847     TestCase test = test_cases[i];
4848 
4849     GURL url = test.is_url_secure ? secure_url : insecure_url;
4850     base::Time creation_time = base::Time::Now() - test.creation_time_delta;
4851     auto cookie = CanonicalCookie::Create(
4852         url, test.cookie_line, creation_time, absl::nullopt /* server_time */,
4853         absl::nullopt /* cookie_partition_key */);
4854     // Make a copy so we can delete it after the test.
4855     CanonicalCookie cookie_copy = *cookie;
4856     CookieAccessResult result = SetCanonicalCookieReturnAccessResult(
4857         cm.get(), std::move(cookie), url,
4858         true /* can_modify_httponly (irrelevant) */);
4859     EXPECT_EQ(test.expected_set_cookie_result, result.status)
4860         << "Test case " << i << " failed.";
4861     if (result.status.IsInclude()) {
4862       auto cookies = GetAllCookiesForURL(cm.get(), url);
4863       ASSERT_EQ(1u, cookies.size());
4864       EXPECT_EQ(test.expected_effective_samesite, result.effective_same_site)
4865           << "Test case " << i << " failed.";
4866       DeleteCanonicalCookie(cm.get(), cookie_copy);
4867     }
4868   }
4869 }
4870 
4871 class CookieMonsterNotificationTest : public CookieMonsterTest {
4872  public:
CookieMonsterNotificationTest()4873   CookieMonsterNotificationTest()
4874       : test_url_("http://www.foo.com/foo"),
4875         store_(base::MakeRefCounted<MockPersistentCookieStore>()),
4876         monster_(std::make_unique<CookieMonster>(store_.get(), nullptr)) {}
4877 
4878   ~CookieMonsterNotificationTest() override = default;
4879 
monster()4880   CookieMonster* monster() { return monster_.get(); }
4881 
4882  protected:
4883   const GURL test_url_;
4884 
4885  private:
4886   scoped_refptr<MockPersistentCookieStore> store_;
4887   std::unique_ptr<CookieMonster> monster_;
4888 };
4889 
RecordCookieChanges(std::vector<CanonicalCookie> * out_cookies,std::vector<CookieChangeCause> * out_causes,const CookieChangeInfo & change)4890 void RecordCookieChanges(std::vector<CanonicalCookie>* out_cookies,
4891                          std::vector<CookieChangeCause>* out_causes,
4892                          const CookieChangeInfo& change) {
4893   DCHECK(out_cookies);
4894   out_cookies->push_back(change.cookie);
4895   if (out_causes)
4896     out_causes->push_back(change.cause);
4897 }
4898 
4899 // Tests that there are no changes emitted for cookie loading, but there are
4900 // changes emitted for other operations.
TEST_F(CookieMonsterNotificationTest,NoNotificationOnLoad)4901 TEST_F(CookieMonsterNotificationTest, NoNotificationOnLoad) {
4902   // Create a persistent store that will not synchronously satisfy the
4903   // loading requirement.
4904   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
4905   store->set_store_load_commands(true);
4906 
4907   // Bind it to a CookieMonster
4908   auto monster = std::make_unique<CookieMonster>(store.get(), nullptr);
4909 
4910   // Trigger load dispatch and confirm it.
4911   monster->GetAllCookiesAsync(CookieStore::GetAllCookiesCallback());
4912   ASSERT_EQ(1u, store->commands().size());
4913   EXPECT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type);
4914 
4915   // Attach a change subscription.
4916   std::vector<CanonicalCookie> cookies;
4917   std::vector<CookieChangeCause> causes;
4918   std::unique_ptr<CookieChangeSubscription> subscription =
4919       monster->GetChangeDispatcher().AddCallbackForAllChanges(
4920           base::BindRepeating(&RecordCookieChanges, &cookies, &causes));
4921 
4922   // Set up some initial cookies, including duplicates.
4923   std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies;
4924   GURL url("http://www.foo.com");
4925   initial_cookies.push_back(CanonicalCookie::Create(
4926       url, "X=1; path=/", base::Time::Now(), absl::nullopt /* server_time */,
4927       absl::nullopt /* cookie_partition_key */));
4928   initial_cookies.push_back(CanonicalCookie::Create(
4929       url, "Y=1; path=/", base::Time::Now(), absl::nullopt /* server_time */,
4930       absl::nullopt /* cookie_partition_key */));
4931   initial_cookies.push_back(CanonicalCookie::Create(
4932       url, "Y=2; path=/", base::Time::Now() + base::Days(1),
4933       absl::nullopt /* server_time */,
4934       absl::nullopt /* cookie_partition_key */));
4935 
4936   // Execute the load
4937   store->TakeCallbackAt(0).Run(std::move(initial_cookies));
4938   base::RunLoop().RunUntilIdle();
4939 
4940   // We should see no insertions (because loads do not cause notifications to be
4941   // dispatched), no deletions (because overwriting a duplicate cookie on load
4942   // does not trigger a notification), and two cookies in the monster.
4943   EXPECT_EQ(0u, cookies.size());
4944   EXPECT_EQ(0u, causes.size());
4945   EXPECT_EQ(2u, this->GetAllCookies(monster.get()).size());
4946 
4947   // Change the cookies again to make sure that other changes do emit
4948   // notifications.
4949   this->CreateAndSetCookie(monster.get(), url, "X=2; path=/",
4950                            CookieOptions::MakeAllInclusive());
4951   this->CreateAndSetCookie(monster.get(), url, "Y=3; path=/; max-age=0",
4952                            CookieOptions::MakeAllInclusive());
4953 
4954   base::RunLoop().RunUntilIdle();
4955   ASSERT_EQ(3u, cookies.size());
4956   ASSERT_EQ(3u, causes.size());
4957   EXPECT_EQ("X", cookies[0].Name());
4958   EXPECT_EQ("1", cookies[0].Value());
4959   EXPECT_EQ(CookieChangeCause::OVERWRITE, causes[0]);
4960   EXPECT_EQ("X", cookies[1].Name());
4961   EXPECT_EQ("2", cookies[1].Value());
4962   EXPECT_EQ(CookieChangeCause::INSERTED, causes[1]);
4963   EXPECT_EQ("Y", cookies[2].Name());
4964   EXPECT_EQ("2", cookies[2].Value());
4965   EXPECT_EQ(CookieChangeCause::EXPIRED_OVERWRITE, causes[2]);
4966 }
4967 
4968 class CookieMonsterLegacyCookieAccessTest : public CookieMonsterTest {
4969  public:
CookieMonsterLegacyCookieAccessTest()4970   CookieMonsterLegacyCookieAccessTest()
4971       : cm_(std::make_unique<CookieMonster>(nullptr /* store */,
4972                                             nullptr /* netlog */
4973                                             )) {
4974     // Need to reset first because there cannot be two TaskEnvironments at the
4975     // same time.
4976     task_environment_.reset();
4977     task_environment_ =
4978         std::make_unique<base::test::SingleThreadTaskEnvironment>(
4979             base::test::TaskEnvironment::TimeSource::MOCK_TIME);
4980 
4981     std::unique_ptr<TestCookieAccessDelegate> access_delegate =
4982         std::make_unique<TestCookieAccessDelegate>();
4983     access_delegate_ = access_delegate.get();
4984     cm_->SetCookieAccessDelegate(std::move(access_delegate));
4985   }
4986 
4987   ~CookieMonsterLegacyCookieAccessTest() override = default;
4988 
4989  protected:
4990   const std::string kDomain = "example.test";
4991   const GURL kHttpsUrl = GURL("https://example.test");
4992   const GURL kHttpUrl = GURL("http://example.test");
4993   std::unique_ptr<CookieMonster> cm_;
4994   raw_ptr<TestCookieAccessDelegate> access_delegate_;
4995 };
4996 
TEST_F(CookieMonsterLegacyCookieAccessTest,SetLegacyNoSameSiteCookie)4997 TEST_F(CookieMonsterLegacyCookieAccessTest, SetLegacyNoSameSiteCookie) {
4998   // Check that setting unspecified-SameSite cookie from cross-site context
4999   // fails if not set to Legacy semantics, but succeeds if set to legacy.
5000   EXPECT_FALSE(CreateAndSetCookie(cm_.get(), kHttpUrl, "cookie=chocolate_chip",
5001                                   CookieOptions()));
5002   access_delegate_->SetExpectationForCookieDomain(
5003       kDomain, CookieAccessSemantics::UNKNOWN);
5004   EXPECT_FALSE(CreateAndSetCookie(cm_.get(), kHttpUrl, "cookie=chocolate_chip",
5005                                   CookieOptions()));
5006   access_delegate_->SetExpectationForCookieDomain(
5007       kDomain, CookieAccessSemantics::NONLEGACY);
5008   EXPECT_FALSE(CreateAndSetCookie(cm_.get(), kHttpUrl, "cookie=chocolate_chip",
5009                                   CookieOptions()));
5010   access_delegate_->SetExpectationForCookieDomain(
5011       kDomain, CookieAccessSemantics::LEGACY);
5012   EXPECT_TRUE(CreateAndSetCookie(cm_.get(), kHttpUrl, "cookie=chocolate_chip",
5013                                  CookieOptions()));
5014 }
5015 
TEST_F(CookieMonsterLegacyCookieAccessTest,GetLegacyNoSameSiteCookie)5016 TEST_F(CookieMonsterLegacyCookieAccessTest, GetLegacyNoSameSiteCookie) {
5017   // Set a cookie with no SameSite attribute.
5018   ASSERT_TRUE(CreateAndSetCookie(cm_.get(), kHttpUrl, "cookie=chocolate_chip",
5019                                  CookieOptions::MakeAllInclusive()));
5020 
5021   // Getting the cookie fails unless semantics is legacy.
5022   access_delegate_->SetExpectationForCookieDomain(
5023       kDomain, CookieAccessSemantics::UNKNOWN);
5024   EXPECT_EQ("", GetCookiesWithOptions(cm_.get(), kHttpUrl, CookieOptions()));
5025   access_delegate_->SetExpectationForCookieDomain(
5026       kDomain, CookieAccessSemantics::NONLEGACY);
5027   EXPECT_EQ("", GetCookiesWithOptions(cm_.get(), kHttpUrl, CookieOptions()));
5028   access_delegate_->SetExpectationForCookieDomain(
5029       kDomain, CookieAccessSemantics::LEGACY);
5030   EXPECT_EQ("cookie=chocolate_chip",
5031             GetCookiesWithOptions(cm_.get(), kHttpUrl, CookieOptions()));
5032 }
5033 
TEST_F(CookieMonsterLegacyCookieAccessTest,SetLegacySameSiteNoneInsecureCookie)5034 TEST_F(CookieMonsterLegacyCookieAccessTest,
5035        SetLegacySameSiteNoneInsecureCookie) {
5036   access_delegate_->SetExpectationForCookieDomain(
5037       kDomain, CookieAccessSemantics::UNKNOWN);
5038   EXPECT_FALSE(CreateAndSetCookie(cm_.get(), kHttpsUrl,
5039                                   "cookie=oatmeal_raisin; SameSite=None",
5040                                   CookieOptions()));
5041   access_delegate_->SetExpectationForCookieDomain(
5042       kDomain, CookieAccessSemantics::NONLEGACY);
5043   EXPECT_FALSE(CreateAndSetCookie(cm_.get(), kHttpsUrl,
5044                                   "cookie=oatmeal_raisin; SameSite=None",
5045                                   CookieOptions()));
5046   // Setting the access semantics to legacy allows setting the cookie.
5047   access_delegate_->SetExpectationForCookieDomain(
5048       kDomain, CookieAccessSemantics::LEGACY);
5049   EXPECT_TRUE(CreateAndSetCookie(cm_.get(), kHttpsUrl,
5050                                  "cookie=oatmeal_raisin; SameSite=None",
5051                                  CookieOptions()));
5052   EXPECT_EQ("cookie=oatmeal_raisin",
5053             GetCookiesWithOptions(cm_.get(), kHttpsUrl, CookieOptions()));
5054 }
5055 
TEST_F(CookieMonsterLegacyCookieAccessTest,GetLegacySameSiteNoneInsecureCookie)5056 TEST_F(CookieMonsterLegacyCookieAccessTest,
5057        GetLegacySameSiteNoneInsecureCookie) {
5058   // Need to inject such a cookie under legacy semantics.
5059   access_delegate_->SetExpectationForCookieDomain(
5060       kDomain, CookieAccessSemantics::LEGACY);
5061   ASSERT_TRUE(CreateAndSetCookie(cm_.get(), kHttpUrl,
5062                                  "cookie=oatmeal_raisin; SameSite=None",
5063                                  CookieOptions::MakeAllInclusive()));
5064   // Getting a SameSite=None but non-Secure cookie fails unless semantics is
5065   // legacy.
5066   access_delegate_->SetExpectationForCookieDomain(
5067       kDomain, CookieAccessSemantics::UNKNOWN);
5068   EXPECT_EQ("", GetCookiesWithOptions(cm_.get(), kHttpUrl, CookieOptions()));
5069   access_delegate_->SetExpectationForCookieDomain(
5070       kDomain, CookieAccessSemantics::NONLEGACY);
5071   EXPECT_EQ("", GetCookiesWithOptions(cm_.get(), kHttpUrl, CookieOptions()));
5072   access_delegate_->SetExpectationForCookieDomain(
5073       kDomain, CookieAccessSemantics::LEGACY);
5074   EXPECT_EQ("cookie=oatmeal_raisin",
5075             GetCookiesWithOptions(cm_.get(), kHttpUrl, CookieOptions()));
5076 }
5077 
TEST_F(CookieMonsterTest,IsCookieSentToSamePortThatSetIt)5078 TEST_F(CookieMonsterTest, IsCookieSentToSamePortThatSetIt) {
5079   // Note: `IsCookieSentToSamePortThatSetIt()` only uses the source_scheme if
5080   // the port is valid, specified, and doesn't match the url's port. So for test
5081   // cases where the above aren't true the value of source_scheme is irreleant.
5082 
5083   // Test unspecified.
5084   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5085                 GURL("https://foo.com"), url::PORT_UNSPECIFIED,
5086                 CookieSourceScheme::kSecure),
5087             CookieMonster::CookieSentToSamePort::kSourcePortUnspecified);
5088 
5089   // Test invalid.
5090   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5091                 GURL("https://foo.com"), url::PORT_INVALID,
5092                 CookieSourceScheme::kSecure),
5093             CookieMonster::CookieSentToSamePort::kInvalid);
5094 
5095   // Test same.
5096   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5097                 GURL("https://foo.com"), 443, CookieSourceScheme::kSecure),
5098             CookieMonster::CookieSentToSamePort::kYes);
5099 
5100   ASSERT_EQ(
5101       CookieMonster::IsCookieSentToSamePortThatSetIt(
5102           GURL("https://foo.com:1234"), 1234, CookieSourceScheme::kSecure),
5103       CookieMonster::CookieSentToSamePort::kYes);
5104 
5105   // Test different but default.
5106   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5107                 GURL("https://foo.com"), 80, CookieSourceScheme::kNonSecure),
5108             CookieMonster::CookieSentToSamePort::kNoButDefault);
5109 
5110   ASSERT_EQ(
5111       CookieMonster::IsCookieSentToSamePortThatSetIt(
5112           GURL("https://foo.com:443"), 80, CookieSourceScheme::kNonSecure),
5113       CookieMonster::CookieSentToSamePort::kNoButDefault);
5114 
5115   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5116                 GURL("wss://foo.com"), 80, CookieSourceScheme::kNonSecure),
5117             CookieMonster::CookieSentToSamePort::kNoButDefault);
5118 
5119   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5120                 GURL("http://foo.com"), 443, CookieSourceScheme::kSecure),
5121             CookieMonster::CookieSentToSamePort::kNoButDefault);
5122 
5123   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5124                 GURL("ws://foo.com"), 443, CookieSourceScheme::kSecure),
5125             CookieMonster::CookieSentToSamePort::kNoButDefault);
5126 
5127   // Test different.
5128   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5129                 GURL("http://foo.com:9000"), 85, CookieSourceScheme::kSecure),
5130             CookieMonster::CookieSentToSamePort::kNo);
5131 
5132   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5133                 GURL("https://foo.com"), 80, CookieSourceScheme::kSecure),
5134             CookieMonster::CookieSentToSamePort::kNo);
5135 
5136   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5137                 GURL("wss://foo.com"), 80, CookieSourceScheme::kSecure),
5138             CookieMonster::CookieSentToSamePort::kNo);
5139 
5140   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5141                 GURL("http://foo.com"), 443, CookieSourceScheme::kNonSecure),
5142             CookieMonster::CookieSentToSamePort::kNo);
5143 
5144   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5145                 GURL("ws://foo.com"), 443, CookieSourceScheme::kNonSecure),
5146             CookieMonster::CookieSentToSamePort::kNo);
5147 
5148   ASSERT_EQ(CookieMonster::IsCookieSentToSamePortThatSetIt(
5149                 GURL("http://foo.com:444"), 443, CookieSourceScheme::kSecure),
5150             CookieMonster::CookieSentToSamePort::kNo);
5151 }
5152 
TEST_F(CookieMonsterTest,CookieDomainSetHistogram)5153 TEST_F(CookieMonsterTest, CookieDomainSetHistogram) {
5154   base::HistogramTester histograms;
5155   const char kHistogramName[] = "Cookie.DomainSet";
5156 
5157   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
5158   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5159 
5160   histograms.ExpectTotalCount(kHistogramName, 0);
5161 
5162   // Set a host only cookie (non-Domain).
5163   EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(), "A=B"));
5164   histograms.ExpectTotalCount(kHistogramName, 1);
5165   histograms.ExpectBucketCount(kHistogramName, false, 1);
5166 
5167   // Set a domain cookie.
5168   EXPECT_TRUE(SetCookie(cm.get(), https_www_foo_.url(),
5169                         "A=B; Domain=" + https_www_foo_.host()));
5170   histograms.ExpectTotalCount(kHistogramName, 2);
5171   histograms.ExpectBucketCount(kHistogramName, true, 1);
5172 
5173   // Invalid cookies don't count toward the histogram.
5174   EXPECT_FALSE(
5175       SetCookie(cm.get(), https_www_foo_.url(), "A=B; Domain=other.com"));
5176   histograms.ExpectTotalCount(kHistogramName, 2);
5177   histograms.ExpectBucketCount(kHistogramName, false, 1);
5178 }
5179 
TEST_F(CookieMonsterTest,CookiePortReadHistogram)5180 TEST_F(CookieMonsterTest, CookiePortReadHistogram) {
5181   base::HistogramTester histograms;
5182   const char kHistogramName[] = "Cookie.Port.Read.RemoteHost";
5183   const char kHistogramNameLocal[] = "Cookie.Port.Read.Localhost";
5184 
5185   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
5186   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5187 
5188   histograms.ExpectTotalCount(kHistogramName, 0);
5189 
5190   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://www.foo.com"), "A=B"));
5191 
5192   // May as well check that it didn't change the histogram...
5193   histograms.ExpectTotalCount(kHistogramName, 0);
5194 
5195   // Now read it from some different ports. This requires some knowledge of how
5196   // `ReducePortRangeForCookieHistogram` maps ports, but that's probably fine.
5197   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.foo.com")), "A=B");
5198   // https default is 443, so check that.
5199   histograms.ExpectTotalCount(kHistogramName, 1);
5200   histograms.ExpectBucketCount(kHistogramName,
5201                                ReducePortRangeForCookieHistogram(443), 1);
5202 
5203   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.foo.com:82")), "A=B");
5204   histograms.ExpectTotalCount(kHistogramName, 2);
5205   histograms.ExpectBucketCount(kHistogramName,
5206                                ReducePortRangeForCookieHistogram(82), 1);
5207 
5208   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.foo.com:8080")), "A=B");
5209   histograms.ExpectTotalCount(kHistogramName, 3);
5210   histograms.ExpectBucketCount(kHistogramName,
5211                                ReducePortRangeForCookieHistogram(8080), 1);
5212 
5213   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.foo.com:1234")), "A=B");
5214   histograms.ExpectTotalCount(kHistogramName, 4);
5215   histograms.ExpectBucketCount(kHistogramName,
5216                                ReducePortRangeForCookieHistogram(1234), 1);
5217 
5218   // Histogram should not increment if nothing is read.
5219   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.other.com")), "");
5220   histograms.ExpectTotalCount(kHistogramName, 4);
5221 
5222   // Make sure the correct histogram is chosen for localhost.
5223   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://localhost"), "local=host"));
5224 
5225   histograms.ExpectTotalCount(kHistogramNameLocal, 0);
5226 
5227   EXPECT_EQ(GetCookies(cm.get(), GURL("https://localhost:82")), "local=host");
5228   histograms.ExpectTotalCount(kHistogramNameLocal, 1);
5229   histograms.ExpectBucketCount(kHistogramNameLocal,
5230                                ReducePortRangeForCookieHistogram(82), 1);
5231 }
5232 
TEST_F(CookieMonsterTest,CookiePortSetHistogram)5233 TEST_F(CookieMonsterTest, CookiePortSetHistogram) {
5234   base::HistogramTester histograms;
5235   const char kHistogramName[] = "Cookie.Port.Set.RemoteHost";
5236   const char kHistogramNameLocal[] = "Cookie.Port.Set.Localhost";
5237 
5238   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
5239   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5240 
5241   histograms.ExpectTotalCount(kHistogramName, 0);
5242 
5243   // Set some cookies. This requires some knowledge of how
5244   // ReducePortRangeForCookieHistogram maps ports, but that's probably fine.
5245 
5246   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://www.foo.com"), "A=B"));
5247   histograms.ExpectTotalCount(kHistogramName, 1);
5248   histograms.ExpectBucketCount(kHistogramName,
5249                                ReducePortRangeForCookieHistogram(443), 1);
5250 
5251   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://www.foo.com:80"), "A=B"));
5252   histograms.ExpectTotalCount(kHistogramName, 2);
5253   histograms.ExpectBucketCount(kHistogramName,
5254                                ReducePortRangeForCookieHistogram(80), 1);
5255 
5256   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://www.foo.com:9000"), "A=B"));
5257   histograms.ExpectTotalCount(kHistogramName, 3);
5258   histograms.ExpectBucketCount(kHistogramName,
5259                                ReducePortRangeForCookieHistogram(9000), 1);
5260 
5261   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://www.foo.com:1234"), "A=B"));
5262   histograms.ExpectTotalCount(kHistogramName, 4);
5263   histograms.ExpectBucketCount(kHistogramName,
5264                                ReducePortRangeForCookieHistogram(1234), 1);
5265 
5266   // Histogram should not increment for invalid cookie.
5267   EXPECT_FALSE(SetCookie(cm.get(), GURL("https://www.foo.com"),
5268                          "A=B; Domain=malformedcookie.com"));
5269   histograms.ExpectTotalCount(kHistogramName, 4);
5270 
5271   // Nor should it increment for a read operation
5272   EXPECT_NE(GetCookies(cm.get(), GURL("https://www.foo.com")), "");
5273   histograms.ExpectTotalCount(kHistogramName, 4);
5274 
5275   // Make sure the correct histogram is chosen for localhost.
5276   histograms.ExpectTotalCount(kHistogramNameLocal, 0);
5277 
5278   EXPECT_TRUE(
5279       SetCookie(cm.get(), GURL("https://localhost:1234"), "local=host"));
5280   histograms.ExpectTotalCount(kHistogramNameLocal, 1);
5281   histograms.ExpectBucketCount(kHistogramNameLocal,
5282                                ReducePortRangeForCookieHistogram(1234), 1);
5283 }
5284 
TEST_F(CookieMonsterTest,CookiePortReadDiffersFromSetHistogram)5285 TEST_F(CookieMonsterTest, CookiePortReadDiffersFromSetHistogram) {
5286   base::HistogramTester histograms;
5287   const char kHistogramName[] = "Cookie.Port.ReadDiffersFromSet.RemoteHost";
5288   const char kHistogramNameLocal[] = "Cookie.Port.ReadDiffersFromSet.Localhost";
5289   const char kHistogramNameDomainSet[] =
5290       "Cookie.Port.ReadDiffersFromSet.DomainSet";
5291 
5292   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
5293   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5294 
5295   histograms.ExpectTotalCount(kHistogramName, 0);
5296 
5297   // Set some cookies. One with a port, one without, and one with an invalid
5298   // port.
5299   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://www.foo.com/withport"),
5300                         "A=B; Path=/withport"));  // Port 443
5301 
5302   auto unspecified_cookie = CanonicalCookie::Create(
5303       GURL("https://www.foo.com/withoutport"), "C=D; Path=/withoutport",
5304       base::Time::Now(), /* server_time */ absl::nullopt,
5305       /* cookie_partition_key */ absl::nullopt);
5306   // Force to be unspecified.
5307   unspecified_cookie->SetSourcePort(url::PORT_UNSPECIFIED);
5308   EXPECT_TRUE(SetCanonicalCookieReturnAccessResult(
5309                   cm.get(), std::move(unspecified_cookie),
5310                   GURL("https://www.foo.com/withoutport"),
5311                   false /*can_modify_httponly*/)
5312                   .status.IsInclude());
5313 
5314   auto invalid_cookie = CanonicalCookie::Create(
5315       GURL("https://www.foo.com/invalidport"), "E=F; Path=/invalidport",
5316       base::Time::Now(), /* server_time */ absl::nullopt,
5317       /* cookie_partition_key */ absl::nullopt);
5318   // Force to be invalid.
5319   invalid_cookie->SetSourcePort(99999);
5320   EXPECT_TRUE(SetCanonicalCookieReturnAccessResult(
5321                   cm.get(), std::move(invalid_cookie),
5322                   GURL("https://www.foo.com/invalidport"),
5323                   false /*can_modify_httponly*/)
5324                   .status.IsInclude());
5325 
5326   // Try same port.
5327   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.foo.com/withport")), "A=B");
5328   histograms.ExpectTotalCount(kHistogramName, 1);
5329   histograms.ExpectBucketCount(kHistogramName,
5330                                CookieMonster::CookieSentToSamePort::kYes, 1);
5331 
5332   // Try different port.
5333   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.foo.com:8080/withport")),
5334             "A=B");
5335   histograms.ExpectTotalCount(kHistogramName, 2);
5336   histograms.ExpectBucketCount(kHistogramName,
5337                                CookieMonster::CookieSentToSamePort::kNo, 1);
5338 
5339   // Try different port, but it's the default for a different scheme.
5340   EXPECT_EQ(GetCookies(cm.get(), GURL("http://www.foo.com/withport")), "A=B");
5341   histograms.ExpectTotalCount(kHistogramName, 3);
5342   histograms.ExpectBucketCount(
5343       kHistogramName, CookieMonster::CookieSentToSamePort::kNoButDefault, 1);
5344 
5345   // Now try it with an unspecified port cookie.
5346   EXPECT_EQ(GetCookies(cm.get(), GURL("http://www.foo.com/withoutport")),
5347             "C=D");
5348   histograms.ExpectTotalCount(kHistogramName, 4);
5349   histograms.ExpectBucketCount(
5350       kHistogramName,
5351       CookieMonster::CookieSentToSamePort::kSourcePortUnspecified, 1);
5352 
5353   // Finally try it with an invalid port cookie.
5354   EXPECT_EQ(GetCookies(cm.get(), GURL("http://www.foo.com/invalidport")),
5355             "E=F");
5356   histograms.ExpectTotalCount(kHistogramName, 5);
5357   histograms.ExpectBucketCount(
5358       kHistogramName, CookieMonster::CookieSentToSamePort::kInvalid, 1);
5359 
5360   // Make sure the correct histogram is chosen for localhost.
5361   histograms.ExpectTotalCount(kHistogramNameLocal, 0);
5362   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://localhost"), "local=host"));
5363 
5364   EXPECT_EQ(GetCookies(cm.get(), GURL("https://localhost")), "local=host");
5365   histograms.ExpectTotalCount(kHistogramNameLocal, 1);
5366   histograms.ExpectBucketCount(kHistogramNameLocal,
5367                                CookieMonster::CookieSentToSamePort::kYes, 1);
5368 
5369   // Make sure the Domain set version works.
5370   EXPECT_TRUE(SetCookie(cm.get(), GURL("https://www.foo.com/withDomain"),
5371                         "W=D; Domain=foo.com; Path=/withDomain"));
5372 
5373   histograms.ExpectTotalCount(kHistogramNameDomainSet, 0);
5374 
5375   EXPECT_EQ(GetCookies(cm.get(), GURL("https://www.foo.com/withDomain")),
5376             "W=D");
5377   histograms.ExpectTotalCount(kHistogramNameDomainSet, 1);
5378   histograms.ExpectBucketCount(kHistogramNameDomainSet,
5379                                CookieMonster::CookieSentToSamePort::kYes, 1);
5380   // The RemoteHost histogram should also increase with this cookie. Domain
5381   // cookies aren't special insofar as this metric is concerned.
5382   histograms.ExpectTotalCount(kHistogramName, 6);
5383   histograms.ExpectBucketCount(kHistogramName,
5384                                CookieMonster::CookieSentToSamePort::kYes, 2);
5385 }
5386 
TEST_F(CookieMonsterTest,CookieSourceSchemeNameHistogram)5387 TEST_F(CookieMonsterTest, CookieSourceSchemeNameHistogram) {
5388   base::HistogramTester histograms;
5389   const char kHistogramName[] = "Cookie.CookieSourceSchemeName";
5390 
5391   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
5392   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5393 
5394   histograms.ExpectTotalCount(kHistogramName, 0);
5395 
5396   struct TestCase {
5397     CookieSourceSchemeName enum_value;
5398     std::string scheme;
5399   };
5400 
5401   // Test the usual and a smattering of some other types including a kOther.
5402   // It doesn't matter if we add this to the scheme registry or not because we
5403   // don't actually need the whole url to parse, we just need GURL to pick up on
5404   // the scheme correctly (which it does). What the rest of the cookie code does
5405   // with the oddly formed GURL is out of scope of this test (i.e. we don't
5406   // care).
5407   const TestCase kTestCases[] = {
5408       {CookieSourceSchemeName::kHttpsScheme, url::kHttpsScheme},
5409       {CookieSourceSchemeName::kHttpScheme, url::kHttpScheme},
5410       {CookieSourceSchemeName::kWssScheme, url::kWssScheme},
5411       {CookieSourceSchemeName::kWsScheme, url::kWsScheme},
5412       {CookieSourceSchemeName::kChromeExtensionScheme, "chrome-extension"},
5413       {CookieSourceSchemeName::kFileScheme, url::kFileScheme},
5414       {CookieSourceSchemeName::kOther, "abcd1234"}};
5415 
5416   // Make sure all the schemes are considered cookieable.
5417   std::vector<std::string> schemes;
5418   for (auto test_case : kTestCases) {
5419     schemes.push_back(test_case.scheme);
5420   }
5421   ResultSavingCookieCallback<bool> cookie_scheme_callback;
5422   cm->SetCookieableSchemes(schemes, cookie_scheme_callback.MakeCallback());
5423   cookie_scheme_callback.WaitUntilDone();
5424   ASSERT_TRUE(cookie_scheme_callback.result());
5425 
5426   const char kUrl[] = "://www.foo.com";
5427   int count = 0;
5428 
5429   // Test all the cases.
5430   for (auto test_case : kTestCases) {
5431     histograms.ExpectBucketCount(kHistogramName, test_case.enum_value, 0);
5432 
5433     EXPECT_TRUE(SetCookie(cm.get(), GURL(test_case.scheme + kUrl), "A=B"));
5434 
5435     histograms.ExpectBucketCount(kHistogramName, test_case.enum_value, 1);
5436     histograms.ExpectTotalCount(kHistogramName, ++count);
5437   }
5438 
5439   // This metric is only for cookies that are actually set. Make sure the
5440   // histogram doesn't increment for cookies that fail to set.
5441 
5442   // Try to set an invalid cookie, for instance: a non-cookieable scheme will be
5443   // rejected.
5444   EXPECT_FALSE(SetCookie(cm.get(), GURL("invalidscheme://foo.com"), "A=B"));
5445   histograms.ExpectTotalCount(kHistogramName, count);
5446 }
5447 
5448 class FirstPartySetEnabledCookieMonsterTest : public CookieMonsterTest {
5449  public:
FirstPartySetEnabledCookieMonsterTest()5450   FirstPartySetEnabledCookieMonsterTest()
5451       : cm_(nullptr /* store */, nullptr /* netlog */
5452         ) {
5453     std::unique_ptr<TestCookieAccessDelegate> access_delegate =
5454         std::make_unique<TestCookieAccessDelegate>();
5455     access_delegate_ = access_delegate.get();
5456     cm_.SetCookieAccessDelegate(std::move(access_delegate));
5457   }
5458 
5459   ~FirstPartySetEnabledCookieMonsterTest() override = default;
5460 
cm()5461   CookieMonster* cm() { return &cm_; }
5462 
5463  protected:
5464   CookieMonster cm_;
5465   raw_ptr<TestCookieAccessDelegate> access_delegate_;
5466 };
5467 
TEST_F(FirstPartySetEnabledCookieMonsterTest,RecordsPeriodicFPSSizes)5468 TEST_F(FirstPartySetEnabledCookieMonsterTest, RecordsPeriodicFPSSizes) {
5469   net::SchemefulSite owner1(GURL("https://owner1.test"));
5470   net::SchemefulSite owner2(GURL("https://owner2.test"));
5471   net::SchemefulSite member1(GURL("https://member1.test"));
5472   net::SchemefulSite member2(GURL("https://member2.test"));
5473   net::SchemefulSite member3(GURL("https://member3.test"));
5474   net::SchemefulSite member4(GURL("https://member4.test"));
5475 
5476   access_delegate_->SetFirstPartySets({
5477       {owner1,
5478        net::FirstPartySetEntry(owner1, net::SiteType::kPrimary, absl::nullopt)},
5479       {member1, net::FirstPartySetEntry(owner1, net::SiteType::kAssociated, 0)},
5480       {member2, net::FirstPartySetEntry(owner1, net::SiteType::kAssociated, 1)},
5481       {owner2,
5482        net::FirstPartySetEntry(owner2, net::SiteType::kPrimary, absl::nullopt)},
5483       {member3, net::FirstPartySetEntry(owner2, net::SiteType::kAssociated, 0)},
5484       {member4, net::FirstPartySetEntry(owner2, net::SiteType::kAssociated, 1)},
5485   });
5486 
5487   ASSERT_TRUE(SetCookie(cm(), GURL("https://owner1.test"), kValidCookieLine));
5488   ASSERT_TRUE(SetCookie(cm(), GURL("https://member1.test"), kValidCookieLine));
5489   ASSERT_TRUE(SetCookie(cm(), GURL("https://member2.test"), kValidCookieLine));
5490   ASSERT_TRUE(SetCookie(cm(), GURL("https://owner2.test"), kValidCookieLine));
5491   ASSERT_TRUE(SetCookie(cm(), GURL("https://member3.test"), kValidCookieLine));
5492   // No cookie set for member4.test.
5493   ASSERT_TRUE(
5494       SetCookie(cm(), GURL("https://unrelated1.test"), kValidCookieLine));
5495   ASSERT_TRUE(
5496       SetCookie(cm(), GURL("https://unrelated2.test"), kValidCookieLine));
5497   ASSERT_TRUE(
5498       SetCookie(cm(), GURL("https://unrelated3.test"), kValidCookieLine));
5499 
5500   base::HistogramTester histogram_tester;
5501   EXPECT_TRUE(cm()->DoRecordPeriodicStatsForTesting());
5502   EXPECT_THAT(histogram_tester.GetAllSamples("Cookie.PerFirstPartySetCount"),
5503               testing::ElementsAre(  //
5504                                      // owner2.test & member3.test
5505                   base::Bucket(2 /* min */, 1 /* samples */),
5506                   // owner1.test, member1.test, & member2.test
5507                   base::Bucket(3 /* min */, 1 /* samples */)));
5508 }
5509 
TEST_F(CookieMonsterTest,GetAllCookiesForURLNonce)5510 TEST_F(CookieMonsterTest, GetAllCookiesForURLNonce) {
5511   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
5512   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5513   CookieOptions options = CookieOptions::MakeAllInclusive();
5514 
5515   auto anonymous_iframe_key = CookiePartitionKey::FromURLForTesting(
5516       GURL("https://anonymous-iframe.test"), base::UnguessableToken::Create());
5517 
5518   // Define cookies from outside an anonymous iframe:
5519   EXPECT_TRUE(CreateAndSetCookie(cm.get(), https_www_foo_.url(),
5520                                  "A=0; Secure; HttpOnly; Path=/;", options));
5521   EXPECT_TRUE(CreateAndSetCookie(cm.get(), https_www_foo_.url(),
5522                                  "__Host-B=0; Secure; HttpOnly; Path=/;",
5523                                  options));
5524 
5525   // Define cookies from inside an anonymous iframe:
5526   EXPECT_TRUE(CreateAndSetCookie(
5527       cm.get(), https_www_foo_.url(),
5528       "__Host-B=1; Secure; HttpOnly; Path=/; Partitioned", options,
5529       absl::nullopt, absl::nullopt, anonymous_iframe_key));
5530   EXPECT_TRUE(CreateAndSetCookie(
5531       cm.get(), https_www_foo_.url(),
5532       "__Host-C=0; Secure; HttpOnly; Path=/; Partitioned", options,
5533       absl::nullopt, absl::nullopt, anonymous_iframe_key));
5534 
5535   // Check cookies from outside the anonymous iframe:
5536   EXPECT_THAT(GetAllCookiesForURL(cm.get(), https_www_foo_.url()),
5537               ElementsAre(MatchesCookieNameValue("A", "0"),
5538                           MatchesCookieNameValue("__Host-B", "0")));
5539 
5540   // Check cookies from inside the anonymous iframe:
5541   EXPECT_THAT(
5542       GetAllCookiesForURL(cm.get(), https_www_foo_.url(),
5543                           CookiePartitionKeyCollection(anonymous_iframe_key)),
5544       ElementsAre(MatchesCookieNameValue("__Host-B", "1"),
5545                   MatchesCookieNameValue("__Host-C", "0")));
5546 }
5547 
TEST_F(CookieMonsterTest,SiteHasCookieInOtherPartition)5548 TEST_F(CookieMonsterTest, SiteHasCookieInOtherPartition) {
5549   auto store = base::MakeRefCounted<MockPersistentCookieStore>();
5550   auto cm = std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5551   CookieOptions options = CookieOptions::MakeAllInclusive();
5552 
5553   GURL url("https://subdomain.example.com/");
5554   net::SchemefulSite site(url);
5555   auto partition_key =
5556       CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"));
5557 
5558   // At first it should return nullopt...
5559   EXPECT_FALSE(cm->SiteHasCookieInOtherPartition(site, partition_key));
5560 
5561   // ...until we load cookies for that domain.
5562   GetAllCookiesForURL(cm.get(), url,
5563                       CookiePartitionKeyCollection::ContainsAll());
5564   EXPECT_THAT(cm->SiteHasCookieInOtherPartition(site, partition_key),
5565               testing::Optional(false));
5566 
5567   // Set partitioned cookie.
5568   EXPECT_TRUE(CreateAndSetCookie(
5569       cm.get(), url, "foo=bar; Secure; SameSite=None; Partitioned", options,
5570       absl::nullopt, absl::nullopt, partition_key));
5571 
5572   // Should return false with that cookie's partition key.
5573   EXPECT_THAT(cm->SiteHasCookieInOtherPartition(site, partition_key),
5574               testing::Optional(false));
5575 
5576   auto other_partition_key = CookiePartitionKey::FromURLForTesting(
5577       GURL("https://nottoplevelsite.com"));
5578 
5579   // Should return true with another partition key.
5580   EXPECT_THAT(cm->SiteHasCookieInOtherPartition(site, other_partition_key),
5581               testing::Optional(true));
5582 
5583   // Set a nonced partitioned cookie with a different partition key.
5584   EXPECT_TRUE(CreateAndSetCookie(
5585       cm.get(), url, "foo=bar; Secure; SameSite=None; Partitioned", options,
5586       absl::nullopt, absl::nullopt,
5587       CookiePartitionKey::FromURLForTesting(GURL("https://nottoplevelsite.com"),
5588                                             base::UnguessableToken::Create())));
5589 
5590   // Should still return false with the original partition key.
5591   EXPECT_THAT(cm->SiteHasCookieInOtherPartition(site, partition_key),
5592               testing::Optional(false));
5593 
5594   // Set unpartitioned cookie.
5595   EXPECT_TRUE(CreateAndSetCookie(cm.get(), url,
5596                                  "bar=baz; Secure; SameSite=None;", options,
5597                                  absl::nullopt, absl::nullopt));
5598 
5599   // Should still return false with the original cookie's partition key. This
5600   // method only considers partitioned cookies.
5601   EXPECT_THAT(cm->SiteHasCookieInOtherPartition(site, partition_key),
5602               testing::Optional(false));
5603 
5604   // Should return nullopt when the partition key is nullopt.
5605   EXPECT_FALSE(
5606       cm->SiteHasCookieInOtherPartition(site, /*partition_key=*/absl::nullopt));
5607 }
5608 
5609 // Tests which use this class verify the expiry date clamping behavior when
5610 // kClampCookieExpiryTo400Days is enabled. This caps expiry dates on new/updated
5611 // cookies to max of 400 days, but does not affect previously stored cookies.
5612 class CookieMonsterWithClampingTest : public CookieMonsterTest,
5613                                       public testing::WithParamInterface<bool> {
5614  public:
CookieMonsterWithClampingTest()5615   CookieMonsterWithClampingTest() {
5616     scoped_feature_list_.InitWithFeatureState(
5617         features::kClampCookieExpiryTo400Days,
5618         IsClampCookieExpiryTo400DaysEnabled());
5619   }
IsClampCookieExpiryTo400DaysEnabled()5620   bool IsClampCookieExpiryTo400DaysEnabled() { return GetParam(); }
5621 
5622  private:
5623   base::test::ScopedFeatureList scoped_feature_list_;
5624 };
5625 
5626 INSTANTIATE_TEST_SUITE_P(/* no label */,
5627                          CookieMonsterWithClampingTest,
5628                          testing::Bool());
5629 
5630 // This test sets a cookie (only checked using IsCanonicalForFromStorage)
5631 // that's 300 days old and expires in 800 days. It checks that this cookie was
5632 // stored, and then update it. It checks that the updated cookie has the
5633 // creation and expiry dates expected given whether or not clamping is on.
TEST_P(CookieMonsterWithClampingTest,FromStorageCookieCreated300DaysAgoThenUpdatedNow)5634 TEST_P(CookieMonsterWithClampingTest,
5635        FromStorageCookieCreated300DaysAgoThenUpdatedNow) {
5636   auto store = base::MakeRefCounted<FlushablePersistentStore>();
5637   auto cookie_monster =
5638       std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5639   cookie_monster->SetPersistSessionCookies(true);
5640   EXPECT_TRUE(GetAllCookies(cookie_monster.get()).empty());
5641 
5642   // Bypass IsCanonical and store a 300 day old cookie to bypass clamping.
5643   base::Time original_creation = base::Time::Now() - base::Days(300);
5644   base::Time original_expiry = original_creation + base::Days(800);
5645   CookieList list;
5646   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
5647       "A", "B", "." + https_www_foo_.url().host(), "/", original_creation,
5648       original_expiry, base::Time(), base::Time(), true, false,
5649       CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true));
5650   EXPECT_TRUE(SetAllCookies(cookie_monster.get(), list));
5651 
5652   // Verify the cookie exists and was not clamped, even if clamping is on.
5653   EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5654               ElementsAre(MatchesCookieNameValueCreationExpiry(
5655                   "A", "B", original_creation, original_expiry)));
5656 
5657   // Update the cookie without bypassing clamping.
5658   base::Time new_creation = base::Time::Now();
5659   base::Time new_expiry = new_creation + base::Days(800);
5660   EXPECT_TRUE(SetCanonicalCookie(
5661       cookie_monster.get(),
5662       CanonicalCookie::CreateSanitizedCookie(
5663           https_www_foo_.url(), "A", "B", https_www_foo_.url().host(), "/",
5664           new_creation, new_expiry, base::Time(), true, false,
5665           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true,
5666           absl::nullopt),
5667       https_www_foo_.url(), false));
5668 
5669   if (IsClampCookieExpiryTo400DaysEnabled()) {
5670     // The clamped update should retain the original creation date, but have
5671     // a clamped expiry date.
5672     EXPECT_THAT(
5673         GetAllCookies(cookie_monster.get()),
5674         ElementsAre(MatchesCookieNameValueCreationExpiry(
5675             "A", "B", original_creation, new_creation + base::Days(400))));
5676   } else {
5677     // The unclamped update should retain the original creation date and have
5678     // an unclamped expiry date.
5679     EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5680                 ElementsAre(MatchesCookieNameValueCreationExpiry(
5681                     "A", "B", original_creation, new_expiry)));
5682   }
5683 }
5684 
5685 // This test sets a cookie (only checked using IsCanonicalForFromStorage)
5686 // that's 500 days old and expires in 800 days. It checks that this cookie was
5687 // stored, and then update it. It checks that the updated cookie has the
5688 // creation and expiry dates expected given whether or not clamping is on.
TEST_P(CookieMonsterWithClampingTest,FromStorageCookieCreated500DaysAgoThenUpdatedNow)5689 TEST_P(CookieMonsterWithClampingTest,
5690        FromStorageCookieCreated500DaysAgoThenUpdatedNow) {
5691   auto store = base::MakeRefCounted<FlushablePersistentStore>();
5692   auto cookie_monster =
5693       std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5694   cookie_monster->SetPersistSessionCookies(true);
5695   EXPECT_TRUE(GetAllCookies(cookie_monster.get()).empty());
5696 
5697   // Bypass IsCanonical and store a 500 day old cookie to bypass clamping.
5698   base::Time original_creation = base::Time::Now() - base::Days(500);
5699   base::Time original_expiry = original_creation + base::Days(800);
5700   CookieList list;
5701   list.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
5702       "A", "B", "." + https_www_foo_.url().host(), "/", original_creation,
5703       original_expiry, base::Time(), base::Time(), true, false,
5704       CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true));
5705   EXPECT_TRUE(SetAllCookies(cookie_monster.get(), list));
5706 
5707   // Verify the cookie exists and was not clamped, even if clamping is on.
5708   EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5709               ElementsAre(MatchesCookieNameValueCreationExpiry(
5710                   "A", "B", original_creation, original_expiry)));
5711 
5712   // Update the cookie without bypassing clamping.
5713   base::Time new_creation = base::Time::Now();
5714   base::Time new_expiry = new_creation + base::Days(800);
5715   EXPECT_TRUE(SetCanonicalCookie(
5716       cookie_monster.get(),
5717       CanonicalCookie::CreateSanitizedCookie(
5718           https_www_foo_.url(), "A", "B", https_www_foo_.url().host(), "/",
5719           new_creation, new_expiry, base::Time(), true, false,
5720           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true,
5721           absl::nullopt),
5722       https_www_foo_.url(), false));
5723 
5724   if (IsClampCookieExpiryTo400DaysEnabled()) {
5725     // The clamped update should retain the original creation date, but have
5726     // a clamped expiry date.
5727     EXPECT_THAT(
5728         GetAllCookies(cookie_monster.get()),
5729         ElementsAre(MatchesCookieNameValueCreationExpiry(
5730             "A", "B", original_creation, new_creation + base::Days(400))));
5731   } else {
5732     // The unclamped update should retain the original creation date and have
5733     // an unclamped expiry date.
5734     EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5735                 ElementsAre(MatchesCookieNameValueCreationExpiry(
5736                     "A", "B", original_creation, new_expiry)));
5737   }
5738 }
5739 
5740 // This test sets a cookie (checked using IsCanonical) that's 300 days old and
5741 // expires in 800 days. It checks that this cookie was stored, and then update
5742 // it. It checks that the updated cookie has the creation and expiry dates
5743 // expected given whether or not clamping is on.
TEST_P(CookieMonsterWithClampingTest,SanitizedCookieCreated300DaysAgoThenUpdatedNow)5744 TEST_P(CookieMonsterWithClampingTest,
5745        SanitizedCookieCreated300DaysAgoThenUpdatedNow) {
5746   auto store = base::MakeRefCounted<FlushablePersistentStore>();
5747   auto cookie_monster =
5748       std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5749   cookie_monster->SetPersistSessionCookies(true);
5750   EXPECT_TRUE(GetAllCookies(cookie_monster.get()).empty());
5751 
5752   // Store a 300 day old cookie without bypassing clamping.
5753   base::Time original_creation = base::Time::Now() - base::Days(300);
5754   base::Time original_expiry = original_creation + base::Days(800);
5755   EXPECT_TRUE(SetCanonicalCookie(
5756       cookie_monster.get(),
5757       CanonicalCookie::CreateSanitizedCookie(
5758           https_www_foo_.url(), "A", "B", https_www_foo_.url().host(), "/",
5759           original_creation, original_expiry, base::Time(), true, false,
5760           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true,
5761           absl::nullopt),
5762       https_www_foo_.url(), false));
5763 
5764   if (IsClampCookieExpiryTo400DaysEnabled()) {
5765     // The clamped set should have a clamped expiry date.
5766     EXPECT_THAT(
5767         GetAllCookies(cookie_monster.get()),
5768         ElementsAre(MatchesCookieNameValueCreationExpiry(
5769             "A", "B", original_creation, original_creation + base::Days(400))));
5770   } else {
5771     // The unclamped set should have an unclamped expiry date.
5772     EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5773                 ElementsAre(MatchesCookieNameValueCreationExpiry(
5774                     "A", "B", original_creation, original_expiry)));
5775   }
5776 
5777   // Update the cookie without bypassing clamping.
5778   base::Time new_creation = base::Time::Now();
5779   base::Time new_expiry = new_creation + base::Days(800);
5780   EXPECT_TRUE(SetCanonicalCookie(
5781       cookie_monster.get(),
5782       CanonicalCookie::CreateSanitizedCookie(
5783           https_www_foo_.url(), "A", "B", https_www_foo_.url().host(), "/",
5784           new_creation, new_expiry, base::Time(), true, false,
5785           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true,
5786           absl::nullopt),
5787       https_www_foo_.url(), false));
5788 
5789   if (IsClampCookieExpiryTo400DaysEnabled()) {
5790     // The clamped update should retain the original creation date, but have
5791     // a clamped expiry date.
5792     EXPECT_THAT(
5793         GetAllCookies(cookie_monster.get()),
5794         ElementsAre(MatchesCookieNameValueCreationExpiry(
5795             "A", "B", original_creation, new_creation + base::Days(400))));
5796   } else {
5797     // The unclamped update should retain the original creation date and have
5798     // an unclamped expiry date.
5799     EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5800                 ElementsAre(MatchesCookieNameValueCreationExpiry(
5801                     "A", "B", original_creation, new_expiry)));
5802   }
5803 }
5804 
5805 // This test sets a cookie (checked using IsCanonical) that's 500 days old and
5806 // expires in 800 days. It checks that this cookie was stored, and then update
5807 // it. It checks that the updated cookie has the creation and expiry dates
5808 // expected given whether or not clamping is on.
TEST_P(CookieMonsterWithClampingTest,SanitizedCookieCreated500DaysAgoThenUpdatedNow)5809 TEST_P(CookieMonsterWithClampingTest,
5810        SanitizedCookieCreated500DaysAgoThenUpdatedNow) {
5811   auto store = base::MakeRefCounted<FlushablePersistentStore>();
5812   auto cookie_monster =
5813       std::make_unique<CookieMonster>(store.get(), net::NetLog::Get());
5814   cookie_monster->SetPersistSessionCookies(true);
5815   EXPECT_TRUE(GetAllCookies(cookie_monster.get()).empty());
5816 
5817   // Store a 500 day old cookie without bypassing clamping.
5818   base::Time original_creation = base::Time::Now() - base::Days(500);
5819   base::Time original_expiry = original_creation + base::Days(800);
5820   EXPECT_TRUE(SetCanonicalCookie(
5821       cookie_monster.get(),
5822       CanonicalCookie::CreateSanitizedCookie(
5823           https_www_foo_.url(), "A", "B", https_www_foo_.url().host(), "/",
5824           original_creation, original_expiry, base::Time(), true, false,
5825           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true,
5826           absl::nullopt),
5827       https_www_foo_.url(), false));
5828 
5829   if (IsClampCookieExpiryTo400DaysEnabled()) {
5830     // The clamped set should result in no stored cookie.
5831     EXPECT_TRUE(GetAllCookies(cookie_monster.get()).empty());
5832   } else {
5833     // The unclamped set should have an unclamped expiry date.
5834     EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5835                 ElementsAre(MatchesCookieNameValueCreationExpiry(
5836                     "A", "B", original_creation, original_expiry)));
5837   }
5838 
5839   // Update the cookie without bypassing clamping.
5840   base::Time new_creation = base::Time::Now();
5841   base::Time new_expiry = new_creation + base::Days(800);
5842   EXPECT_TRUE(SetCanonicalCookie(
5843       cookie_monster.get(),
5844       CanonicalCookie::CreateSanitizedCookie(
5845           https_www_foo_.url(), "A", "B", https_www_foo_.url().host(), "/",
5846           new_creation, new_expiry, base::Time(), true, false,
5847           CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT, true,
5848           absl::nullopt),
5849       https_www_foo_.url(), false));
5850 
5851   // The clamped one has the new creation date as the old cookie was expired.
5852   if (IsClampCookieExpiryTo400DaysEnabled()) {
5853     // The clamped update was really a set as the old cookie expired, so it has
5854     // the new creation date and a clamped expiry date.
5855     EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5856                 ElementsAre(MatchesCookieNameValueCreationExpiry(
5857                     "A", "B", new_creation, new_creation + base::Days(400))));
5858   } else {
5859     // The unclamped update should retain the original creation date and have
5860     // an unclamped expiry date.
5861     EXPECT_THAT(GetAllCookies(cookie_monster.get()),
5862                 ElementsAre(MatchesCookieNameValueCreationExpiry(
5863                     "A", "B", original_creation, new_expiry)));
5864   }
5865 }
5866 
5867 }  // namespace net
5868