From cc7c86fdf4b3d8b556259b49fca5efb4917d05ff Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Tue, 13 Apr 2021 12:28:39 -0400 Subject: [PATCH] Browser: Remove expired cookies from the CookieJar The spec doesn't have any exact steps here, it just notes: The user agent MUST evict all expired cookies from the cookie store if, at any time, an expired cookie exists in the cookie store. Here, we implement "at any time" as "when a cookie is retrieved or stored". --- Userland/Applications/Browser/CookieJar.cpp | 19 ++++++++++++++++++- Userland/Applications/Browser/CookieJar.h | 3 ++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Userland/Applications/Browser/CookieJar.cpp b/Userland/Applications/Browser/CookieJar.cpp index 577233aa11..cb32a1b07d 100644 --- a/Userland/Applications/Browser/CookieJar.cpp +++ b/Userland/Applications/Browser/CookieJar.cpp @@ -45,8 +45,10 @@ struct ParsedCookie { bool http_only_attribute_present { false }; }; -String CookieJar::get_cookie(const URL& url) const +String CookieJar::get_cookie(const URL& url) { + purge_expired_cookies(); + auto domain = canonicalize_domain(url); if (!domain.has_value()) return {}; @@ -76,6 +78,7 @@ void CookieJar::set_cookie(const URL& url, const String& cookie_string) return; store_cookie(parsed_cookie.value(), url, move(domain.value())); + purge_expired_cookies(); } void CookieJar::dump_cookies() const @@ -549,4 +552,18 @@ void CookieJar::store_cookie(ParsedCookie& parsed_cookie, const URL& url, String m_cookies.set(key, move(cookie)); } +void CookieJar::purge_expired_cookies() +{ + time_t now = Core::DateTime::now().timestamp(); + Vector keys_to_evict; + + for (const auto& cookie : m_cookies) { + if (cookie.value.expiry_time.timestamp() < now) + keys_to_evict.append(cookie.key); + } + + for (const auto& key : keys_to_evict) + m_cookies.remove(key); +} + } diff --git a/Userland/Applications/Browser/CookieJar.h b/Userland/Applications/Browser/CookieJar.h index 2576266b2f..cccb75c839 100644 --- a/Userland/Applications/Browser/CookieJar.h +++ b/Userland/Applications/Browser/CookieJar.h @@ -60,7 +60,7 @@ struct CookieStorageKey { class CookieJar { public: - String get_cookie(const URL& url) const; + String get_cookie(const URL& url); void set_cookie(const URL& url, const String& cookie); void dump_cookies() const; @@ -80,6 +80,7 @@ private: static bool domain_matches(const String& string, const String& domain_string); void store_cookie(ParsedCookie& parsed_cookie, const URL& url, String canonicalized_domain); + void purge_expired_cookies(); HashMap m_cookies; };