CookieJar.cpp 31 KB

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