CookieJar.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. /*
  2. * Copyright (c) 2021-2024, Tim Flynn <trflynn89@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2023, Jelle Raaijmakers <jelle@gmta.nl>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/IPv4Address.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/Time.h>
  12. #include <AK/Vector.h>
  13. #include <LibURL/URL.h>
  14. #include <LibWeb/Cookie/ParsedCookie.h>
  15. #include <LibWebView/CookieJar.h>
  16. #include <LibWebView/URL.h>
  17. namespace WebView {
  18. static constexpr auto DATABASE_SYNCHRONIZATION_TIMER = AK::Duration::from_seconds(30);
  19. ErrorOr<NonnullOwnPtr<CookieJar>> CookieJar::create(Database& database)
  20. {
  21. Statements statements {};
  22. auto create_table = TRY(database.prepare_statement(MUST(String::formatted(R"#(
  23. CREATE TABLE IF NOT EXISTS Cookies (
  24. name TEXT,
  25. value TEXT,
  26. same_site INTEGER CHECK (same_site >= 0 AND same_site <= {}),
  27. creation_time INTEGER,
  28. last_access_time INTEGER,
  29. expiry_time INTEGER,
  30. domain TEXT,
  31. path TEXT,
  32. secure BOOLEAN,
  33. http_only BOOLEAN,
  34. host_only BOOLEAN,
  35. persistent BOOLEAN,
  36. PRIMARY KEY(name, domain, path)
  37. );)#",
  38. to_underlying(Web::Cookie::SameSite::Lax)))));
  39. database.execute_statement(create_table, {});
  40. statements.insert_cookie = TRY(database.prepare_statement("INSERT OR REPLACE INTO Cookies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"sv));
  41. statements.expire_cookie = TRY(database.prepare_statement("DELETE FROM Cookies WHERE (expiry_time < ?);"sv));
  42. statements.select_all_cookies = TRY(database.prepare_statement("SELECT * FROM Cookies;"sv));
  43. return adopt_own(*new CookieJar { PersistedStorage { database, statements } });
  44. }
  45. NonnullOwnPtr<CookieJar> CookieJar::create()
  46. {
  47. return adopt_own(*new CookieJar { OptionalNone {} });
  48. }
  49. CookieJar::CookieJar(Optional<PersistedStorage> persisted_storage)
  50. : m_persisted_storage(move(persisted_storage))
  51. {
  52. if (!m_persisted_storage.has_value())
  53. return;
  54. // FIXME: Make cookie retrieval lazy so we don't need to retrieve all cookies up front.
  55. auto cookies = m_persisted_storage->select_all_cookies();
  56. m_transient_storage.set_cookies(move(cookies));
  57. m_persisted_storage->synchronization_timer = Core::Timer::create_repeating(
  58. static_cast<int>(DATABASE_SYNCHRONIZATION_TIMER.to_milliseconds()),
  59. [this]() {
  60. for (auto const& it : m_transient_storage.take_dirty_cookies())
  61. m_persisted_storage->insert_cookie(it.value);
  62. auto now = m_transient_storage.purge_expired_cookies();
  63. m_persisted_storage->database.execute_statement(m_persisted_storage->statements.expire_cookie, {}, now);
  64. });
  65. m_persisted_storage->synchronization_timer->start();
  66. }
  67. CookieJar::~CookieJar()
  68. {
  69. if (!m_persisted_storage.has_value())
  70. return;
  71. m_persisted_storage->synchronization_timer->stop();
  72. m_persisted_storage->synchronization_timer->on_timeout();
  73. }
  74. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.8.3
  75. String CookieJar::get_cookie(const URL::URL& url, Web::Cookie::Source source)
  76. {
  77. m_transient_storage.purge_expired_cookies();
  78. auto domain = canonicalize_domain(url);
  79. if (!domain.has_value())
  80. return {};
  81. auto cookie_list = get_matching_cookies(url, domain.value(), source);
  82. // 4. Serialize the cookie-list into a cookie-string by processing each cookie in the cookie-list in order:
  83. StringBuilder builder;
  84. for (auto const& cookie : cookie_list) {
  85. if (!builder.is_empty())
  86. builder.append("; "sv);
  87. // 1. If the cookies' name is not empty, output the cookie's name followed by the %x3D ("=") character.
  88. if (!cookie.name.is_empty())
  89. builder.appendff("{}=", cookie.name);
  90. // 2. If the cookies' value is not empty, output the cookie's value.
  91. if (!cookie.value.is_empty())
  92. builder.append(cookie.value);
  93. // 3. If there is an unprocessed cookie in the cookie-list, output the characters %x3B and %x20 ("; ").
  94. }
  95. return MUST(builder.to_string());
  96. }
  97. void CookieJar::set_cookie(const URL::URL& url, Web::Cookie::ParsedCookie const& parsed_cookie, Web::Cookie::Source source)
  98. {
  99. auto domain = canonicalize_domain(url);
  100. if (!domain.has_value())
  101. return;
  102. store_cookie(parsed_cookie, url, domain.release_value(), source);
  103. }
  104. // This is based on store_cookie() below, however the whole ParsedCookie->Cookie conversion is skipped.
  105. void CookieJar::update_cookie(Web::Cookie::Cookie cookie)
  106. {
  107. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  108. // 23. If the cookie store contains a cookie with the same name, domain, host-only-flag, and path as the
  109. // newly-created cookie:
  110. if (auto const& old_cookie = m_transient_storage.get_cookie(key); old_cookie.has_value() && old_cookie->host_only == cookie.host_only) {
  111. // 3. Update the creation-time of the newly-created cookie to match the creation-time of the old-cookie.
  112. cookie.creation_time = old_cookie->creation_time;
  113. // 4. Remove the old-cookie from the cookie store.
  114. // NOTE: Rather than deleting then re-inserting this cookie, we update it in-place.
  115. }
  116. // 24. Insert the newly-created cookie into the cookie store.
  117. m_transient_storage.set_cookie(move(key), move(cookie));
  118. m_transient_storage.purge_expired_cookies();
  119. }
  120. void CookieJar::dump_cookies()
  121. {
  122. StringBuilder builder;
  123. m_transient_storage.for_each_cookie([&](auto const& cookie) {
  124. static constexpr auto key_color = "\033[34;1m"sv;
  125. static constexpr auto attribute_color = "\033[33m"sv;
  126. static constexpr auto no_color = "\033[0m"sv;
  127. builder.appendff("{}{}{} - ", key_color, cookie.name, no_color);
  128. builder.appendff("{}{}{} - ", key_color, cookie.domain, no_color);
  129. builder.appendff("{}{}{}\n", key_color, cookie.path, no_color);
  130. builder.appendff("\t{}Value{} = {}\n", attribute_color, no_color, cookie.value);
  131. builder.appendff("\t{}CreationTime{} = {}\n", attribute_color, no_color, cookie.creation_time_to_string());
  132. builder.appendff("\t{}LastAccessTime{} = {}\n", attribute_color, no_color, cookie.last_access_time_to_string());
  133. builder.appendff("\t{}ExpiryTime{} = {}\n", attribute_color, no_color, cookie.expiry_time_to_string());
  134. builder.appendff("\t{}Secure{} = {:s}\n", attribute_color, no_color, cookie.secure);
  135. builder.appendff("\t{}HttpOnly{} = {:s}\n", attribute_color, no_color, cookie.http_only);
  136. builder.appendff("\t{}HostOnly{} = {:s}\n", attribute_color, no_color, cookie.host_only);
  137. builder.appendff("\t{}Persistent{} = {:s}\n", attribute_color, no_color, cookie.persistent);
  138. builder.appendff("\t{}SameSite{} = {:s}\n", attribute_color, no_color, Web::Cookie::same_site_to_string(cookie.same_site));
  139. });
  140. dbgln("{} cookies stored\n{}", m_transient_storage.size(), builder.string_view());
  141. }
  142. Vector<Web::Cookie::Cookie> CookieJar::get_all_cookies()
  143. {
  144. Vector<Web::Cookie::Cookie> cookies;
  145. cookies.ensure_capacity(m_transient_storage.size());
  146. m_transient_storage.for_each_cookie([&](auto const& cookie) {
  147. cookies.unchecked_append(cookie);
  148. });
  149. return cookies;
  150. }
  151. // https://w3c.github.io/webdriver/#dfn-associated-cookies
  152. Vector<Web::Cookie::Cookie> CookieJar::get_all_cookies(URL::URL const& url)
  153. {
  154. auto domain = canonicalize_domain(url);
  155. if (!domain.has_value())
  156. return {};
  157. return get_matching_cookies(url, domain.value(), Web::Cookie::Source::Http, MatchingCookiesSpecMode::WebDriver);
  158. }
  159. Optional<Web::Cookie::Cookie> CookieJar::get_named_cookie(URL::URL const& url, StringView name)
  160. {
  161. auto domain = canonicalize_domain(url);
  162. if (!domain.has_value())
  163. return {};
  164. auto cookie_list = get_matching_cookies(url, domain.value(), Web::Cookie::Source::Http, MatchingCookiesSpecMode::WebDriver);
  165. for (auto const& cookie : cookie_list) {
  166. if (cookie.name == name)
  167. return cookie;
  168. }
  169. return {};
  170. }
  171. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.1.2
  172. Optional<String> CookieJar::canonicalize_domain(const URL::URL& url)
  173. {
  174. if (!url.is_valid() || url.host().has<Empty>())
  175. return {};
  176. // 1. Convert the host name to a sequence of individual domain name labels.
  177. // 2. Convert each label that is not a Non-Reserved LDH (NR-LDH) label, to an A-label (see Section 2.3.2.1 of
  178. // [RFC5890] for the former and latter), or to a "punycode label" (a label resulting from the "ToASCII" conversion
  179. // in Section 4 of [RFC3490]), as appropriate (see Section 6.3 of this specification).
  180. // 3. Concatenate the resulting labels, separated by a %x2E (".") character.
  181. // FIXME: Implement the above conversions.
  182. return MUST(MUST(url.serialized_host()).to_lowercase());
  183. }
  184. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.1.3
  185. bool CookieJar::domain_matches(StringView string, StringView domain_string)
  186. {
  187. // A string domain-matches a given domain string if at least one of the following conditions hold:
  188. // * The domain string and the string are identical. (Note that both the domain string and the string will have been
  189. // canonicalized to lower case at this point.)
  190. if (string == domain_string)
  191. return true;
  192. // * All of the following conditions hold:
  193. // - The domain string is a suffix of the string.
  194. if (!string.ends_with(domain_string))
  195. return false;
  196. // - The last character of the string that is not included in the domain string is a %x2E (".") character.
  197. if (string[string.length() - domain_string.length() - 1] != '.')
  198. return false;
  199. // - The string is a host name (i.e., not an IP address).
  200. if (AK::IPv4Address::from_string(string).has_value())
  201. return false;
  202. return true;
  203. }
  204. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.1.4
  205. bool CookieJar::path_matches(StringView request_path, StringView cookie_path)
  206. {
  207. // A request-path path-matches a given cookie-path if at least one of the following conditions holds:
  208. // * The cookie-path and the request-path are identical.
  209. if (request_path == cookie_path)
  210. return true;
  211. if (request_path.starts_with(cookie_path)) {
  212. // * The cookie-path is a prefix of the request-path, and the last character of the cookie-path is %x2F ("/").
  213. if (cookie_path.ends_with('/'))
  214. return true;
  215. // * The cookie-path is a prefix of the request-path, and the first character of the request-path that is not
  216. // included in the cookie-path is a %x2F ("/") character.
  217. if (request_path[cookie_path.length()] == '/')
  218. return true;
  219. }
  220. return false;
  221. }
  222. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.1.4
  223. String CookieJar::default_path(const URL::URL& url)
  224. {
  225. // 1. Let uri-path be the path portion of the request-uri if such a portion exists (and empty otherwise).
  226. auto uri_path = URL::percent_decode(url.serialize_path());
  227. // 2. If the uri-path is empty or if the first character of the uri-path is not a %x2F ("/") character, output
  228. // %x2F ("/") and skip the remaining steps.
  229. if (uri_path.is_empty() || (uri_path[0] != '/'))
  230. return "/"_string;
  231. StringView uri_path_view = uri_path;
  232. size_t last_separator = uri_path_view.find_last('/').value();
  233. // 3. If the uri-path contains no more than one %x2F ("/") character, output %x2F ("/") and skip the remaining step.
  234. if (last_separator == 0)
  235. return "/"_string;
  236. // 4. Output the characters of the uri-path from the first character up to, but not including, the right-most
  237. // %x2F ("/").
  238. // FIXME: The path might not be valid UTF-8.
  239. return MUST(String::from_utf8(uri_path.substring_view(0, last_separator)));
  240. }
  241. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#name-storage-model
  242. void CookieJar::store_cookie(Web::Cookie::ParsedCookie const& parsed_cookie, const URL::URL& url, String canonicalized_domain, Web::Cookie::Source source)
  243. {
  244. // 1. A user agent MAY ignore a received cookie in its entirety. See Section 5.3.
  245. // 2. If cookie-name is empty and cookie-value is empty, abort these steps and ignore the cookie entirely.
  246. if (parsed_cookie.name.is_empty() && parsed_cookie.value.is_empty())
  247. return;
  248. // 3. If the cookie-name or the cookie-value contains a %x00-08 / %x0A-1F / %x7F character (CTL characters
  249. // excluding HTAB), abort these steps and ignore the cookie entirely.
  250. if (Web::Cookie::cookie_contains_invalid_control_character(parsed_cookie.name))
  251. return;
  252. if (Web::Cookie::cookie_contains_invalid_control_character(parsed_cookie.value))
  253. return;
  254. // 4. If the sum of the lengths of cookie-name and cookie-value is more than 4096 octets, abort these steps and
  255. // ignore the cookie entirely.
  256. if (parsed_cookie.name.byte_count() + parsed_cookie.value.byte_count() > 4096)
  257. return;
  258. // 5. Create a new cookie with name cookie-name, value cookie-value. Set the creation-time and the last-access-time
  259. // to the current date and time.
  260. Web::Cookie::Cookie cookie { parsed_cookie.name, parsed_cookie.value };
  261. cookie.creation_time = UnixDateTime::now();
  262. cookie.last_access_time = cookie.creation_time;
  263. // 6. If the cookie-attribute-list contains an attribute with an attribute-name of "Max-Age":
  264. if (parsed_cookie.expiry_time_from_max_age_attribute.has_value()) {
  265. // 1. Set the cookie's persistent-flag to true.
  266. cookie.persistent = true;
  267. // 2. Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with
  268. // an attribute-name of "Max-Age".
  269. cookie.expiry_time = parsed_cookie.expiry_time_from_max_age_attribute.value();
  270. }
  271. // Otherwise, if the cookie-attribute-list contains an attribute with an attribute-name of "Expires" (and does not
  272. // contain an attribute with an attribute-name of "Max-Age"):
  273. else if (parsed_cookie.expiry_time_from_expires_attribute.has_value()) {
  274. // 1. Set the cookie's persistent-flag to true.
  275. cookie.persistent = true;
  276. // 2. Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with
  277. // an attribute-name of "Expires".
  278. cookie.expiry_time = parsed_cookie.expiry_time_from_expires_attribute.value();
  279. }
  280. // Otherwise:
  281. else {
  282. // 1. Set the cookie's persistent-flag to false.
  283. cookie.persistent = false;
  284. // 2. Set the cookie's expiry-time to the latest representable date.
  285. cookie.expiry_time = UnixDateTime::from_unix_time_parts(3000, 1, 1, 0, 0, 0, 0);
  286. }
  287. String domain_attribute;
  288. // 7. If the cookie-attribute-list contains an attribute with an attribute-name of "Domain":
  289. if (parsed_cookie.domain.has_value()) {
  290. // 1. Let the domain-attribute be the attribute-value of the last attribute in the cookie-attribute-list with
  291. // both an attribute-name of "Domain" and an attribute-value whose length is no more than 1024 octets. (Note
  292. // that a leading %x2E ("."), if present, is ignored even though that character is not permitted.)
  293. if (parsed_cookie.domain->byte_count() <= 1024)
  294. domain_attribute = parsed_cookie.domain.value();
  295. }
  296. // Otherwise:
  297. else {
  298. // 1. Let the domain-attribute be the empty string.
  299. }
  300. // 8. If the domain-attribute contains a character that is not in the range of [USASCII] characters, abort these
  301. // steps and ignore the cookie entirely.
  302. for (auto code_point : domain_attribute.code_points()) {
  303. if (!is_ascii(code_point))
  304. return;
  305. }
  306. // 9. If the user agent is configured to reject "public suffixes" and the domain-attribute is a public suffix:
  307. if (is_public_suffix(domain_attribute)) {
  308. // 1. If the domain-attribute is identical to the canonicalized request-host:
  309. if (domain_attribute == canonicalized_domain) {
  310. // 1. Let the domain-attribute be the empty string.
  311. domain_attribute = String {};
  312. }
  313. // Otherwise:
  314. else {
  315. // 1. Abort these steps and ignore the cookie entirely.
  316. return;
  317. }
  318. }
  319. // 10. If the domain-attribute is non-empty:
  320. if (!domain_attribute.is_empty()) {
  321. // 1. If the canonicalized request-host does not domain-match the domain-attribute:
  322. if (!domain_matches(canonicalized_domain, domain_attribute)) {
  323. // 1. Abort these steps and ignore the cookie entirely.
  324. return;
  325. }
  326. // Otherwise:
  327. else {
  328. // 1. Set the cookie's host-only-flag to false.
  329. cookie.host_only = false;
  330. // 2. Set the cookie's domain to the domain-attribute.
  331. cookie.domain = move(domain_attribute);
  332. }
  333. }
  334. // Otherwise:
  335. else {
  336. // 1. Set the cookie's host-only-flag to true.
  337. cookie.host_only = true;
  338. // 2. Set the cookie's domain to the canonicalized request-host.
  339. cookie.domain = move(canonicalized_domain);
  340. }
  341. // 11. If the cookie-attribute-list contains an attribute with an attribute-name of "Path", set the cookie's path to
  342. // attribute-value of the last attribute in the cookie-attribute-list with both an attribute-name of "Path" and
  343. // an attribute-value whose length is no more than 1024 octets. Otherwise, set the cookie's path to the
  344. // default-path of the request-uri.
  345. if (parsed_cookie.path.has_value()) {
  346. if (parsed_cookie.path->byte_count() <= 1024)
  347. cookie.path = parsed_cookie.path.value();
  348. } else {
  349. cookie.path = default_path(url);
  350. }
  351. // 12. If the cookie-attribute-list contains an attribute with an attribute-name of "Secure", set the cookie's
  352. // secure-only-flag to true. Otherwise, set the cookie's secure-only-flag to false.
  353. cookie.secure = parsed_cookie.secure_attribute_present;
  354. // 13. If the request-uri does not denote a "secure" connection (as defined by the user agent), and the cookie's
  355. // secure-only-flag is true, then abort these steps and ignore the cookie entirely.
  356. if (cookie.secure && url.scheme() != "https"sv)
  357. return;
  358. // 14. If the cookie-attribute-list contains an attribute with an attribute-name of "HttpOnly", set the cookie's
  359. // http-only-flag to true. Otherwise, set the cookie's http-only-flag to false.
  360. cookie.http_only = parsed_cookie.http_only_attribute_present;
  361. // 15. If the cookie was received from a "non-HTTP" API and the cookie's http-only-flag is true, abort these steps
  362. // and ignore the cookie entirely.
  363. if (source == Web::Cookie::Source::NonHttp && cookie.http_only)
  364. return;
  365. // 16. If the cookie's secure-only-flag is false, and the request-uri does not denote a "secure" connection, then
  366. // abort these steps and ignore the cookie entirely if the cookie store contains one or more cookies that meet
  367. // all of the following criteria:
  368. if (!cookie.secure && url.scheme() != "https"sv) {
  369. auto ignore_cookie = false;
  370. m_transient_storage.for_each_cookie([&](Web::Cookie::Cookie const& old_cookie) {
  371. // 1. Their name matches the name of the newly-created cookie.
  372. if (old_cookie.name != cookie.name)
  373. return IterationDecision::Continue;
  374. // 2. Their secure-only-flag is true.
  375. if (!old_cookie.secure)
  376. return IterationDecision::Continue;
  377. // 3. Their domain domain-matches the domain of the newly-created cookie, or vice-versa.
  378. if (!domain_matches(old_cookie.domain, cookie.domain) && !domain_matches(cookie.domain, old_cookie.domain))
  379. return IterationDecision::Continue;
  380. // 4. The path of the newly-created cookie path-matches the path of the existing cookie.
  381. if (!path_matches(cookie.path, old_cookie.path))
  382. return IterationDecision::Continue;
  383. ignore_cookie = true;
  384. return IterationDecision::Break;
  385. });
  386. if (ignore_cookie)
  387. return;
  388. }
  389. // 17. If the cookie-attribute-list contains an attribute with an attribute-name of "SameSite", and an
  390. // attribute-value of "Strict", "Lax", or "None", set the cookie's same-site-flag to the attribute-value of the
  391. // last attribute in the cookie-attribute-list with an attribute-name of "SameSite". Otherwise, set the cookie's
  392. // same-site-flag to "Default".
  393. cookie.same_site = parsed_cookie.same_site_attribute;
  394. // 18. If the cookie's same-site-flag is not "None":
  395. if (cookie.same_site != Web::Cookie::SameSite::None) {
  396. // FIXME: 1. If the cookie was received from a "non-HTTP" API, and the API was called from a navigable's active document
  397. // whose "site for cookies" is not same-site with the top-level origin, then abort these steps and ignore the
  398. // newly created cookie entirely.
  399. // FIXME: 2. If the cookie was received from a "same-site" request (as defined in Section 5.2), skip the remaining
  400. // substeps and continue processing the cookie.
  401. // FIXME: 3. If the cookie was received from a request which is navigating a top-level traversable [HTML] (e.g. if the
  402. // request's "reserved client" is either null or an environment whose "target browsing context"'s navigable
  403. // is a top-level traversable), skip the remaining substeps and continue processing the cookie.
  404. // FIXME: 4. Abort these steps and ignore the newly created cookie entirely.
  405. }
  406. // 19. If the cookie's "same-site-flag" is "None", abort these steps and ignore the cookie entirely unless the
  407. // cookie's secure-only-flag is true.
  408. if (cookie.same_site == Web::Cookie::SameSite::None && !cookie.secure)
  409. return;
  410. auto has_case_insensitive_prefix = [&](StringView value, StringView prefix) {
  411. if (value.length() < prefix.length())
  412. return false;
  413. value = value.substring_view(0, prefix.length());
  414. return value.equals_ignoring_ascii_case(prefix);
  415. };
  416. // 20. If the cookie-name begins with a case-insensitive match for the string "__Secure-", abort these steps and
  417. // ignore the cookie entirely unless the cookie's secure-only-flag is true.
  418. if (has_case_insensitive_prefix(cookie.name, "__Secure-"sv) && !cookie.secure)
  419. return;
  420. // 21. If the cookie-name begins with a case-insensitive match for the string "__Host-", abort these steps and
  421. // ignore the cookie entirely unless the cookie meets all the following criteria:
  422. if (has_case_insensitive_prefix(cookie.name, "__Host-"sv)) {
  423. // 1. The cookie's secure-only-flag is true.
  424. if (!cookie.secure)
  425. return;
  426. // 2. The cookie's host-only-flag is true.
  427. if (!cookie.host_only)
  428. return;
  429. // 3. The cookie-attribute-list contains an attribute with an attribute-name of "Path", and the cookie's path is /.
  430. if (parsed_cookie.path.has_value() && parsed_cookie.path != "/"sv)
  431. return;
  432. }
  433. // 22. If the cookie-name is empty and either of the following conditions are true, abort these steps and ignore
  434. // the cookie entirely:
  435. if (cookie.name.is_empty()) {
  436. // * the cookie-value begins with a case-insensitive match for the string "__Secure-"
  437. if (has_case_insensitive_prefix(cookie.value, "__Secure-"sv))
  438. return;
  439. // * the cookie-value begins with a case-insensitive match for the string "__Host-"
  440. if (has_case_insensitive_prefix(cookie.value, "__Host-"sv))
  441. return;
  442. }
  443. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  444. // 23. If the cookie store contains a cookie with the same name, domain, host-only-flag, and path as the
  445. // newly-created cookie:
  446. if (auto const& old_cookie = m_transient_storage.get_cookie(key); old_cookie.has_value() && old_cookie->host_only == cookie.host_only) {
  447. // 1. Let old-cookie be the existing cookie with the same name, domain, host-only-flag, and path as the
  448. // newly-created cookie. (Notice that this algorithm maintains the invariant that there is at most one such
  449. // cookie.)
  450. // 2. If the newly-created cookie was received from a "non-HTTP" API and the old-cookie's http-only-flag is true,
  451. // abort these steps and ignore the newly created cookie entirely.
  452. if (source == Web::Cookie::Source::NonHttp && old_cookie->http_only)
  453. return;
  454. // 3. Update the creation-time of the newly-created cookie to match the creation-time of the old-cookie.
  455. cookie.creation_time = old_cookie->creation_time;
  456. // 4. Remove the old-cookie from the cookie store.
  457. // NOTE: Rather than deleting then re-inserting this cookie, we update it in-place.
  458. }
  459. // 24. Insert the newly-created cookie into the cookie store.
  460. m_transient_storage.set_cookie(move(key), move(cookie));
  461. m_transient_storage.purge_expired_cookies();
  462. }
  463. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.8.3
  464. Vector<Web::Cookie::Cookie> CookieJar::get_matching_cookies(const URL::URL& url, StringView canonicalized_domain, Web::Cookie::Source source, MatchingCookiesSpecMode mode)
  465. {
  466. auto now = UnixDateTime::now();
  467. // 1. Let cookie-list be the set of cookies from the cookie store that meets all of the following requirements:
  468. Vector<Web::Cookie::Cookie> cookie_list;
  469. m_transient_storage.for_each_cookie([&](Web::Cookie::Cookie& cookie) {
  470. // * Either:
  471. // The cookie's host-only-flag is true and the canonicalized host of the retrieval's URI is identical to
  472. // the cookie's domain.
  473. bool is_host_only_and_has_identical_domain = cookie.host_only && (canonicalized_domain == cookie.domain);
  474. // Or:
  475. // The cookie's host-only-flag is false and the canonicalized host of the retrieval's URI domain-matches
  476. // the cookie's domain.
  477. bool is_not_host_only_and_domain_matches = !cookie.host_only && domain_matches(canonicalized_domain, cookie.domain);
  478. if (!is_host_only_and_has_identical_domain && !is_not_host_only_and_domain_matches)
  479. return;
  480. // * The retrieval's URI's path path-matches the cookie's path.
  481. if (!path_matches(url.serialize_path(), cookie.path))
  482. return;
  483. // * If the cookie's secure-only-flag is true, then the retrieval's URI must denote a "secure" connection (as
  484. // defined by the user agent).
  485. if (cookie.secure && url.scheme() != "https"sv)
  486. return;
  487. // * If the cookie's http-only-flag is true, then exclude the cookie if the retrieval's type is "non-HTTP".
  488. if (cookie.http_only && (source != Web::Cookie::Source::Http))
  489. return;
  490. // FIXME: * If the cookie's same-site-flag is not "None" and the retrieval's same-site status is "cross-site", then
  491. // exclude the cookie unless all of the following conditions are met:
  492. // * The retrieval's type is "HTTP".
  493. // * The same-site-flag is "Lax" or "Default".
  494. // * The HTTP request associated with the retrieval uses a "safe" method.
  495. // * The target browsing context of the HTTP request associated with the retrieval is the active browsing context
  496. // or a top-level traversable.
  497. // NOTE: The WebDriver spec expects only step 1 above to be executed to match cookies.
  498. if (mode == MatchingCookiesSpecMode::WebDriver) {
  499. cookie_list.append(cookie);
  500. return;
  501. }
  502. // 3. Update the last-access-time of each cookie in the cookie-list to the current date and time.
  503. // NOTE: We do this first so that both our internal storage and cookie-list are updated.
  504. cookie.last_access_time = now;
  505. // 2. The user agent SHOULD sort the cookie-list in the following order:
  506. auto cookie_path_length = cookie.path.bytes().size();
  507. auto cookie_creation_time = cookie.creation_time;
  508. cookie_list.insert_before_matching(cookie, [cookie_path_length, cookie_creation_time](auto const& entry) {
  509. // * Cookies with longer paths are listed before cookies with shorter paths.
  510. if (cookie_path_length > entry.path.bytes().size()) {
  511. return true;
  512. }
  513. // * Among cookies that have equal-length path fields, cookies with earlier creation-times are listed
  514. // before cookies with later creation-times.
  515. if (cookie_path_length == entry.path.bytes().size()) {
  516. if (cookie_creation_time < entry.creation_time)
  517. return true;
  518. }
  519. return false;
  520. });
  521. });
  522. if (mode != MatchingCookiesSpecMode::WebDriver)
  523. m_transient_storage.purge_expired_cookies();
  524. return cookie_list;
  525. }
  526. void CookieJar::TransientStorage::set_cookies(Cookies cookies)
  527. {
  528. m_cookies = move(cookies);
  529. purge_expired_cookies();
  530. }
  531. void CookieJar::TransientStorage::set_cookie(CookieStorageKey key, Web::Cookie::Cookie cookie)
  532. {
  533. m_cookies.set(key, cookie);
  534. m_dirty_cookies.set(move(key), move(cookie));
  535. }
  536. Optional<Web::Cookie::Cookie> CookieJar::TransientStorage::get_cookie(CookieStorageKey const& key)
  537. {
  538. return m_cookies.get(key);
  539. }
  540. UnixDateTime CookieJar::TransientStorage::purge_expired_cookies()
  541. {
  542. auto now = UnixDateTime::now();
  543. auto is_expired = [&](auto const&, auto const& cookie) { return cookie.expiry_time < now; };
  544. m_cookies.remove_all_matching(is_expired);
  545. return now;
  546. }
  547. void CookieJar::PersistedStorage::insert_cookie(Web::Cookie::Cookie const& cookie)
  548. {
  549. database.execute_statement(
  550. statements.insert_cookie,
  551. {},
  552. cookie.name,
  553. cookie.value,
  554. to_underlying(cookie.same_site),
  555. cookie.creation_time,
  556. cookie.last_access_time,
  557. cookie.expiry_time,
  558. cookie.domain,
  559. cookie.path,
  560. cookie.secure,
  561. cookie.http_only,
  562. cookie.host_only,
  563. cookie.persistent);
  564. }
  565. static Web::Cookie::Cookie parse_cookie(Database& database, Database::StatementID statement_id)
  566. {
  567. int column = 0;
  568. auto convert_text = [&](auto& field) { field = database.result_column<String>(statement_id, column++); };
  569. auto convert_bool = [&](auto& field) { field = database.result_column<bool>(statement_id, column++); };
  570. auto convert_time = [&](auto& field) { field = database.result_column<UnixDateTime>(statement_id, column++); };
  571. auto convert_same_site = [&](auto& field) {
  572. auto same_site = database.result_column<UnderlyingType<Web::Cookie::SameSite>>(statement_id, column++);
  573. field = static_cast<Web::Cookie::SameSite>(same_site);
  574. };
  575. Web::Cookie::Cookie cookie;
  576. convert_text(cookie.name);
  577. convert_text(cookie.value);
  578. convert_same_site(cookie.same_site);
  579. convert_time(cookie.creation_time);
  580. convert_time(cookie.last_access_time);
  581. convert_time(cookie.expiry_time);
  582. convert_text(cookie.domain);
  583. convert_text(cookie.path);
  584. convert_bool(cookie.secure);
  585. convert_bool(cookie.http_only);
  586. convert_bool(cookie.host_only);
  587. convert_bool(cookie.persistent);
  588. return cookie;
  589. }
  590. CookieJar::TransientStorage::Cookies CookieJar::PersistedStorage::select_all_cookies()
  591. {
  592. HashMap<CookieStorageKey, Web::Cookie::Cookie> cookies;
  593. database.execute_statement(
  594. statements.select_all_cookies,
  595. [&](auto statement_id) {
  596. auto cookie = parse_cookie(database, statement_id);
  597. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  598. cookies.set(move(key), move(cookie));
  599. });
  600. return cookies;
  601. }
  602. }