cookie_manager_impl_unittest.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include <lib/fidl/cpp/binding.h>
  5. #include <map>
  6. #include <vector>
  7. #include "base/bind.h"
  8. #include "base/run_loop.h"
  9. #include "base/strings/string_piece.h"
  10. #include "base/test/bind.h"
  11. #include "base/test/task_environment.h"
  12. #include "base/test/test_future.h"
  13. #include "fuchsia_web/common/test/fit_adapter.h"
  14. #include "fuchsia_web/webengine/browser/cookie_manager_impl.h"
  15. #include "mojo/public/cpp/bindings/remote.h"
  16. #include "net/cookies/cookie_access_result.h"
  17. #include "services/network/network_service.h"
  18. #include "services/network/public/mojom/cookie_manager.mojom.h"
  19. #include "services/network/public/mojom/network_context.mojom.h"
  20. #include "services/network/test/fake_test_cert_verifier_params_factory.h"
  21. #include "testing/gtest/include/gtest/gtest.h"
  22. #include "third_party/abseil-cpp/absl/types/optional.h"
  23. namespace {
  24. const char kTestCookieUrl[] = "https://www.testing.com/";
  25. const char kTestOtherUrl[] = "https://www.other.com/";
  26. const char kCookieName1[] = "Cookie";
  27. const char kCookieName2[] = "Monster";
  28. const char kCookieValue1[] = "Eats";
  29. const char kCookieValue2[] = "Cookies";
  30. const char kCookieValue3[] = "Nyom nyom nyom";
  31. // Creates a CanonicalCookie with |name| and |value|, for kTestCookieUrl.
  32. std::unique_ptr<net::CanonicalCookie> CreateCookie(base::StringPiece name,
  33. base::StringPiece value) {
  34. return net::CanonicalCookie::CreateSanitizedCookie(
  35. GURL(kTestCookieUrl), std::string(name), std::string(value),
  36. /*domain=*/"",
  37. /*path=*/"", /*creation_time=*/base::Time(),
  38. /*expiration_time=*/base::Time(), /*last_access_time=*/base::Time(),
  39. /*secure=*/true,
  40. /*httponly*/ false, net::CookieSameSite::NO_RESTRICTION,
  41. net::COOKIE_PRIORITY_MEDIUM, /*same_party=*/false,
  42. /*partition_key=*/absl::nullopt);
  43. }
  44. class CookieManagerImplTest : public testing::Test {
  45. public:
  46. CookieManagerImplTest()
  47. : task_environment_(base::test::TaskEnvironment::MainThreadType::IO),
  48. network_service_(network::NetworkService::CreateForTesting()),
  49. cookie_manager_(
  50. base::BindRepeating(&CookieManagerImplTest::GetNetworkContext,
  51. base::Unretained(this))) {}
  52. CookieManagerImplTest(const CookieManagerImplTest&) = delete;
  53. CookieManagerImplTest& operator=(const CookieManagerImplTest&) = delete;
  54. ~CookieManagerImplTest() override = default;
  55. protected:
  56. network::mojom::NetworkContext* GetNetworkContext() {
  57. if (!network_context_.is_bound()) {
  58. network::mojom::NetworkContextParamsPtr params =
  59. network::mojom::NetworkContextParams::New();
  60. // Use a dummy CertVerifier that always passes cert verification, since
  61. // these unittests don't need to test CertVerifier behavior.
  62. params->cert_verifier_params =
  63. network::FakeTestCertVerifierParamsFactory::GetCertVerifierParams();
  64. network_service_->CreateNetworkContext(
  65. network_context_.BindNewPipeAndPassReceiver(), std::move(params));
  66. network_context_.reset_on_disconnect();
  67. }
  68. return network_context_.get();
  69. }
  70. // Adds the specified cookie under kTestCookieUrl.
  71. void CreateAndSetCookieAsync(base::StringPiece name,
  72. base::StringPiece value) {
  73. EnsureMojoCookieManager();
  74. net::CookieOptions options;
  75. mojo_cookie_manager_->SetCanonicalCookie(
  76. *CreateCookie(name, value), GURL(kTestCookieUrl), options,
  77. base::BindOnce([](net::CookieAccessResult result) {
  78. EXPECT_TRUE(result.status.IsInclude());
  79. }));
  80. }
  81. // Removes the specified cookie from under kTestCookieUrl.
  82. void DeleteCookieAsync(base::StringPiece name, base::StringPiece value) {
  83. EnsureMojoCookieManager();
  84. mojo_cookie_manager_->DeleteCanonicalCookie(
  85. *CreateCookie(name, value),
  86. base::BindOnce([](bool success) { EXPECT_TRUE(success); }));
  87. }
  88. // Synchronously fetches all cookies via the |cookie_manager_|.
  89. // Returns a absl::nullopt if the iterator closes before a GetNext() returns.
  90. absl::optional<std::vector<fuchsia::web::Cookie>> GetAllCookies() {
  91. base::RunLoop get_cookies_loop;
  92. fuchsia::web::CookiesIteratorPtr cookies_iterator;
  93. cookies_iterator.set_error_handler([&](zx_status_t status) {
  94. EXPECT_EQ(ZX_ERR_PEER_CLOSED, status);
  95. get_cookies_loop.Quit();
  96. });
  97. cookie_manager_.GetCookieList(nullptr, nullptr,
  98. cookies_iterator.NewRequest());
  99. absl::optional<std::vector<fuchsia::web::Cookie>> cookies;
  100. std::function<void(std::vector<fuchsia::web::Cookie>)> get_next_callback =
  101. [&](std::vector<fuchsia::web::Cookie> new_cookies) {
  102. if (!cookies.has_value()) {
  103. cookies.emplace(std::move(new_cookies));
  104. } else {
  105. cookies->insert(cookies->end(),
  106. std::make_move_iterator(new_cookies.begin()),
  107. std::make_move_iterator(new_cookies.end()));
  108. }
  109. cookies_iterator->GetNext(get_next_callback);
  110. };
  111. cookies_iterator->GetNext(get_next_callback);
  112. get_cookies_loop.Run();
  113. return cookies;
  114. }
  115. void EnsureMojoCookieManager() {
  116. if (mojo_cookie_manager_.is_bound())
  117. return;
  118. network_context_->GetCookieManager(
  119. mojo_cookie_manager_.BindNewPipeAndPassReceiver());
  120. }
  121. base::test::TaskEnvironment task_environment_;
  122. std::unique_ptr<network::NetworkService> network_service_;
  123. mojo::Remote<network::mojom::NetworkContext> network_context_;
  124. mojo::Remote<network::mojom::CookieManager> mojo_cookie_manager_;
  125. CookieManagerImpl cookie_manager_;
  126. };
  127. // Calls GetNext() on the supplied |iterator| and lets the caller express
  128. // expectations on the results.
  129. class GetNextCookiesIteratorResult {
  130. public:
  131. explicit GetNextCookiesIteratorResult(
  132. fuchsia::web::CookiesIterator* iterator) {
  133. iterator->GetNext(CallbackToFitFunction(result_.GetCallback()));
  134. }
  135. GetNextCookiesIteratorResult(const GetNextCookiesIteratorResult&) = delete;
  136. GetNextCookiesIteratorResult& operator=(const GetNextCookiesIteratorResult&) =
  137. delete;
  138. ~GetNextCookiesIteratorResult() = default;
  139. void ExpectSingleCookie(base::StringPiece name,
  140. absl::optional<base::StringPiece> value) {
  141. ExpectCookieUpdates({{name, value}});
  142. }
  143. void ExpectDeleteSingleCookie(base::StringPiece name) {
  144. ExpectCookieUpdates({{name, absl::nullopt}});
  145. }
  146. // Specifies the cookie name/value pairs expected in the GetNext() results.
  147. // Deletions expectations are specified by using absl::nullopt as the value.
  148. void ExpectCookieUpdates(
  149. std::map<base::StringPiece, absl::optional<base::StringPiece>> expected) {
  150. ASSERT_TRUE(result_.Wait());
  151. ASSERT_EQ(result_.Get().size(), expected.size());
  152. std::map<base::StringPiece, base::StringPiece> result_updates;
  153. for (const auto& cookie_update : result_.Get()) {
  154. ASSERT_TRUE(cookie_update.has_id());
  155. ASSERT_TRUE(cookie_update.id().has_name());
  156. auto it = expected.find(cookie_update.id().name());
  157. ASSERT_TRUE(it != expected.end());
  158. ASSERT_EQ(cookie_update.has_value(), it->second.has_value());
  159. if (it->second.has_value())
  160. EXPECT_EQ(*it->second, cookie_update.value());
  161. expected.erase(it);
  162. }
  163. EXPECT_TRUE(expected.empty());
  164. }
  165. void ExpectReceivedNoUpdates() {
  166. // If we ran |loop_| then this would hang, so just ensure any pending work
  167. // has been processed.
  168. base::RunLoop().RunUntilIdle();
  169. EXPECT_FALSE(result_.IsReady());
  170. }
  171. protected:
  172. base::test::TestFuture<std::vector<fuchsia::web::Cookie>> result_;
  173. };
  174. } // namespace
  175. TEST_F(CookieManagerImplTest, GetAndObserveAddModifyDelete) {
  176. // Add global, URL-filtered and URL+name-filtered observers.
  177. fuchsia::web::CookiesIteratorPtr global_changes;
  178. global_changes.set_error_handler([](zx_status_t) { ADD_FAILURE(); });
  179. cookie_manager_.ObserveCookieChanges(nullptr, nullptr,
  180. global_changes.NewRequest());
  181. fuchsia::web::CookiesIteratorPtr url_changes;
  182. url_changes.set_error_handler([](zx_status_t) { ADD_FAILURE(); });
  183. cookie_manager_.ObserveCookieChanges(kTestCookieUrl, nullptr,
  184. url_changes.NewRequest());
  185. fuchsia::web::CookiesIteratorPtr name_changes;
  186. name_changes.set_error_handler([](zx_status_t) { ADD_FAILURE(); });
  187. cookie_manager_.ObserveCookieChanges(kTestCookieUrl, kCookieName1,
  188. name_changes.NewRequest());
  189. // Register interest in updates for another URL, so we can verify none are
  190. // received.
  191. fuchsia::web::CookiesIteratorPtr other_changes;
  192. name_changes.set_error_handler([](zx_status_t) { ADD_FAILURE(); });
  193. cookie_manager_.ObserveCookieChanges(kTestOtherUrl, nullptr,
  194. other_changes.NewRequest());
  195. GetNextCookiesIteratorResult other_updates(other_changes.get());
  196. // Ensure that all ObserveCookieChanges() were processed before modifying
  197. // cookies.
  198. EXPECT_EQ(GetAllCookies()->size(), 0u);
  199. // Set cookie kCookieName1, which should trigger notifications to all
  200. // observers.
  201. {
  202. GetNextCookiesIteratorResult global_update(global_changes.get());
  203. GetNextCookiesIteratorResult url_update(url_changes.get());
  204. GetNextCookiesIteratorResult name_update(name_changes.get());
  205. CreateAndSetCookieAsync(kCookieName1, kCookieValue1);
  206. global_update.ExpectSingleCookie(kCookieName1, kCookieValue1);
  207. url_update.ExpectSingleCookie(kCookieName1, kCookieValue1);
  208. name_update.ExpectSingleCookie(kCookieName1, kCookieValue1);
  209. }
  210. // Expect an add notification for kCookieName2, except on the with-name
  211. // observer. If the with-name observer does get notified then the remove &
  212. // re-add check below will observe kCookieName2 rather than kCookieName1, and
  213. // fail.
  214. {
  215. GetNextCookiesIteratorResult global_update(global_changes.get());
  216. GetNextCookiesIteratorResult url_update(url_changes.get());
  217. CreateAndSetCookieAsync(kCookieName2, kCookieValue2);
  218. global_update.ExpectSingleCookie(kCookieName2, kCookieValue2);
  219. url_update.ExpectSingleCookie(kCookieName2, kCookieValue2);
  220. }
  221. // Set kCookieName1 to a new value, which will trigger deletion notifications,
  222. // followed by an addition with the new value.
  223. {
  224. GetNextCookiesIteratorResult global_update(global_changes.get());
  225. GetNextCookiesIteratorResult url_update(url_changes.get());
  226. GetNextCookiesIteratorResult name_update(name_changes.get());
  227. // Updating the cookie will generate a deletion, following by an insertion.
  228. // CookiesIterator will batch updates into a single response, so we may get
  229. // two separate updates, or a single update, depending on timing. Eliminate
  230. // the non-determinism by ensuring that the GetNext() calls have been
  231. // received before updating the cookie.
  232. base::RunLoop().RunUntilIdle();
  233. CreateAndSetCookieAsync(kCookieName1, kCookieValue3);
  234. global_update.ExpectDeleteSingleCookie(kCookieName1);
  235. url_update.ExpectDeleteSingleCookie(kCookieName1);
  236. name_update.ExpectDeleteSingleCookie(kCookieName1);
  237. }
  238. {
  239. GetNextCookiesIteratorResult global_update(global_changes.get());
  240. GetNextCookiesIteratorResult url_update(url_changes.get());
  241. GetNextCookiesIteratorResult name_update(name_changes.get());
  242. global_update.ExpectSingleCookie(kCookieName1, kCookieValue3);
  243. url_update.ExpectSingleCookie(kCookieName1, kCookieValue3);
  244. name_update.ExpectSingleCookie(kCookieName1, kCookieValue3);
  245. }
  246. // Set kCookieName2 empty, which will notify only the global and URL
  247. // observers. If the name observer is mis-notified then the next step, below,
  248. // will fail.
  249. {
  250. GetNextCookiesIteratorResult global_update(global_changes.get());
  251. GetNextCookiesIteratorResult url_update(url_changes.get());
  252. DeleteCookieAsync(kCookieName2, kCookieValue2);
  253. global_update.ExpectDeleteSingleCookie(kCookieName2);
  254. url_update.ExpectDeleteSingleCookie(kCookieName2);
  255. }
  256. // Set kCookieName1 empty, which will notify all the observers that it was
  257. // removed.
  258. {
  259. GetNextCookiesIteratorResult global_update(global_changes.get());
  260. GetNextCookiesIteratorResult url_update(url_changes.get());
  261. GetNextCookiesIteratorResult name_update(name_changes.get());
  262. DeleteCookieAsync(kCookieName1, kCookieValue3);
  263. global_update.ExpectDeleteSingleCookie(kCookieName1);
  264. url_update.ExpectDeleteSingleCookie(kCookieName1);
  265. name_update.ExpectDeleteSingleCookie(kCookieName1);
  266. }
  267. // Verify that no updates were received for the "other" URL (since we did not
  268. // set any cookies for it). It is possible that this could pass due to the
  269. // CookiesIterator not having been scheduled, but that is very unlikely.
  270. other_updates.ExpectReceivedNoUpdates();
  271. }
  272. TEST_F(CookieManagerImplTest, UpdateBatching) {
  273. fuchsia::web::CookiesIteratorPtr global_changes;
  274. global_changes.set_error_handler([](zx_status_t) { ADD_FAILURE(); });
  275. cookie_manager_.ObserveCookieChanges(nullptr, nullptr,
  276. global_changes.NewRequest());
  277. // Ensure that all ObserveCookieChanges() were processed before modifying
  278. // cookies.
  279. EXPECT_EQ(GetAllCookies()->size(), 0u);
  280. {
  281. // Verify that some insertions are batched into a single GetNext() result.
  282. CreateAndSetCookieAsync(kCookieName1, kCookieValue1);
  283. CreateAndSetCookieAsync(kCookieName2, kCookieValue2);
  284. CreateAndSetCookieAsync(kCookieName1, kCookieValue3);
  285. // Flush the Cookie Manager so that all cookie changes are processed.
  286. mojo_cookie_manager_.FlushForTesting();
  287. // Run all pending tasks so that CookiesIteratorImpl receives all cookie
  288. // changes through network::mojom::CookieChangeListener::OnCookieChange().
  289. // This is important because fuchsia::web::CookiesIterator::GetNext() only
  290. // returns cookie updates that have already been received by the iterator
  291. // implementation.
  292. base::RunLoop().RunUntilIdle();
  293. // Request cookie updates through fuchsia::web::CookiesIterator::GetNext().
  294. // Multiple updates to the same cookie should be coalesced.
  295. GetNextCookiesIteratorResult global_updates(global_changes.get());
  296. global_updates.ExpectCookieUpdates(
  297. {{kCookieName1, kCookieValue3}, {kCookieName2, kCookieValue2}});
  298. }
  299. {
  300. // Verify that some deletions are batched into a single GetNext() result.
  301. DeleteCookieAsync(kCookieName2, kCookieValue2);
  302. DeleteCookieAsync(kCookieName1, kCookieValue3);
  303. mojo_cookie_manager_.FlushForTesting();
  304. GetNextCookiesIteratorResult global_updates(global_changes.get());
  305. global_updates.ExpectCookieUpdates(
  306. {{kCookieName1, absl::nullopt}, {kCookieName2, absl::nullopt}});
  307. }
  308. }
  309. TEST_F(CookieManagerImplTest, ReconnectToNetworkContext) {
  310. // Attach a cookie observer, which we expect should become disconnected with
  311. // an appropriate error if the NetworkService goes away.
  312. base::RunLoop mojo_disconnect_loop;
  313. cookie_manager_.set_on_mojo_disconnected_for_test(
  314. mojo_disconnect_loop.QuitClosure());
  315. // Verify that GetAllCookies() returns a valid list of cookies (as opposed to
  316. // not returning a list at all) initially.
  317. EXPECT_TRUE(GetAllCookies().has_value());
  318. // Tear-down and re-create the NetworkService and |network_context_|, causing
  319. // the CookieManager's connection to it to be dropped.
  320. network_service_.reset();
  321. network_context_.reset();
  322. network_service_ = network::NetworkService::CreateForTesting();
  323. // Wait for the |cookie_manager_| to observe the NetworkContext disconnect,
  324. // so that GetAllCookies() can re-connect.
  325. mojo_disconnect_loop.Run();
  326. // If the CookieManager fails to re-connect then GetAllCookies() will receive
  327. // no data (as opposed to receiving an empty list of cookies).
  328. EXPECT_TRUE(GetAllCookies().has_value());
  329. }