CookieJar.cpp 30 KB

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