CookieJar.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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#name-storage-model
  223. void CookieJar::store_cookie(Web::Cookie::ParsedCookie const& parsed_cookie, const URL::URL& url, String canonicalized_domain, Web::Cookie::Source source)
  224. {
  225. // 1. A user agent MAY ignore a received cookie in its entirety. See Section 5.3.
  226. // 2. If cookie-name is empty and cookie-value is empty, abort these steps and ignore the cookie entirely.
  227. if (parsed_cookie.name.is_empty() && parsed_cookie.value.is_empty())
  228. return;
  229. // 3. If the cookie-name or the cookie-value contains a %x00-08 / %x0A-1F / %x7F character (CTL characters
  230. // excluding HTAB), abort these steps and ignore the cookie entirely.
  231. if (Web::Cookie::cookie_contains_invalid_control_character(parsed_cookie.name))
  232. return;
  233. if (Web::Cookie::cookie_contains_invalid_control_character(parsed_cookie.value))
  234. return;
  235. // 4. If the sum of the lengths of cookie-name and cookie-value is more than 4096 octets, abort these steps and
  236. // ignore the cookie entirely.
  237. if (parsed_cookie.name.byte_count() + parsed_cookie.value.byte_count() > 4096)
  238. return;
  239. // 5. Create a new cookie with name cookie-name, value cookie-value. Set the creation-time and the last-access-time
  240. // to the current date and time.
  241. Web::Cookie::Cookie cookie { parsed_cookie.name, parsed_cookie.value };
  242. cookie.creation_time = UnixDateTime::now();
  243. cookie.last_access_time = cookie.creation_time;
  244. // 6. If the cookie-attribute-list contains an attribute with an attribute-name of "Max-Age":
  245. if (parsed_cookie.expiry_time_from_max_age_attribute.has_value()) {
  246. // 1. Set the cookie's persistent-flag to true.
  247. cookie.persistent = true;
  248. // 2. Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with
  249. // an attribute-name of "Max-Age".
  250. cookie.expiry_time = parsed_cookie.expiry_time_from_max_age_attribute.value();
  251. }
  252. // Otherwise, if the cookie-attribute-list contains an attribute with an attribute-name of "Expires" (and does not
  253. // contain an attribute with an attribute-name of "Max-Age"):
  254. else if (parsed_cookie.expiry_time_from_expires_attribute.has_value()) {
  255. // 1. Set the cookie's persistent-flag to true.
  256. cookie.persistent = true;
  257. // 2. Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with
  258. // an attribute-name of "Expires".
  259. cookie.expiry_time = parsed_cookie.expiry_time_from_expires_attribute.value();
  260. }
  261. // Otherwise:
  262. else {
  263. // 1. Set the cookie's persistent-flag to false.
  264. cookie.persistent = false;
  265. // 2. Set the cookie's expiry-time to the latest representable date.
  266. cookie.expiry_time = UnixDateTime::from_unix_time_parts(3000, 1, 1, 0, 0, 0, 0);
  267. }
  268. String domain_attribute;
  269. // 7. If the cookie-attribute-list contains an attribute with an attribute-name of "Domain":
  270. if (parsed_cookie.domain.has_value()) {
  271. // 1. Let the domain-attribute be the attribute-value of the last attribute in the cookie-attribute-list with
  272. // both an attribute-name of "Domain" and an attribute-value whose length is no more than 1024 octets. (Note
  273. // that a leading %x2E ("."), if present, is ignored even though that character is not permitted.)
  274. if (parsed_cookie.domain->byte_count() <= 1024)
  275. domain_attribute = parsed_cookie.domain.value();
  276. }
  277. // Otherwise:
  278. else {
  279. // 1. Let the domain-attribute be the empty string.
  280. }
  281. // 8. If the domain-attribute contains a character that is not in the range of [USASCII] characters, abort these
  282. // steps and ignore the cookie entirely.
  283. for (auto code_point : domain_attribute.code_points()) {
  284. if (!is_ascii(code_point))
  285. return;
  286. }
  287. // 9. If the user agent is configured to reject "public suffixes" and the domain-attribute is a public suffix:
  288. if (is_public_suffix(domain_attribute)) {
  289. // 1. If the domain-attribute is identical to the canonicalized request-host:
  290. if (domain_attribute == canonicalized_domain) {
  291. // 1. Let the domain-attribute be the empty string.
  292. domain_attribute = String {};
  293. }
  294. // Otherwise:
  295. else {
  296. // 1. Abort these steps and ignore the cookie entirely.
  297. return;
  298. }
  299. }
  300. // 10. If the domain-attribute is non-empty:
  301. if (!domain_attribute.is_empty()) {
  302. // 1. If the canonicalized request-host does not domain-match the domain-attribute:
  303. if (!domain_matches(canonicalized_domain, domain_attribute)) {
  304. // 1. Abort these steps and ignore the cookie entirely.
  305. return;
  306. }
  307. // Otherwise:
  308. else {
  309. // 1. Set the cookie's host-only-flag to false.
  310. cookie.host_only = false;
  311. // 2. Set the cookie's domain to the domain-attribute.
  312. cookie.domain = move(domain_attribute);
  313. }
  314. }
  315. // Otherwise:
  316. else {
  317. // 1. Set the cookie's host-only-flag to true.
  318. cookie.host_only = true;
  319. // 2. Set the cookie's domain to the canonicalized request-host.
  320. cookie.domain = move(canonicalized_domain);
  321. }
  322. // 11. If the cookie-attribute-list contains an attribute with an attribute-name of "Path", set the cookie's path to
  323. // attribute-value of the last attribute in the cookie-attribute-list with both an attribute-name of "Path" and
  324. // an attribute-value whose length is no more than 1024 octets. Otherwise, set the cookie's path to the
  325. // default-path of the request-uri.
  326. if (parsed_cookie.path.has_value()) {
  327. if (parsed_cookie.path->byte_count() <= 1024)
  328. cookie.path = parsed_cookie.path.value();
  329. } else {
  330. cookie.path = Web::Cookie::default_path(url);
  331. }
  332. // 12. If the cookie-attribute-list contains an attribute with an attribute-name of "Secure", set the cookie's
  333. // secure-only-flag to true. Otherwise, set the cookie's secure-only-flag to false.
  334. cookie.secure = parsed_cookie.secure_attribute_present;
  335. // 13. If the request-uri does not denote a "secure" connection (as defined by the user agent), and the cookie's
  336. // secure-only-flag is true, then abort these steps and ignore the cookie entirely.
  337. if (cookie.secure && url.scheme() != "https"sv)
  338. return;
  339. // 14. If the cookie-attribute-list contains an attribute with an attribute-name of "HttpOnly", set the cookie's
  340. // http-only-flag to true. Otherwise, set the cookie's http-only-flag to false.
  341. cookie.http_only = parsed_cookie.http_only_attribute_present;
  342. // 15. If the cookie was received from a "non-HTTP" API and the cookie's http-only-flag is true, abort these steps
  343. // and ignore the cookie entirely.
  344. if (source == Web::Cookie::Source::NonHttp && cookie.http_only)
  345. return;
  346. // 16. If the cookie's secure-only-flag is false, and the request-uri does not denote a "secure" connection, then
  347. // abort these steps and ignore the cookie entirely if the cookie store contains one or more cookies that meet
  348. // all of the following criteria:
  349. if (!cookie.secure && url.scheme() != "https"sv) {
  350. auto ignore_cookie = false;
  351. m_transient_storage.for_each_cookie([&](Web::Cookie::Cookie const& old_cookie) {
  352. // 1. Their name matches the name of the newly-created cookie.
  353. if (old_cookie.name != cookie.name)
  354. return IterationDecision::Continue;
  355. // 2. Their secure-only-flag is true.
  356. if (!old_cookie.secure)
  357. return IterationDecision::Continue;
  358. // 3. Their domain domain-matches the domain of the newly-created cookie, or vice-versa.
  359. if (!domain_matches(old_cookie.domain, cookie.domain) && !domain_matches(cookie.domain, old_cookie.domain))
  360. return IterationDecision::Continue;
  361. // 4. The path of the newly-created cookie path-matches the path of the existing cookie.
  362. if (!path_matches(cookie.path, old_cookie.path))
  363. return IterationDecision::Continue;
  364. ignore_cookie = true;
  365. return IterationDecision::Break;
  366. });
  367. if (ignore_cookie)
  368. return;
  369. }
  370. // 17. If the cookie-attribute-list contains an attribute with an attribute-name of "SameSite", and an
  371. // attribute-value of "Strict", "Lax", or "None", set the cookie's same-site-flag to the attribute-value of the
  372. // last attribute in the cookie-attribute-list with an attribute-name of "SameSite". Otherwise, set the cookie's
  373. // same-site-flag to "Default".
  374. cookie.same_site = parsed_cookie.same_site_attribute;
  375. // 18. If the cookie's same-site-flag is not "None":
  376. if (cookie.same_site != Web::Cookie::SameSite::None) {
  377. // FIXME: 1. If the cookie was received from a "non-HTTP" API, and the API was called from a navigable's active document
  378. // whose "site for cookies" is not same-site with the top-level origin, then abort these steps and ignore the
  379. // newly created cookie entirely.
  380. // FIXME: 2. If the cookie was received from a "same-site" request (as defined in Section 5.2), skip the remaining
  381. // substeps and continue processing the cookie.
  382. // FIXME: 3. If the cookie was received from a request which is navigating a top-level traversable [HTML] (e.g. if the
  383. // request's "reserved client" is either null or an environment whose "target browsing context"'s navigable
  384. // is a top-level traversable), skip the remaining substeps and continue processing the cookie.
  385. // FIXME: 4. Abort these steps and ignore the newly created cookie entirely.
  386. }
  387. // 19. If the cookie's "same-site-flag" is "None", abort these steps and ignore the cookie entirely unless the
  388. // cookie's secure-only-flag is true.
  389. if (cookie.same_site == Web::Cookie::SameSite::None && !cookie.secure)
  390. return;
  391. auto has_case_insensitive_prefix = [&](StringView value, StringView prefix) {
  392. if (value.length() < prefix.length())
  393. return false;
  394. value = value.substring_view(0, prefix.length());
  395. return value.equals_ignoring_ascii_case(prefix);
  396. };
  397. // 20. If the cookie-name begins with a case-insensitive match for the string "__Secure-", abort these steps and
  398. // ignore the cookie entirely unless the cookie's secure-only-flag is true.
  399. if (has_case_insensitive_prefix(cookie.name, "__Secure-"sv) && !cookie.secure)
  400. return;
  401. // 21. If the cookie-name begins with a case-insensitive match for the string "__Host-", abort these steps and
  402. // ignore the cookie entirely unless the cookie meets all the following criteria:
  403. if (has_case_insensitive_prefix(cookie.name, "__Host-"sv)) {
  404. // 1. The cookie's secure-only-flag is true.
  405. if (!cookie.secure)
  406. return;
  407. // 2. The cookie's host-only-flag is true.
  408. if (!cookie.host_only)
  409. return;
  410. // 3. The cookie-attribute-list contains an attribute with an attribute-name of "Path", and the cookie's path is /.
  411. if (parsed_cookie.path.has_value() && parsed_cookie.path != "/"sv)
  412. return;
  413. }
  414. // 22. If the cookie-name is empty and either of the following conditions are true, abort these steps and ignore
  415. // the cookie entirely:
  416. if (cookie.name.is_empty()) {
  417. // * the cookie-value begins with a case-insensitive match for the string "__Secure-"
  418. if (has_case_insensitive_prefix(cookie.value, "__Secure-"sv))
  419. return;
  420. // * the cookie-value begins with a case-insensitive match for the string "__Host-"
  421. if (has_case_insensitive_prefix(cookie.value, "__Host-"sv))
  422. return;
  423. }
  424. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  425. // 23. If the cookie store contains a cookie with the same name, domain, host-only-flag, and path as the
  426. // newly-created cookie:
  427. if (auto const& old_cookie = m_transient_storage.get_cookie(key); old_cookie.has_value() && old_cookie->host_only == cookie.host_only) {
  428. // 1. Let old-cookie be the existing cookie with the same name, domain, host-only-flag, and path as the
  429. // newly-created cookie. (Notice that this algorithm maintains the invariant that there is at most one such
  430. // cookie.)
  431. // 2. If the newly-created cookie was received from a "non-HTTP" API and the old-cookie's http-only-flag is true,
  432. // abort these steps and ignore the newly created cookie entirely.
  433. if (source == Web::Cookie::Source::NonHttp && old_cookie->http_only)
  434. return;
  435. // 3. Update the creation-time of the newly-created cookie to match the creation-time of the old-cookie.
  436. cookie.creation_time = old_cookie->creation_time;
  437. // 4. Remove the old-cookie from the cookie store.
  438. // NOTE: Rather than deleting then re-inserting this cookie, we update it in-place.
  439. }
  440. // 24. Insert the newly-created cookie into the cookie store.
  441. m_transient_storage.set_cookie(move(key), move(cookie));
  442. m_transient_storage.purge_expired_cookies();
  443. }
  444. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.8.3
  445. Vector<Web::Cookie::Cookie> CookieJar::get_matching_cookies(const URL::URL& url, StringView canonicalized_domain, Web::Cookie::Source source, MatchingCookiesSpecMode mode)
  446. {
  447. auto now = UnixDateTime::now();
  448. // 1. Let cookie-list be the set of cookies from the cookie store that meets all of the following requirements:
  449. Vector<Web::Cookie::Cookie> cookie_list;
  450. m_transient_storage.for_each_cookie([&](Web::Cookie::Cookie& cookie) {
  451. // * Either:
  452. // The cookie's host-only-flag is true and the canonicalized host of the retrieval's URI is identical to
  453. // the cookie's domain.
  454. bool is_host_only_and_has_identical_domain = cookie.host_only && (canonicalized_domain == cookie.domain);
  455. // Or:
  456. // The cookie's host-only-flag is false and the canonicalized host of the retrieval's URI domain-matches
  457. // the cookie's domain.
  458. bool is_not_host_only_and_domain_matches = !cookie.host_only && domain_matches(canonicalized_domain, cookie.domain);
  459. if (!is_host_only_and_has_identical_domain && !is_not_host_only_and_domain_matches)
  460. return;
  461. // * The retrieval's URI's path path-matches the cookie's path.
  462. if (!path_matches(url.serialize_path(), cookie.path))
  463. return;
  464. // * If the cookie's secure-only-flag is true, then the retrieval's URI must denote a "secure" connection (as
  465. // defined by the user agent).
  466. if (cookie.secure && url.scheme() != "https"sv)
  467. return;
  468. // * If the cookie's http-only-flag is true, then exclude the cookie if the retrieval's type is "non-HTTP".
  469. if (cookie.http_only && (source != Web::Cookie::Source::Http))
  470. return;
  471. // FIXME: * If the cookie's same-site-flag is not "None" and the retrieval's same-site status is "cross-site", then
  472. // exclude the cookie unless all of the following conditions are met:
  473. // * The retrieval's type is "HTTP".
  474. // * The same-site-flag is "Lax" or "Default".
  475. // * The HTTP request associated with the retrieval uses a "safe" method.
  476. // * The target browsing context of the HTTP request associated with the retrieval is the active browsing context
  477. // or a top-level traversable.
  478. // NOTE: The WebDriver spec expects only step 1 above to be executed to match cookies.
  479. if (mode == MatchingCookiesSpecMode::WebDriver) {
  480. cookie_list.append(cookie);
  481. return;
  482. }
  483. // 3. Update the last-access-time of each cookie in the cookie-list to the current date and time.
  484. // NOTE: We do this first so that both our internal storage and cookie-list are updated.
  485. cookie.last_access_time = now;
  486. // 2. The user agent SHOULD sort the cookie-list in the following order:
  487. auto cookie_path_length = cookie.path.bytes().size();
  488. auto cookie_creation_time = cookie.creation_time;
  489. cookie_list.insert_before_matching(cookie, [cookie_path_length, cookie_creation_time](auto const& entry) {
  490. // * Cookies with longer paths are listed before cookies with shorter paths.
  491. if (cookie_path_length > entry.path.bytes().size()) {
  492. return true;
  493. }
  494. // * Among cookies that have equal-length path fields, cookies with earlier creation-times are listed
  495. // before cookies with later creation-times.
  496. if (cookie_path_length == entry.path.bytes().size()) {
  497. if (cookie_creation_time < entry.creation_time)
  498. return true;
  499. }
  500. return false;
  501. });
  502. });
  503. if (mode != MatchingCookiesSpecMode::WebDriver)
  504. m_transient_storage.purge_expired_cookies();
  505. return cookie_list;
  506. }
  507. void CookieJar::TransientStorage::set_cookies(Cookies cookies)
  508. {
  509. m_cookies = move(cookies);
  510. purge_expired_cookies();
  511. }
  512. void CookieJar::TransientStorage::set_cookie(CookieStorageKey key, Web::Cookie::Cookie cookie)
  513. {
  514. m_cookies.set(key, cookie);
  515. m_dirty_cookies.set(move(key), move(cookie));
  516. }
  517. Optional<Web::Cookie::Cookie> CookieJar::TransientStorage::get_cookie(CookieStorageKey const& key)
  518. {
  519. return m_cookies.get(key);
  520. }
  521. UnixDateTime CookieJar::TransientStorage::purge_expired_cookies()
  522. {
  523. auto now = UnixDateTime::now();
  524. auto is_expired = [&](auto const&, auto const& cookie) { return cookie.expiry_time < now; };
  525. m_cookies.remove_all_matching(is_expired);
  526. return now;
  527. }
  528. void CookieJar::PersistedStorage::insert_cookie(Web::Cookie::Cookie const& cookie)
  529. {
  530. database.execute_statement(
  531. statements.insert_cookie,
  532. {},
  533. cookie.name,
  534. cookie.value,
  535. to_underlying(cookie.same_site),
  536. cookie.creation_time,
  537. cookie.last_access_time,
  538. cookie.expiry_time,
  539. cookie.domain,
  540. cookie.path,
  541. cookie.secure,
  542. cookie.http_only,
  543. cookie.host_only,
  544. cookie.persistent);
  545. }
  546. static Web::Cookie::Cookie parse_cookie(Database& database, Database::StatementID statement_id)
  547. {
  548. int column = 0;
  549. auto convert_text = [&](auto& field) { field = database.result_column<String>(statement_id, column++); };
  550. auto convert_bool = [&](auto& field) { field = database.result_column<bool>(statement_id, column++); };
  551. auto convert_time = [&](auto& field) { field = database.result_column<UnixDateTime>(statement_id, column++); };
  552. auto convert_same_site = [&](auto& field) {
  553. auto same_site = database.result_column<UnderlyingType<Web::Cookie::SameSite>>(statement_id, column++);
  554. field = static_cast<Web::Cookie::SameSite>(same_site);
  555. };
  556. Web::Cookie::Cookie cookie;
  557. convert_text(cookie.name);
  558. convert_text(cookie.value);
  559. convert_same_site(cookie.same_site);
  560. convert_time(cookie.creation_time);
  561. convert_time(cookie.last_access_time);
  562. convert_time(cookie.expiry_time);
  563. convert_text(cookie.domain);
  564. convert_text(cookie.path);
  565. convert_bool(cookie.secure);
  566. convert_bool(cookie.http_only);
  567. convert_bool(cookie.host_only);
  568. convert_bool(cookie.persistent);
  569. return cookie;
  570. }
  571. CookieJar::TransientStorage::Cookies CookieJar::PersistedStorage::select_all_cookies()
  572. {
  573. HashMap<CookieStorageKey, Web::Cookie::Cookie> cookies;
  574. database.execute_statement(
  575. statements.select_all_cookies,
  576. [&](auto statement_id) {
  577. auto cookie = parse_cookie(database, statement_id);
  578. CookieStorageKey key { cookie.name, cookie.domain, cookie.path };
  579. cookies.set(move(key), move(cookie));
  580. });
  581. return cookies;
  582. }
  583. }