Skip to content

Truly independent web browser

LibWeb+RequestServer: Enforce SameSite cookie rules

Shannon Booth16d438dee449
diff --git a/Libraries/LibHTTP/Cookie/Cookie.cpp b/Libraries/LibHTTP/Cookie/Cookie.cpp
index 3261c45aa3e..3322259d351 100644
--- a/Libraries/LibHTTP/Cookie/Cookie.cpp
+++ b/Libraries/LibHTTP/Cookie/Cookie.cpp
@@ -152,7 +152,7 @@ String default_path(URL::URL const& url)
}
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.8.3
-bool cookie_matches_url(Cookie const& cookie, URL::URL const& url, String const& retrieval_host_canonical, Optional<Source> source)
+bool cookie_matches_url(Cookie const& cookie, URL::URL const& url, String const& retrieval_host_canonical, Source source, SameSiteContext same_site_context)
{
// * Either:
// - The cookie's host-only-flag is true and retrieval-host-canonical is identical to the cookie's domain.
@@ -180,17 +180,39 @@ bool cookie_matches_url(Cookie const& cookie, URL::URL const& url, String const&
if (cookie.http_only && (source != Source::Http))
return false;
- // FIXME: * If the cookie's same-site-flag is not "None" and the retrieval's same-site status is "cross-site", then
- // exclude the cookie unless all of the following conditions are met:
- // * The retrieval's type is "HTTP".
- // * The same-site-flag is "Lax" or "Default".
- // * The HTTP request associated with the retrieval uses a "safe" method.
- // * The target browsing context of the HTTP request associated with the retrieval is the active browsing context
- // or a top-level traversable.
+ // * If the cookie's same-site-flag is not "None" and the retrieval's same-site status is "cross-site", then
+ // exclude the cookie unless all of the following conditions are met:
+ if (cookie.same_site != SameSite::None && same_site_context.status == SameSiteStatus::CrossSite) {
+ // * The retrieval's type is "HTTP".
+ if (source != Source::Http)
+ return false;
+
+ // * The same-site-flag is "Lax" or "Default".
+ if (cookie.same_site != SameSite::Lax && cookie.same_site != SameSite::Default)
+ return false;
+
+ // * The HTTP request associated with the retrieval uses a "safe" method.
+ if (!same_site_context.is_safe_method)
+ return false;
+
+ // * The target browsing context of the HTTP request associated with the retrieval is the active browsing
+ // context or a top-level traversable.
+ if (!same_site_context.is_top_level_navigation)
+ return false;
+ }
return true;
}
+// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.8.2
+SameSiteContext non_http_same_site_context(PartitionContext const& context)
+{
+ // The retrieval's same-site status is "same-site" if the Document's "site for cookies" is same-site with the
+ // top-level origin as defined in Section 5.2.1 (otherwise it is "cross-site").
+ // NB: A context's site for cookies is the top-level origin exactly when it has no cross-site ancestor.
+ return { .status = context.has_cross_site_ancestor ? SameSiteStatus::CrossSite : SameSiteStatus::SameSite };
+}
+
}
template<>
@@ -233,6 +255,25 @@ ErrorOr<HTTP::Cookie::Cookie> IPC::decode(Decoder& decoder)
return HTTP::Cookie::Cookie { move(name), move(value), same_site, creation_time, last_access_time, expiry_time, move(domain), move(path), secure, http_only, host_only, persistent, move(partition_key) };
}
+template<>
+ErrorOr<void> IPC::encode(Encoder& encoder, HTTP::Cookie::SameSiteContext const& context)
+{
+ TRY(encoder.encode(context.status));
+ TRY(encoder.encode(context.is_top_level_navigation));
+ TRY(encoder.encode(context.is_safe_method));
+ return {};
+}
+
+template<>
+ErrorOr<HTTP::Cookie::SameSiteContext> IPC::decode(Decoder& decoder)
+{
+ return HTTP::Cookie::SameSiteContext {
+ .status = TRY(decoder.decode<HTTP::Cookie::SameSiteStatus>()),
+ .is_top_level_navigation = TRY(decoder.decode<bool>()),
+ .is_safe_method = TRY(decoder.decode<bool>()),
+ };
+}
+
template<>
ErrorOr<void> IPC::encode(Encoder& encoder, HTTP::Cookie::PartitionContext const& context)
{
diff --git a/Libraries/LibHTTP/Cookie/Cookie.h b/Libraries/LibHTTP/Cookie/Cookie.h
index 404c5832813..353be685e44 100644
--- a/Libraries/LibHTTP/Cookie/Cookie.h
+++ b/Libraries/LibHTTP/Cookie/Cookie.h
@@ -29,6 +29,19 @@ enum class Source : u8 {
Http,
};
+enum class SameSiteStatus : u8 {
+ CrossSite,
+ SameSite,
+};
+
+struct SameSiteContext {
+ SameSiteStatus status { SameSiteStatus::CrossSite };
+ bool is_top_level_navigation { false };
+ bool is_safe_method { false };
+
+ static SameSiteContext same_site() { return { .status = SameSiteStatus::SameSite }; }
+};
+
struct Cookie {
String creation_time_to_string() const;
String last_access_time_to_string() const;
@@ -74,7 +87,8 @@ bool domain_matches(StringView string, StringView domain_string);
bool path_matches(StringView request_path, StringView cookie_path);
String default_path(URL::URL const&);
-bool cookie_matches_url(Cookie const&, URL::URL const&, String const& retrieval_host_canonical, Optional<Source> = {});
+bool cookie_matches_url(Cookie const&, URL::URL const&, String const& retrieval_host_canonical, Source, SameSiteContext);
+SameSiteContext non_http_same_site_context(PartitionContext const&);
}
@@ -86,6 +100,11 @@ ErrorOr<void> encode(Encoder&, HTTP::Cookie::Cookie const&);
template<>
ErrorOr<HTTP::Cookie::Cookie> decode(Decoder&);
+template<>
+ErrorOr<void> encode(Encoder&, HTTP::Cookie::SameSiteContext const&);
+template<>
+ErrorOr<HTTP::Cookie::SameSiteContext> decode(Decoder&);
+
template<>
ErrorOr<void> encode(Encoder&, HTTP::Cookie::PartitionContext const&);
diff --git a/Libraries/LibRequests/RequestClient.cpp b/Libraries/LibRequests/RequestClient.cpp
index 536b837a02a..8e8ac3d3eef 100644
--- a/Libraries/LibRequests/RequestClient.cpp
+++ b/Libraries/LibRequests/RequestClient.cpp
@@ -61,7 +61,7 @@ void RequestClient::die()
}
}
-RefPtr<Request> RequestClient::start_request(ByteString const& method, URL::URL const& url, Optional<HTTP::HeaderList const&> request_headers, ReadonlyBytes request_body, HTTP::CacheMode cache_mode, HTTP::Cookie::IncludeCredentials include_credentials, TransferLease transfer_lease, Optional<u32> address_selection_hint, CacheMissNotification cache_miss_notification, u64 originating_page_id, Optional<HTTP::NetworkIsolationKey> network_isolation_key)
+RefPtr<Request> RequestClient::start_request(ByteString const& method, URL::URL const& url, HTTP::Cookie::SameSiteContext same_site_context, Optional<HTTP::HeaderList const&> request_headers, ReadonlyBytes request_body, HTTP::CacheMode cache_mode, HTTP::Cookie::IncludeCredentials include_credentials, TransferLease transfer_lease, Optional<u32> address_selection_hint, CacheMissNotification cache_miss_notification, u64 originating_page_id, Optional<HTTP::NetworkIsolationKey> network_isolation_key)
{
auto request_id = m_next_request_id++;
auto headers = request_headers.map([](auto const& headers) { return headers.headers().span(); }).value_or({});
@@ -69,7 +69,7 @@ RefPtr<Request> RequestClient::start_request(ByteString const& method, URL::URL
auto transfer_lease_key = transfer_lease == TransferLease::Yes
? Optional<RequestTransferLeaseKey> { { m_request_server_client_id, request_id } }
: Optional<RequestTransferLeaseKey> {};
- IPCProxy::async_start_request(request_id, method, url, headers, request_body, cache_mode, move(network_isolation_key), include_credentials, transfer_lease_key.has_value(), address_selection_hint, cache_miss_notification == CacheMissNotification::Yes, Core::System::getpid(), originating_page_id);
+ IPCProxy::async_start_request(request_id, method, url, headers, request_body, cache_mode, move(network_isolation_key), include_credentials, transfer_lease_key.has_value(), address_selection_hint, cache_miss_notification == CacheMissNotification::Yes, Core::System::getpid(), originating_page_id, same_site_context);
auto request = Request::create_from_id({}, *this, request_id, move(transfer_lease_key));
m_requests.set(request_id, request);
return request;
@@ -242,10 +242,10 @@ void RequestClient::request_transferred(u64 request_id)
(*request)->did_transfer({});
}
-RefPtr<WebSocket> RequestClient::websocket_connect(URL::URL const& url, Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderList const& request_headers)
+RefPtr<WebSocket> RequestClient::websocket_connect(URL::URL const& url, Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderList const& request_headers, HTTP::Cookie::SameSiteContext same_site_context)
{
auto websocket_id = m_next_websocket_id++;
- IPCProxy::async_websocket_connect(websocket_id, url, network_isolation_key, origin, protocols, extensions, request_headers.headers());
+ IPCProxy::async_websocket_connect(websocket_id, url, network_isolation_key, origin, protocols, extensions, request_headers.headers(), same_site_context);
auto connection = WebSocket::create_from_id({}, *this, websocket_id);
m_websockets.set(websocket_id, connection);
return connection;
diff --git a/Libraries/LibRequests/RequestClient.h b/Libraries/LibRequests/RequestClient.h
index 31fde3b2817..c52ce758f55 100644
--- a/Libraries/LibRequests/RequestClient.h
+++ b/Libraries/LibRequests/RequestClient.h
@@ -50,7 +50,7 @@ public:
virtual ~RequestClient() override;
// Best-effort index into the resolved address pool.
- RefPtr<Request> start_request(ByteString const& method, URL::URL const&, Optional<HTTP::HeaderList const&> request_headers = {}, ReadonlyBytes request_body = {}, HTTP::CacheMode = HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials = HTTP::Cookie::IncludeCredentials::Yes, TransferLease = TransferLease::No, Optional<u32> address_selection_hint = {}, CacheMissNotification = CacheMissNotification::No, u64 originating_page_id = 0, Optional<HTTP::NetworkIsolationKey> = {});
+ RefPtr<Request> start_request(ByteString const& method, URL::URL const&, HTTP::Cookie::SameSiteContext, Optional<HTTP::HeaderList const&> request_headers = {}, ReadonlyBytes request_body = {}, HTTP::CacheMode = HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials = HTTP::Cookie::IncludeCredentials::Yes, TransferLease = TransferLease::No, Optional<u32> address_selection_hint = {}, CacheMissNotification = CacheMissNotification::No, u64 originating_page_id = 0, Optional<HTTP::NetworkIsolationKey> = {});
RefPtr<Request> adopt_request(int source_client_id, u64 source_request_id, TransferLease = TransferLease::No);
// Moves a response between RequestServers. The request leaves this client on export; the imported one is a new
@@ -65,7 +65,7 @@ public:
void resolve_host(ByteString const& host, Function<void(Vector<ByteString>)> on_resolved);
int request_server_client_id() const { return m_request_server_client_id; }
- RefPtr<WebSocket> websocket_connect(URL::URL const&, Optional<HTTP::NetworkIsolationKey> const&, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderList const& request_headers);
+ RefPtr<WebSocket> websocket_connect(URL::URL const&, Optional<HTTP::NetworkIsolationKey> const&, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderList const& request_headers, HTTP::Cookie::SameSiteContext);
// Stores the data in the HTTP cache, and returns it mapped read-only from the cache's file, or nothing when it wasn't stored.
diff --git a/Libraries/LibRequests/RequestControlClient.cpp b/Libraries/LibRequests/RequestControlClient.cpp
index 5d04bcb336d..0d1396e99a6 100644
--- a/Libraries/LibRequests/RequestControlClient.cpp
+++ b/Libraries/LibRequests/RequestControlClient.cpp
@@ -48,20 +48,20 @@ void RequestControlClient::client_disconnected(int client_id)
on_client_disconnected(client_id);
}
-void RequestControlClient::retrieve_http_cookie(int client_id, u64 request_id, RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context)
+void RequestControlClient::retrieve_http_cookie(int client_id, u64 request_id, RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context)
{
String cookie;
if (on_retrieve_http_cookie)
- cookie = on_retrieve_http_cookie(client_id, url, partition_context);
+ cookie = on_retrieve_http_cookie(client_id, url, partition_context, same_site_context);
async_retrieved_http_cookie(client_id, request_id, request_type, cookie_request_id, cookie);
}
-void RequestControlClient::store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy)
+void RequestControlClient::store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy)
{
if (on_store_response_cookies_and_hsts_policy)
- on_store_response_cookies_and_hsts_policy(client_id, url, partition_context, cookies, hsts_policy);
+ on_store_response_cookies_and_hsts_policy(client_id, url, partition_context, same_site_context, cookies, hsts_policy);
async_stored_response_cookies_and_hsts_policy(client_id, request_id, store_request_id);
}
diff --git a/Libraries/LibRequests/RequestControlClient.h b/Libraries/LibRequests/RequestControlClient.h
index a0072fecf65..45e4638d620 100644
--- a/Libraries/LibRequests/RequestControlClient.h
+++ b/Libraries/LibRequests/RequestControlClient.h
@@ -36,8 +36,8 @@ public:
Function<void(Vector<NetworkUsage>, u64 interval_microseconds)> on_network_usage;
Function<void(int client_id)> on_client_disconnected;
- Function<String(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&)> on_retrieve_http_cookie;
- Function<void(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&, Vector<HTTP::Cookie::ParsedCookie> const&, Optional<HTTP::HSTS::ParsedHSTSPolicy> const&)> on_store_response_cookies_and_hsts_policy;
+ Function<String(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&, HTTP::Cookie::SameSiteContext)> on_retrieve_http_cookie;
+ Function<void(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&, HTTP::Cookie::SameSiteContext, Vector<HTTP::Cookie::ParsedCookie> const&, Optional<HTTP::HSTS::ParsedHSTSPolicy> const&)> on_store_response_cookies_and_hsts_policy;
Function<void()> on_request_server_died;
Function<void(u64 size)> on_disk_cache_size_changed;
@@ -46,8 +46,8 @@ private:
virtual void network_usage(Vector<NetworkUsage> usage, u64 interval_microseconds) override;
virtual void client_disconnected(int client_id) override;
- virtual void retrieve_http_cookie(int client_id, u64 request_id, RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context) override;
- virtual void store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy) override;
+ virtual void retrieve_http_cookie(int client_id, u64 request_id, RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context) override;
+ virtual void store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy) override;
virtual void estimated_cache_size(u64 cache_size_estimation_id, CacheSizes sizes) override;
virtual void removed_cache_entries(u64 clear_cache_request_id) override;
virtual void disk_cache_size_changed(u64 size) override;
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index a66841cf08d..808d5279c00 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -11901,6 +11901,53 @@ GC::Ptr<DOM::Document> Document::container_document() const
return node_navigable->container_document();
}
+// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#document-requests
+URL::Origin Document::site_for_cookies() const
+{
+ // Note: This algorithm only applies when the entire chain of documents from top-document to document are all active.
+ auto document_navigable = navigable();
+
+ // NB: A pending document can fetch Link header preloads before activation.
+ if (!document_navigable)
+ document_navigable = navigable_awaiting_activation();
+ if (!document_navigable)
+ return URL::Origin::create_opaque();
+
+ // NB: Ancestors may be hosted by another process, so their documents are read through their navigables. This
+ // document is read directly, since it may not be its navigable's active document yet.
+ auto origin_for_cookies = [&](HTML::Navigable const& navigable) -> Optional<URL::Origin> {
+ if (&navigable == document_navigable.ptr())
+ return has_flag(active_sandboxing_flag_set(), HTML::SandboxingFlagSet::SandboxedOrigin) ? url().origin() : origin();
+ if (has_flag(navigable.active_document_sandboxing_flag_set(), HTML::SandboxingFlagSet::SandboxedOrigin))
+ return navigable.active_document_url().map([](auto const& url) { return url.origin(); });
+ return navigable.active_document_origin();
+ };
+
+ // 1. Let top-document be the active document in document's navigable's top-level traversable.
+ auto top_document_navigable = document_navigable->top_level_traversable();
+
+ // 2. Let top-origin be the origin of top-document's URI if top-document's sandboxed origin browsing context flag
+ // is set, and top-document's origin otherwise.
+ auto top_origin = origin_for_cookies(top_document_navigable);
+ if (!top_origin.has_value())
+ return URL::Origin::create_opaque();
+
+ // 3. Let documents be a list consisting of the active documents of document's inclusive ancestor navigables.
+ // 4. For each item in documents:
+ for (GC::Ptr<HTML::Navigable> item = document_navigable; item; item = item->parent()) {
+ // 1. Let origin be the origin of item's URI if item's sandboxed origin browsing context flag is set, and
+ // item's origin otherwise.
+ auto origin = origin_for_cookies(*item);
+
+ // 2. If origin is not same-site with top-origin, return an origin set to an opaque origin.
+ if (!origin.has_value() || !origin->is_same_site(*top_origin))
+ return URL::Origin::create_opaque();
+ }
+
+ // 5. Return top-origin.
+ return top_origin.release_value();
+}
+
GC::Ptr<HTML::LocalNavigable> Document::navigable() const
{
return m_navigable.ptr();
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 252c945af08..ea0afee1711 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -1658,6 +1658,8 @@ public:
i64 cursor_blink_cycle_start_time_ns() const { return m_cursor_blink_cycle_start_time_ns; }
+ URL::Origin site_for_cookies() const;
+
// Back-pointer to the navigable whose active document is this document.
// Maintained by LocalNavigable when it sets/clears its active document.
GC::Ptr<HTML::LocalNavigable> navigable() const;
diff --git a/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cpp b/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cpp
index bdb287a74a9..f85bb9c7514 100644
--- a/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cpp
@@ -121,9 +121,16 @@ NonnullRefPtr<Infrastructure::ClientContextSnapshot const> snapshot_client_conte
global_kind = Context::GlobalKind::Worker;
auto navigable = window ? window->navigable() : nullptr;
auto document = client.responsible_document();
+ auto const* worker = Bindings::worker_global_scope_from_global_object(global);
+ auto site_for_cookies = URL::Origin::create_opaque();
+ if (document)
+ site_for_cookies = document->site_for_cookies();
+ else if (worker)
+ site_for_cookies = worker->site_for_cookies();
return make_ref_counted<Infrastructure::ClientContextSnapshot>(Context {
.origin = client.origin(),
+ .site_for_cookies = move(site_for_cookies),
.creation_url = client.creation_url,
.top_level_creation_url = client.top_level_creation_url,
.top_level_origin = client.top_level_origin,
@@ -155,6 +162,7 @@ NonnullRefPtr<Infrastructure::ClientContextSnapshot const> snapshot_client_conte
// NB: A client another process hosts is never treated as loading bypassing the HTTP cache.
return make_ref_counted<Infrastructure::ClientContextSnapshot>(Context {
.origin = settings.origin,
+ .site_for_cookies = window ? window->associated_document.site_for_cookies : settings.global.get<HTML::SerializedWorkerGlobalScope>().site_for_cookies,
.creation_url = settings.creation_url,
.top_level_creation_url = settings.top_level_creation_url,
.top_level_origin = settings.top_level_origin,
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index b12d817bd69..5981d7dace3 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -2801,6 +2801,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
load_request.set_method(request->method());
load_request.set_cache_mode(request->cache_mode());
load_request.set_include_credentials(include_credentials);
+ load_request.set_same_site_context(request->same_site_context());
load_request.set_initiator_type(request->initiator_type());
load_request.set_destination(request->destination());
load_request.set_request_mode(request->mode());
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h b/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h
index bc6951e18bf..98c56553196 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h
@@ -50,6 +50,7 @@ struct ClientContext {
};
URL::Origin origin;
+ URL::Origin site_for_cookies;
URL::URL creation_url;
Optional<URL::URL> top_level_creation_url;
Optional<URL::Origin> top_level_origin;
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
index 74affad5d9c..3326425859d 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
@@ -91,6 +91,44 @@ void Request::set_policy_container(NonnullRefPtr<HTML::PolicyContainer const> po
m_policy_container = move(policy_container);
}
+// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.2
+HTTP::Cookie::SameSiteStatus Request::same_site_status() const
+{
+ using HTTP::Cookie::SameSiteStatus;
+
+ // 1. The request is not the result of a reload navigation triggered through a user interface element (as defined by
+ // the user agent; e.g., a request triggered by the user clicking a refresh button on a toolbar).
+ if (m_reloaded_document_same_site_status.has_value()) {
+ // Requests which are the result of a reload navigation triggered through a user interface element are same-site
+ // if the reloaded document was originally navigated to via a same-site request. A request that is not "same-site"
+ // is instead "cross-site".
+ return *m_reloaded_document_same_site_status;
+ }
+
+ // 2. The request's current url's origin is same-site with the request's client's "site for cookies" (which is an
+ // origin), or if the request has no client or the request's client is null.
+ if (!m_client_snapshot)
+ return SameSiteStatus::SameSite;
+
+ // AD-HOC: Check every URL of the redirect chain, not only the current one, as tested by cookies/samesite.
+ auto const& site_for_cookies = m_client_snapshot->site_for_cookies;
+ for (auto const& url : url_list()) {
+ if (!url.origin().is_same_site(site_for_cookies))
+ return SameSiteStatus::CrossSite;
+ }
+
+ return SameSiteStatus::SameSite;
+}
+
+HTTP::Cookie::SameSiteContext Request::same_site_context() const
+{
+ return {
+ .status = same_site_status(),
+ .is_top_level_navigation = m_mode == Mode::Navigate && m_destination == Destination::Document,
+ .is_safe_method = m_method.is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv, "TRACE"sv),
+ };
+}
+
// https://fetch.spec.whatwg.org/#request-destination-script-like
bool Request::destination_is_script_like() const
{
@@ -241,6 +279,7 @@ NonnullRefPtr<Request> Request::clone() const
new_request->set_cryptographic_nonce_metadata(m_cryptographic_nonce_metadata);
new_request->set_parser_metadata(m_parser_metadata);
new_request->set_reload_navigation(m_reload_navigation);
+ new_request->m_reloaded_document_same_site_status = m_reloaded_document_same_site_status;
new_request->set_history_navigation(m_history_navigation);
new_request->set_user_activation(m_user_activation);
new_request->set_text_directive_user_activation(m_text_directive_user_activation);
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h
index b7b166ad04d..f6ac3eb1e58 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h
@@ -21,6 +21,7 @@
#include <AK/Variant.h>
#include <AK/Vector.h>
#include <LibHTTP/Cache/CacheMode.h>
+#include <LibHTTP/Cookie/Cookie.h>
#include <LibHTTP/HeaderList.h>
#include <LibURL/Origin.h>
#include <LibURL/URL.h>
@@ -236,6 +237,10 @@ public:
[[nodiscard]] OriginType const& origin() const { return m_origin; }
void set_origin(OriginType origin) { m_origin = move(origin); }
+ [[nodiscard]] HTTP::Cookie::SameSiteStatus same_site_status() const;
+ [[nodiscard]] HTTP::Cookie::SameSiteContext same_site_context() const;
+ void set_reloaded_document_same_site_status(HTTP::Cookie::SameSiteStatus status) { m_reloaded_document_same_site_status = status; }
+
[[nodiscard]] Optional<URL::Origin> const& top_level_navigation_initiator_origin() const { return m_top_level_navigation_initiator_origin; }
void set_top_level_navigation_initiator_origin(Optional<URL::Origin> top_level_navigation_initiator_origin) { m_top_level_navigation_initiator_origin = move(top_level_navigation_initiator_origin); }
@@ -447,6 +452,8 @@ private:
// A request has an associated origin, which is "client" or an origin. Unless stated otherwise it is "client".
OriginType m_origin { Origin::Client };
+ Optional<HTTP::Cookie::SameSiteStatus> m_reloaded_document_same_site_status;
+
// https://fetch.spec.whatwg.org/#request-top-level-navigation-initiator-origin
// A request has an associated top-level navigation initiator origin, which is an origin or null. Unless stated otherwise it is null.
Optional<URL::Origin> m_top_level_navigation_initiator_origin;
diff --git a/Libraries/LibWeb/HTML/DocumentState.h b/Libraries/LibWeb/HTML/DocumentState.h
index fda08af9c8d..541a8ebd947 100644
--- a/Libraries/LibWeb/HTML/DocumentState.h
+++ b/Libraries/LibWeb/HTML/DocumentState.h
@@ -63,6 +63,9 @@ public:
[[nodiscard]] DocumentResource resource() const { return m_resource; }
void set_resource(DocumentResource resource) { m_resource = move(resource); }
+ [[nodiscard]] HTTP::Cookie::SameSiteStatus navigation_same_site_status() const { return m_navigation_same_site_status; }
+ void set_navigation_same_site_status(HTTP::Cookie::SameSiteStatus status) { m_navigation_same_site_status = status; }
+
[[nodiscard]] bool reload_pending() const { return m_reload_pending; }
void set_reload_pending(bool reload_pending) { m_reload_pending = reload_pending; }
@@ -110,6 +113,8 @@ private:
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#document-state-resource
DocumentResource m_resource {};
+ HTTP::Cookie::SameSiteStatus m_navigation_same_site_status { HTTP::Cookie::SameSiteStatus::CrossSite };
+
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#document-state-reload-pending
bool m_reload_pending { false };
diff --git a/Libraries/LibWeb/HTML/HistoryExecutor.cpp b/Libraries/LibWeb/HTML/HistoryExecutor.cpp
index 2b98df63706..8e4b9eb362a 100644
--- a/Libraries/LibWeb/HTML/HistoryExecutor.cpp
+++ b/Libraries/LibWeb/HTML/HistoryExecutor.cpp
@@ -335,6 +335,7 @@ GC::Ref<GC::Function<void(HistoryNavigationPopulation)>> HistoryExecutor::popula
output->redirect_replaced_fragment = result.redirect_replaced_fragment;
output->classic_history_api_state = move(result.classic_history_api_state);
output->resource_cleared = result.resource_cleared;
+ output->navigation_same_site_status = result.navigation_same_site_status;
output->inline_content_origin = move(result.inline_content_origin);
output->document_id = result.document_id;
if (result.replacement_document_state.has_value()) {
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 1d10c0e565f..e05c666eda2 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -239,6 +239,7 @@ public:
Optional<StorageSerializationRecord> classic_history_api_state;
RefPtr<DocumentState> replacement_document_state;
bool resource_cleared = false;
+ Optional<HTTP::Cookie::SameSiteStatus> navigation_same_site_status;
private:
virtual void visit_edges(Cell::Visitor& visitor) override
@@ -616,7 +617,8 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> nav
for (auto const& received : response->release_body_for_transfer())
initial_data.append(received.bytes());
- auto download_id = navigation_params->navigable->page().client().page_did_start_download(navigation_params->navigable->id(), navigation_params->id, download_url, suggested_filename, response_content_length(*response->header_list()), lease->source_client_id, lease->source_request_id, move(initial_data),
+ auto same_site_context = navigation_params->request ? navigation_params->request->same_site_context() : HTTP::Cookie::SameSiteContext {};
+ auto download_id = navigation_params->navigable->page().client().page_did_start_download(navigation_params->navigable->id(), navigation_params->id, download_url, suggested_filename, response_content_length(*response->header_list()), same_site_context, lease->source_client_id, lease->source_request_id, move(initial_data),
move(network_response));
if (!download_id.has_value()) {
stop_response_body_delivery(*navigation_params);
@@ -637,6 +639,8 @@ void PopulateSessionHistoryEntryDocumentOutput::apply_to(NonnullRefPtr<SessionHi
{
if (replacement_document_state)
entry->set_document_state(replacement_document_state);
+ if (navigation_same_site_status.has_value())
+ entry->document_state()->set_navigation_same_site_status(*navigation_same_site_status);
if (redirected_url.has_value()) {
// https://wicg.github.io/scroll-to-text-fragment/#extracting-the-fragment-directive
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
@@ -1005,6 +1009,7 @@ void LocalNavigable::continue_navigation_at_population(NavigationPopulationReque
output->redirect_replaced_fragment = result.redirect_replaced_fragment;
output->classic_history_api_state = move(result.classic_history_api_state);
output->resource_cleared = result.resource_cleared;
+ output->navigation_same_site_status = result.navigation_same_site_status;
output->inline_content_origin = move(result.inline_content_origin);
output->document_id = result.document_id;
@@ -1461,6 +1466,13 @@ Optional<URL::Origin> LocalNavigable::active_document_origin() const
return m_active_document->origin();
}
+SandboxingFlagSet LocalNavigable::active_document_sandboxing_flag_set() const
+{
+ if (!m_active_document)
+ return {};
+ return m_active_document->active_sandboxing_flag_set();
+}
+
Vector<GC::Root<Navigable>> LocalNavigable::active_document_inclusive_descendant_navigables()
{
// AD-HOC: Skip a navigable that doesn't have an active document.
@@ -1539,6 +1551,7 @@ ReplicatedNavigableState LocalNavigable::replicated_state() const
.target_name = target_name(),
.active_document_url = m_active_document->url(),
.active_document_origin = m_active_document->origin(),
+ .active_document_sandboxing_flag_set = m_active_document->active_sandboxing_flag_set(),
.active_document_is_fully_active = m_active_document->is_fully_active(),
.top_level_creation_url = settings.top_level_creation_url.value(),
.top_level_origin = settings.top_level_origin.value(),
@@ -2681,6 +2694,8 @@ static void create_navigation_params_by_fetching(
// 7. If entry's document state's reload pending is true, then set request's reload-navigation flag.
if (document_state.reload_pending) {
request->set_reload_navigation(true);
+ if (user_involvement == UserNavigationInvolvement::BrowserUI)
+ request->set_reloaded_document_same_site_status(document_state.navigation_same_site_status);
// AD-HOC: The specs don't define HTTP cache behavior for reloads. But every major engine forces at least re-
// validation of the reloaded document rather than serving it straight from cache. Use the "no-cache"
@@ -2851,6 +2866,9 @@ static void create_navigation_params_by_fetching(
VERIFY(!state_holder->location_url.value().has_value());
VERIFY(!state_holder->response->is_network_error());
+ if (Fetch::Infrastructure::is_http_or_https_scheme(state_holder->request->current_url().scheme()))
+ result->navigation_same_site_status = state_holder->request->same_site_status();
+
// 25. Let resultPolicyContainer be the result of determining navigation params policy container given response's URL,
// entry's document state's history policy container, sourceSnapshotParams's source policy container, null, and responsePolicyContainer.
RefPtr<PolicyContainer> history_policy_container = state_holder->history_policy_container.visit(
@@ -3000,6 +3018,7 @@ static void create_navigation_population_result(Window& window, GC::Ref<Internal
.classic_history_api_state = move(result->classic_history_api_state),
.replacement_document_state = move(replacement_document_state),
.resource_cleared = result->resource_cleared,
+ .navigation_same_site_status = result->navigation_same_site_status,
});
}));
}
@@ -4291,6 +4310,7 @@ void LocalNavigable::navigate_to_a_javascript_url(NonnullRefPtr<Fetch::Infrastru
document_state->set_navigable_target_name(old_doc_state->navigable_target_name());
// NB: Not one of the spec's document state fields. The entry keeps its URL, so it keeps what its fetch recorded.
document_state->set_user_agent_initiated(old_doc_state->user_agent_initiated());
+ document_state->set_navigation_same_site_status(old_doc_state->navigation_same_site_status());
document_state->set_document_id(new_document->unique_id());
// 12. Let historyEntry be a new session history entry, with
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.h
index 8675c5cda49..01afc542fce 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.h
+++ b/Libraries/LibWeb/HTML/LocalNavigable.h
@@ -144,6 +144,7 @@ public:
virtual Optional<URL::URL> active_document_url() const override;
virtual Optional<URL::Origin> active_document_origin() const override;
+ virtual SandboxingFlagSet active_document_sandboxing_flag_set() const override;
virtual bool active_document_is_fully_active() const override;
virtual bool active_document_is_completely_loaded() const override;
virtual bool active_document_is(DOM::Document const&) const override;
@@ -807,6 +808,7 @@ public:
Optional<StorageSerializationRecord> classic_history_api_state;
RefPtr<DocumentState> replacement_document_state;
bool resource_cleared = false;
+ Optional<HTTP::Cookie::SameSiteStatus> navigation_same_site_status;
Optional<URL::Origin> inline_content_origin;
Optional<CrossProcessId> document_id;
diff --git a/Libraries/LibWeb/HTML/Navigable.h b/Libraries/LibWeb/HTML/Navigable.h
index 48d61f78150..82a7cb1e9d8 100644
--- a/Libraries/LibWeb/HTML/Navigable.h
+++ b/Libraries/LibWeb/HTML/Navigable.h
@@ -71,6 +71,7 @@ public:
virtual Optional<u64> browsing_context_group_id() const = 0;
virtual Optional<URL::URL> active_document_url() const = 0;
virtual Optional<URL::Origin> active_document_origin() const = 0;
+ virtual SandboxingFlagSet active_document_sandboxing_flag_set() const = 0;
virtual bool active_document_is_fully_active() const = 0;
virtual bool active_document_is_completely_loaded() const = 0;
virtual bool active_document_is(DOM::Document const&) const = 0;
diff --git a/Libraries/LibWeb/HTML/RemoteNavigable.h b/Libraries/LibWeb/HTML/RemoteNavigable.h
index 2eed47af1c4..691dd337ad4 100644
--- a/Libraries/LibWeb/HTML/RemoteNavigable.h
+++ b/Libraries/LibWeb/HTML/RemoteNavigable.h
@@ -65,6 +65,7 @@ public:
virtual Optional<URL::URL> active_document_url() const override { return m_replicated_state.active_document_url; }
virtual Optional<URL::Origin> active_document_origin() const override { return m_replicated_state.active_document_origin; }
+ virtual SandboxingFlagSet active_document_sandboxing_flag_set() const override { return m_replicated_state.active_document_sandboxing_flag_set; }
virtual bool active_document_is_fully_active() const override { return m_replicated_state.active_document_is_fully_active; }
virtual bool active_document_is_completely_loaded() const override { return m_replicated_state.active_document_is_completely_loaded; }
virtual bool active_document_is(DOM::Document const&) const override { return false; }
diff --git a/Libraries/LibWeb/HTML/Scripting/Environments.cpp b/Libraries/LibWeb/HTML/Scripting/Environments.cpp
index 8859b5fce6e..f9b122e4657 100644
--- a/Libraries/LibWeb/HTML/Scripting/Environments.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/Environments.cpp
@@ -736,6 +736,7 @@ SerializedEnvironmentSettingsObject EnvironmentSettingsObject::serialize()
return SerializedWindow {
.associated_document {
.url = window->associated_document().url(),
+ .site_for_cookies = window->associated_document().site_for_cookies(),
.relevant_settings_object_is_secure_context = relevant_settings_object_is_secure_context,
.relevant_settings_object_policy_container = move(relevant_settings_object_policy_container),
},
@@ -747,6 +748,7 @@ SerializedEnvironmentSettingsObject EnvironmentSettingsObject::serialize()
auto const* dedicated_worker_global_scope = as_if<DedicatedWorkerGlobalScope>(worker_global_scope);
auto supported_animation_frame_provider = dedicated_worker_global_scope && dedicated_worker_global_scope->is_supported();
return SerializedWorkerGlobalScope {
+ .site_for_cookies = worker_global_scope->site_for_cookies(),
.relevant_settings_object_is_secure_context = relevant_settings_object_is_secure_context,
.relevant_settings_object_policy_container = move(relevant_settings_object_policy_container),
.is_supported_animation_frame_provider = supported_animation_frame_provider,
diff --git a/Libraries/LibWeb/HTML/SessionHistoryEntry.cpp b/Libraries/LibWeb/HTML/SessionHistoryEntry.cpp
index 0a1deb8b765..f81d4fab5e7 100644
--- a/Libraries/LibWeb/HTML/SessionHistoryEntry.cpp
+++ b/Libraries/LibWeb/HTML/SessionHistoryEntry.cpp
@@ -92,6 +92,7 @@ SessionHistoryDocumentStateDescriptor create_session_history_document_state_desc
.origin = document_state.origin(),
.about_base_url = document_state.about_base_url(),
.resource = document_state.resource(),
+ .navigation_same_site_status = document_state.navigation_same_site_status(),
.reload_pending = document_state.reload_pending(),
.reload_bypasses_cache = document_state.reload_bypasses_cache(),
.ever_populated = document_state.ever_populated(),
@@ -211,6 +212,7 @@ void apply_session_history_document_state_descriptor_from_ui_process(DocumentSta
document_state.set_origin(document_state_descriptor.origin);
document_state.set_about_base_url(document_state_descriptor.about_base_url);
document_state.set_resource(document_state_descriptor.resource);
+ document_state.set_navigation_same_site_status(document_state_descriptor.navigation_same_site_status);
document_state.set_reload_pending(document_state_descriptor.reload_pending);
document_state.set_reload_bypasses_cache(document_state_descriptor.reload_bypasses_cache);
document_state.set_ever_populated(document_state_descriptor.ever_populated);
diff --git a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
index adedabe7c3a..a6ea0b980f8 100644
--- a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
@@ -30,6 +30,28 @@
namespace Web::HTML {
+// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#dedicated-and-shared-requests
+URL::Origin WorkerGlobalScope::site_for_cookies() const
+{
+ // 1. Let site be worker's origin.
+ auto site = relevant_settings_object(*this).origin();
+
+ // 2. For each document in worker's Documents:
+ // NB: A worker owner represents the sites for cookies of its own Documents.
+ for (auto const& owner : owner_set()) {
+ // 1. Let document-site be document's "site for cookies" (as defined in Section 5.2.1).
+ auto const* document = owner.get_pointer<SerializedDocument>();
+ auto const& document_site = document ? document->site_for_cookies : owner.get<SerializedWorkerGlobalScope>().site_for_cookies;
+
+ // 2. If document-site is not same-site with site, return an origin set to an opaque origin.
+ if (!document_site.is_same_site(site))
+ return URL::Origin::create_opaque();
+ }
+
+ // 3. Return site.
+ return site;
+}
+
GC_DEFINE_ALLOCATOR(WorkerGlobalScope);
WorkerGlobalScope::WorkerGlobalScope(GC::Ref<Web::Page> page)
diff --git a/Libraries/LibWeb/HTML/WorkerGlobalScope.h b/Libraries/LibWeb/HTML/WorkerGlobalScope.h
index a218807ce91..5ed87d34c78 100644
--- a/Libraries/LibWeb/HTML/WorkerGlobalScope.h
+++ b/Libraries/LibWeb/HTML/WorkerGlobalScope.h
@@ -141,6 +141,8 @@ public:
[[nodiscard]] bool check_embedder_policy(EmbedderPolicy const& owner_policy) const;
[[nodiscard]] ContentSecurityPolicy::Directives::Directive::Result run_csp_initialization() const;
+ URL::Origin site_for_cookies() const;
+
auto& owner_set() { return m_owner_set; }
auto const& owner_set() const { return m_owner_set; }
diff --git a/Libraries/LibWeb/Loader/LoadRequest.h b/Libraries/LibWeb/Loader/LoadRequest.h
index 6bd65d1ac15..2b95b30730d 100644
--- a/Libraries/LibWeb/Loader/LoadRequest.h
+++ b/Libraries/LibWeb/Loader/LoadRequest.h
@@ -10,6 +10,7 @@
#include <AK/Time.h>
#include <LibCore/ElapsedTimer.h>
#include <LibHTTP/Cache/CacheMode.h>
+#include <LibHTTP/Cookie/Cookie.h>
#include <LibHTTP/Cookie/IncludeCredentials.h>
#include <LibHTTP/HeaderList.h>
#include <LibHTTP/NetworkIsolationKey.h>
@@ -65,6 +66,9 @@ public:
Fetch::Infrastructure::Request::Priority priority() const { return m_priority; }
void set_priority(Fetch::Infrastructure::Request::Priority priority) { m_priority = priority; }
+ HTTP::Cookie::SameSiteContext same_site_context() const { return m_same_site_context; }
+ void set_same_site_context(HTTP::Cookie::SameSiteContext context) { m_same_site_context = context; }
+
Optional<HTTP::NetworkIsolationKey> const& network_isolation_key() const { return m_network_isolation_key; }
void set_network_isolation_key(Optional<HTTP::NetworkIsolationKey> network_isolation_key) { m_network_isolation_key = move(network_isolation_key); }
@@ -99,6 +103,7 @@ private:
Fetch::Infrastructure::Request::Priority m_priority { Fetch::Infrastructure::Request::Priority::Auto };
Optional<URL::URL> m_source_url;
Optional<URL::URL> m_top_level_creation_url;
+ HTTP::Cookie::SameSiteContext m_same_site_context;
Optional<HTTP::NetworkIsolationKey> m_network_isolation_key;
};
diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cpp
index f4efbfa55ea..6e482ec8984 100644
--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp
+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp
@@ -632,7 +632,7 @@ RefPtr<Requests::Request> ResourceLoader::start_network_request(LoadRequest cons
// requests are attributed through the worker's browser-level owners.
auto originating_page_id = request.page() && request.page()->has_top_level_traversable() ? request.page()->client().id().value() : 0;
auto headers = headers_with_normalized_values(request.headers());
- auto protocol_request = request_client->start_request(request.method(), request.url().value(), *headers, request.body(), request.cache_mode(), request.include_credentials(), transfer_lease, {}, cache_miss_notification, originating_page_id, request.network_isolation_key());
+ auto protocol_request = request_client->start_request(request.method(), request.url().value(), request.same_site_context(), *headers, request.body(), request.cache_mode(), request.include_credentials(), transfer_lease, {}, cache_miss_notification, originating_page_id, request.network_isolation_key());
if (!protocol_request) {
log_failure(request, "Failed to initiate load"sv);
return nullptr;
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index 1e7ee374472..49a3d14bf65 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -821,12 +821,13 @@ public:
virtual void page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document&) { }
virtual void page_did_change_active_document_in_child_navigable(Web::DOM::Document&) { }
virtual void page_did_finish_loading(HTML::CrossProcessId, HTML::CrossProcessId) { }
- virtual Optional<u64> page_did_start_download(HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
+ virtual Optional<u64> page_did_start_download(HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
{
(void)navigable_id;
(void)navigation_id;
(void)suggested_filename;
(void)total_size;
+ (void)same_site_context;
(void)request_server_client_id;
(void)request_server_request_id;
(void)initial_data;
diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cpp
index 9935836549d..3bdbf813f85 100644
--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp
+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp
@@ -243,7 +243,7 @@ ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL const& url_rec
if (!request_client)
return Error::from_string_literal("RequestServer is currently unavailable");
- m_websocket = request_client->websocket_connect(connection_url, move(network_isolation_key), origin_string, protocol_byte_strings, {}, additional_headers);
+ m_websocket = request_client->websocket_connect(connection_url, move(network_isolation_key), origin_string, protocol_byte_strings, {}, additional_headers, { .status = request->same_site_status(), .is_safe_method = true });
m_websocket->on_open = GC::weak_callback(*this, [](auto& self) {
self.on_open();
diff --git a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp
index 26296ed4bbe..a60511900e0 100644
--- a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp
+++ b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp
@@ -129,6 +129,8 @@ void apply_navigation_population_result(NavigationPopulationRequest& request, Na
{
if (result.replacement_document_state.has_value())
request.history_entry.document_state = *result.replacement_document_state;
+ if (result.navigation_same_site_status.has_value())
+ request.history_entry.document_state.navigation_same_site_status = *result.navigation_same_site_status;
if (result.redirected_url.has_value()) {
auto redirected_url = *result.redirected_url;
auto fragment_directive = remove_the_fragment_directive(redirected_url);
@@ -245,6 +247,7 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::NavigationPopulationResult con
TRY(encoder.encode(result.classic_history_api_state));
TRY(encoder.encode(result.replacement_document_state));
TRY(encoder.encode(result.resource_cleared));
+ TRY(encoder.encode(result.navigation_same_site_status));
TRY(encoder.encode(result.inline_content_origin));
TRY(encoder.encode(result.document_id));
return {};
@@ -260,6 +263,7 @@ ErrorOr<Web::HTML::NavigationPopulationResult> decode(Decoder& decoder)
.classic_history_api_state = TRY(decoder.decode<Optional<Web::HTML::StorageSerializationRecord>>()),
.replacement_document_state = TRY(decoder.decode<Optional<Web::HTML::SessionHistoryDocumentStateDescriptor>>()),
.resource_cleared = TRY(decoder.decode<bool>()),
+ .navigation_same_site_status = TRY(decoder.decode<Optional<HTTP::Cookie::SameSiteStatus>>()),
.inline_content_origin = TRY(decoder.decode<Optional<URL::Origin>>()),
.document_id = TRY(decoder.decode<Optional<Web::HTML::CrossProcessId>>()),
};
diff --git a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h
index 6ecba7e7d01..b4adb6c84d5 100644
--- a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h
+++ b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h
@@ -69,6 +69,7 @@ struct NavigationPopulationResult {
Optional<StorageSerializationRecord> classic_history_api_state;
Optional<SessionHistoryDocumentStateDescriptor> replacement_document_state;
bool resource_cleared { false };
+ Optional<HTTP::Cookie::SameSiteStatus> navigation_same_site_status {};
// The origin the UI process gives a document created for inline content in place of the response.
Optional<URL::Origin> inline_content_origin {};
Optional<CrossProcessId> document_id {};
diff --git a/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.cpp b/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.cpp
index e7df3f90b02..8391e1b7717 100644
--- a/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.cpp
+++ b/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.cpp
@@ -84,6 +84,7 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::ReplicatedNavigableState const
TRY(encoder.encode(state.target_name));
TRY(encoder.encode(state.active_document_url));
TRY(encoder.encode(state.active_document_origin));
+ TRY(encoder.encode(state.active_document_sandboxing_flag_set));
TRY(encoder.encode(state.active_document_is_fully_active));
TRY(encoder.encode(state.top_level_creation_url));
TRY(encoder.encode(state.top_level_origin));
@@ -111,6 +112,7 @@ ErrorOr<Web::HTML::ReplicatedNavigableState> decode(Decoder& decoder)
.target_name = TRY(decoder.decode<Utf16String>()),
.active_document_url = TRY(decoder.decode<URL::URL>()),
.active_document_origin = TRY(decoder.decode<URL::Origin>()),
+ .active_document_sandboxing_flag_set = TRY(decoder.decode<Web::HTML::SandboxingFlagSet>()),
.active_document_is_fully_active = TRY(decoder.decode<bool>()),
.top_level_creation_url = TRY(decoder.decode<URL::URL>()),
.top_level_origin = TRY(decoder.decode<URL::Origin>()),
diff --git a/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h b/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h
index be24d9c6556..6de2aa6da27 100644
--- a/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h
+++ b/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h
@@ -81,6 +81,7 @@ struct ReplicatedNavigableState {
Utf16String target_name;
URL::URL active_document_url;
URL::Origin active_document_origin;
+ SandboxingFlagSet active_document_sandboxing_flag_set {};
bool active_document_is_fully_active { false };
URL::URL top_level_creation_url;
URL::Origin top_level_origin;
diff --git a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp
index 1411e7e8159..2db2fcbfa27 100644
--- a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp
+++ b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp
@@ -15,6 +15,7 @@ template<>
ErrorOr<void> encode(Encoder& encoder, Web::HTML::SerializedWindow const& window)
{
TRY(encoder.encode(window.associated_document.url));
+ TRY(encoder.encode(window.associated_document.site_for_cookies));
TRY(encoder.encode(window.associated_document.relevant_settings_object_is_secure_context));
TRY(encoder.encode(window.associated_document.relevant_settings_object_policy_container));
TRY(encoder.encode(window.navigable_is_top_level));
@@ -28,6 +29,7 @@ ErrorOr<Web::HTML::SerializedWindow> decode(Decoder& decoder)
return Web::HTML::SerializedWindow {
.associated_document {
.url = TRY(decoder.decode<URL::URL>()),
+ .site_for_cookies = TRY(decoder.decode<URL::Origin>()),
.relevant_settings_object_is_secure_context = TRY(decoder.decode<bool>()),
.relevant_settings_object_policy_container = TRY(decoder.decode<Web::HTML::SerializedPolicyContainer>()),
},
@@ -38,6 +40,7 @@ ErrorOr<Web::HTML::SerializedWindow> decode(Decoder& decoder)
template<>
ErrorOr<void> encode(Encoder& encoder, Web::HTML::SerializedWorkerGlobalScope const& worker_global_scope)
{
+ TRY(encoder.encode(worker_global_scope.site_for_cookies));
TRY(encoder.encode(worker_global_scope.relevant_settings_object_is_secure_context));
TRY(encoder.encode(worker_global_scope.relevant_settings_object_policy_container));
TRY(encoder.encode(worker_global_scope.is_supported_animation_frame_provider));
@@ -48,6 +51,7 @@ template<>
ErrorOr<Web::HTML::SerializedWorkerGlobalScope> decode(Decoder& decoder)
{
return Web::HTML::SerializedWorkerGlobalScope {
+ .site_for_cookies = TRY(decoder.decode<URL::Origin>()),
.relevant_settings_object_is_secure_context = TRY(decoder.decode<bool>()),
.relevant_settings_object_policy_container = TRY(decoder.decode<Web::HTML::SerializedPolicyContainer>()),
.is_supported_animation_frame_provider = TRY(decoder.decode<bool>()),
diff --git a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h
index 7e1356dc7d1..485e033015e 100644
--- a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h
+++ b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h
@@ -26,6 +26,7 @@ enum class CanUseCrossOriginIsolatedAPIs : u8 {
struct SerializedDocument {
URL::URL url;
+ URL::Origin site_for_cookies { URL::Origin::create_opaque() };
bool relevant_settings_object_is_secure_context { false };
SerializedPolicyContainer relevant_settings_object_policy_container;
};
@@ -38,6 +39,7 @@ struct SerializedWindow {
};
struct SerializedWorkerGlobalScope {
+ URL::Origin site_for_cookies { URL::Origin::create_opaque() };
bool relevant_settings_object_is_secure_context { false };
SerializedPolicyContainer relevant_settings_object_policy_container;
diff --git a/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.cpp b/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.cpp
index ef493244ec6..9d6f68a891f 100644
--- a/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.cpp
+++ b/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.cpp
@@ -217,6 +217,7 @@ ErrorOr<void> IPC::encode(Encoder& encoder, Web::HTML::SessionHistoryDocumentSta
TRY(encoder.encode(document_state.origin));
TRY(encoder.encode(document_state.about_base_url));
TRY(encoder.encode(document_state.resource));
+ TRY(encoder.encode(document_state.navigation_same_site_status));
TRY(encoder.encode(document_state.reload_pending));
TRY(encoder.encode(document_state.reload_bypasses_cache));
TRY(encoder.encode(document_state.ever_populated));
@@ -236,6 +237,7 @@ ErrorOr<Web::HTML::SessionHistoryDocumentStateDescriptor> IPC::decode(Decoder& d
auto origin = TRY(decoder.decode<Optional<URL::Origin>>());
auto about_base_url = TRY(decoder.decode<Optional<URL::URL>>());
auto resource = TRY(decoder.decode<Web::HTML::DocumentResource>());
+ auto navigation_same_site_status = TRY(decoder.decode<HTTP::Cookie::SameSiteStatus>());
auto reload_pending = TRY(decoder.decode<bool>());
auto reload_bypasses_cache = TRY(decoder.decode<bool>());
auto ever_populated = TRY(decoder.decode<bool>());
@@ -251,6 +253,7 @@ ErrorOr<Web::HTML::SessionHistoryDocumentStateDescriptor> IPC::decode(Decoder& d
.origin = move(origin),
.about_base_url = move(about_base_url),
.resource = move(resource),
+ .navigation_same_site_status = navigation_same_site_status,
.reload_pending = reload_pending,
.reload_bypasses_cache = reload_bypasses_cache,
.ever_populated = ever_populated,
diff --git a/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.h b/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.h
index 418a2eff872..58caa6e3cd4 100644
--- a/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.h
+++ b/Libraries/LibWebCommon/HTML/SessionHistoryEntryDescriptor.h
@@ -10,6 +10,7 @@
#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <AK/Vector.h>
+#include <LibHTTP/Cookie/Cookie.h>
#include <LibIPC/Forward.h>
#include <LibURL/URL.h>
#include <LibWebCommon/Export.h>
@@ -55,6 +56,7 @@ struct SessionHistoryDocumentStateDescriptor {
Optional<URL::Origin> origin;
Optional<URL::URL> about_base_url;
DocumentResource resource;
+ HTTP::Cookie::SameSiteStatus navigation_same_site_status { HTTP::Cookie::SameSiteStatus::CrossSite };
bool reload_pending { false };
// AD-HOC: Whether the pending reload bypasses the HTTP cache.
bool reload_bypasses_cache { false };
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index 653760eabcc..b21ae928453 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -973,7 +973,7 @@ void Application::start_next_content_blocker_list_update()
return;
}
m_content_blocker_list_update_request = client.value()->start_request(
- "GET"sv, update.url, *request_headers, {}, HTTP::CacheMode::NoStore,
+ "GET"sv, update.url, {}, *request_headers, {}, HTTP::CacheMode::NoStore,
HTTP::Cookie::IncludeCredentials::No);
if (!m_content_blocker_list_update_request) {
warnln("Unable to start update request for {}", update.name);
@@ -2165,21 +2165,21 @@ ErrorOr<void> Application::launch_request_server()
void Application::configure_request_server_control_client(Requests::RequestControlClient& control_client)
{
- control_client.on_store_response_cookies_and_hsts_policy = [](int client_id, URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const& partition_context, Vector<HTTP::Cookie::ParsedCookie> const& cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> const& hsts_policy) {
+ control_client.on_store_response_cookies_and_hsts_policy = [](int client_id, URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const& partition_context, HTTP::Cookie::SameSiteContext same_site_context, Vector<HTTP::Cookie::ParsedCookie> const& cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> const& hsts_policy) {
auto session = the().session_for_request_server_client(client_id);
if (!session)
return;
if (the().request_server_client_may_use_cookies_in(client_id, url, partition_context)) {
for (auto const& cookie : cookies)
- session->cookie_jar->set_cookie(url, cookie, HTTP::Cookie::Source::Http, partition_context);
+ session->cookie_jar->set_cookie(url, cookie, HTTP::Cookie::Source::Http, partition_context, same_site_context);
}
if (hsts_policy.has_value() && url.host().has_value() && url.host()->is_domain())
session->hsts_store->store_policy(url.host()->get<String>(), *hsts_policy);
};
- control_client.on_retrieve_http_cookie = [](int client_id, URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const& partition_context) -> String {
+ control_client.on_retrieve_http_cookie = [](int client_id, URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const& partition_context, HTTP::Cookie::SameSiteContext same_site_context) -> String {
auto session = the().session_for_request_server_client(client_id);
if (!session)
return {};
@@ -2187,9 +2187,9 @@ void Application::configure_request_server_control_client(Requests::RequestContr
return {};
auto& cookie_jar = *session->cookie_jar;
if constexpr (!REQUESTSERVER_WIRE_DEBUG)
- return cookie_jar.get_cookie(url, HTTP::Cookie::Source::Http, partition_context);
+ return cookie_jar.get_cookie(url, HTTP::Cookie::Source::Http, partition_context, same_site_context);
auto started_at = MonotonicTime::now();
- auto cookie = cookie_jar.get_cookie(url, HTTP::Cookie::Source::Http, partition_context);
+ auto cookie = cookie_jar.get_cookie(url, HTTP::Cookie::Source::Http, partition_context, same_site_context);
auto elapsed_ms = (MonotonicTime::now() - started_at).to_milliseconds();
if (elapsed_ms > 5) {
dbgln("UI wire-cookie: get_cookie({}) took {} ms ({} bytes returned)",
diff --git a/Libraries/LibWebView/Autocomplete.cpp b/Libraries/LibWebView/Autocomplete.cpp
index 776ff6ef253..06e41a1374c 100644
--- a/Libraries/LibWebView/Autocomplete.cpp
+++ b/Libraries/LibWebView/Autocomplete.cpp
@@ -381,7 +381,7 @@ void Autocomplete::start_remote_query(AutocompleteQueryID query_id, SearchEngine
deliver_current_result();
return;
}
- m_request = client.value()->start_request("GET"sv, *url);
+ m_request = client.value()->start_request("GET"sv, *url, HTTP::Cookie::SameSiteContext::same_site());
m_request->set_buffered_request_finished_callback(
[this, query_id, engine, query = move(query)](u64, Requests::RequestTimingInfo const&, Optional<Requests::NetworkError> const& network_error, HTTP::HeaderList const& response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Requests::CacheState, Core::ImmutableBytes payload) {
diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cpp
index 0dff9d5e02f..30401cb365f 100644
--- a/Libraries/LibWebView/CanonicalNavigable.cpp
+++ b/Libraries/LibWebView/CanonicalNavigable.cpp
@@ -1398,6 +1398,7 @@ Optional<Web::HTML::ReplicatedNavigableState> CanonicalNavigable::replicated_sta
.target_name = target_name(),
.active_document_url = active_document_url(),
.active_document_origin = active_document().origin(),
+ .active_document_sandboxing_flag_set = active_document().active_sandboxing_flag_set(),
.active_document_is_fully_active = hosted_state.active_document_is_fully_active,
.top_level_creation_url = active_document().relevant_global_object().relevant_settings_object().top_level_creation_url().value(),
.top_level_origin = traversable.active_document().origin(),
diff --git a/Libraries/LibWebView/CanonicalSessionHistoryEntry.cpp b/Libraries/LibWebView/CanonicalSessionHistoryEntry.cpp
index 6e4fe636cd3..3333c643a2f 100644
--- a/Libraries/LibWebView/CanonicalSessionHistoryEntry.cpp
+++ b/Libraries/LibWebView/CanonicalSessionHistoryEntry.cpp
@@ -65,6 +65,7 @@ Web::HTML::SessionHistoryDocumentStateDescriptor CanonicalDocumentState::descrip
.origin = origin,
.about_base_url = about_base_url,
.resource = resource,
+ .navigation_same_site_status = navigation_same_site_status,
.reload_pending = reload_pending,
.reload_bypasses_cache = reload_bypasses_cache,
.ever_populated = ever_populated,
@@ -94,6 +95,7 @@ static NonnullRefPtr<CanonicalDocumentState> document_state_from_descriptor(Web:
}
document_state->about_base_url = descriptor.about_base_url;
document_state->resource = descriptor.resource;
+ document_state->navigation_same_site_status = descriptor.navigation_same_site_status;
document_state->reload_pending = descriptor.reload_pending;
document_state->reload_bypasses_cache = descriptor.reload_bypasses_cache;
document_state->ever_populated = descriptor.ever_populated;
diff --git a/Libraries/LibWebView/CanonicalSessionHistoryEntry.h b/Libraries/LibWebView/CanonicalSessionHistoryEntry.h
index 066a48b0b12..ad1322464fd 100644
--- a/Libraries/LibWebView/CanonicalSessionHistoryEntry.h
+++ b/Libraries/LibWebView/CanonicalSessionHistoryEntry.h
@@ -67,6 +67,7 @@ public:
Optional<URL::Origin> origin;
Optional<URL::URL> about_base_url;
Web::HTML::DocumentResource resource;
+ HTTP::Cookie::SameSiteStatus navigation_same_site_status { HTTP::Cookie::SameSiteStatus::CrossSite };
bool reload_pending { false };
bool reload_bypasses_cache { false };
bool ever_populated { false };
diff --git a/Libraries/LibWebView/CookieJar.cpp b/Libraries/LibWebView/CookieJar.cpp
index c676ffc7283..53330a63fb3 100644
--- a/Libraries/LibWebView/CookieJar.cpp
+++ b/Libraries/LibWebView/CookieJar.cpp
@@ -190,11 +190,11 @@ CookieJar::~CookieJar()
}
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.8.3
-String CookieJar::get_cookie(URL::URL const& url, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const& context)
+String CookieJar::get_cookie(URL::URL const& url, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const& context, HTTP::Cookie::SameSiteContext same_site_context)
{
m_transient_storage.purge_expired_cookies();
- auto cookie_list = get_matching_cookies(url, source, partition_key_for(url, context));
+ auto cookie_list = get_matching_cookies(url, source, partition_key_for(url, context), same_site_context);
// 6. Serialize the cookie-list into a cookie-string by processing each cookie in the cookie-list in order:
StringBuilder builder;
@@ -218,7 +218,7 @@ String CookieJar::get_cookie(URL::URL const& url, HTTP::Cookie::Source source, O
}
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.7
-void CookieJar::set_cookie(URL::URL const& url, HTTP::Cookie::ParsedCookie const& parsed_cookie, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const& context)
+void CookieJar::set_cookie(URL::URL const& url, HTTP::Cookie::ParsedCookie const& parsed_cookie, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const& context, HTTP::Cookie::SameSiteContext same_site_context)
{
// 1. A user agent MAY ignore a received cookie in its entirety. See Section 5.3.
@@ -411,18 +411,26 @@ void CookieJar::set_cookie(URL::URL const& url, HTTP::Cookie::ParsedCookie const
// 18. If the cookie's same-site-flag is not "None":
if (cookie.same_site != HTTP::Cookie::SameSite::None) {
- // FIXME: 1. If the cookie was received from a "non-HTTP" API, and the API was called from a navigable's active document
- // whose "site for cookies" is not same-site with the top-level origin, then abort this algorithm and ignore
- // the newly created cookie entirely.
+ // 1. If the cookie was received from a "non-HTTP" API, and the API was called from a navigable's active
+ // document whose "site for cookies" is not same-site with the top-level origin, then abort this algorithm
+ // and ignore the newly created cookie entirely.
+ if (source == HTTP::Cookie::Source::NonHttp && same_site_context.status == HTTP::Cookie::SameSiteStatus::CrossSite)
+ return;
+
+ // 2. If the cookie was received from a "same-site" request (as defined in Section 5.2), skip the remaining
+ // substeps and continue processing the cookie.
+ // AD-HOC: A same-site non-HTTP write also continues here.
- // FIXME: 2. If the cookie was received from a "same-site" request (as defined in Section 5.2), skip the remaining
- // substeps and continue processing the cookie.
+ // 3. If the cookie was received from a request which is navigating a top-level traversable [HTML] (e.g. if
+ // the request's "reserved client" is either null or an environment whose "target browsing context"'s
+ // navigable is a top-level traversable), skip the remaining substeps and continue processing the cookie.
- // FIXME: 3. If the cookie was received from a request which is navigating a top-level traversable [HTML] (e.g. if the
- // request's "reserved client" is either null or an environment whose "target browsing context"'s navigable
- // is a top-level traversable), skip the remaining substeps and continue processing the cookie.
+ // Note: Top-level navigations can create a cookie with any SameSite value, even if the new cookie wouldn't
+ // have been sent along with the request had it already existed prior to the navigation.
- // FIXME: 4. Abort this algorithm and ignore the newly created cookie entirely.
+ // 4. Abort this algorithm and ignore the newly created cookie entirely.
+ if (same_site_context.status == HTTP::Cookie::SameSiteStatus::CrossSite && !same_site_context.is_top_level_navigation)
+ return;
}
// 19. If the cookie's "same-site-flag" is "None", abort this algorithm and ignore the cookie entirely unless the
@@ -535,9 +543,9 @@ ErrorOr<void> CookieJar::set_cookie_from_devtools(URL::URL const& url, Optional<
auto parsed_cookie = TRY(HTTP::Cookie::parse_cookie(cookie));
// NB: DevTools edits a cookie in its own partition.
if (cookie.partition_key.is_empty())
- set_cookie(url, parsed_cookie, HTTP::Cookie::Source::Http, {});
+ set_cookie(url, parsed_cookie, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
else
- set_cookie(url, parsed_cookie, HTTP::Cookie::Source::Http, HTTP::Cookie::PartitionContext { cookie.partition_key, true });
+ set_cookie(url, parsed_cookie, HTTP::Cookie::Source::Http, HTTP::Cookie::PartitionContext { cookie.partition_key, true }, HTTP::Cookie::SameSiteContext::same_site());
if (old_key.has_value() && *old_key != new_key)
delete_cookie(*old_key);
@@ -602,17 +610,17 @@ Vector<HTTP::Cookie::Cookie> CookieJar::get_all_cookies_webdriver(URL::URL const
{
// NB: WebDriver drives top-level documents, which use first-party cookies. Tests may look at cookies from the
// context of another top-level site.
- return get_matching_cookies(url, HTTP::Cookie::Source::Http, partition_key_for(url, context), MatchingCookiesSpecMode::WebDriver);
+ return get_matching_cookies(url, HTTP::Cookie::Source::Http, partition_key_for(url, context), HTTP::Cookie::SameSiteContext::same_site(), MatchingCookiesSpecMode::WebDriver);
}
-Vector<HTTP::Cookie::Cookie> CookieJar::get_all_cookies_cookiestore(URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const& context)
+Vector<HTTP::Cookie::Cookie> CookieJar::get_all_cookies_cookiestore(URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const& context, HTTP::Cookie::SameSiteContext same_site_context)
{
- return get_matching_cookies(url, HTTP::Cookie::Source::NonHttp, partition_key_for(url, context), MatchingCookiesSpecMode::RFC6265);
+ return get_matching_cookies(url, HTTP::Cookie::Source::NonHttp, partition_key_for(url, context), same_site_context);
}
Optional<HTTP::Cookie::Cookie> CookieJar::get_named_cookie(URL::URL const& url, StringView name)
{
- auto cookie_list = get_matching_cookies(url, HTTP::Cookie::Source::Http, {}, MatchingCookiesSpecMode::WebDriver);
+ auto cookie_list = get_matching_cookies(url, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site(), MatchingCookiesSpecMode::WebDriver);
for (auto const& cookie : cookie_list) {
if (cookie.name == name)
@@ -646,7 +654,7 @@ Requests::CacheSizes CookieJar::estimate_storage_size_accessed_since(UnixDateTim
}
// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.8.3
-Vector<HTTP::Cookie::Cookie> CookieJar::get_matching_cookies(URL::URL const& url, HTTP::Cookie::Source source, Utf16String const& partition_key, MatchingCookiesSpecMode mode)
+Vector<HTTP::Cookie::Cookie> CookieJar::get_matching_cookies(URL::URL const& url, HTTP::Cookie::Source source, Utf16String const& partition_key, HTTP::Cookie::SameSiteContext same_site_context, MatchingCookiesSpecMode mode)
{
auto now = UnixDateTime::now();
@@ -663,7 +671,7 @@ Vector<HTTP::Cookie::Cookie> CookieJar::get_matching_cookies(URL::URL const& url
m_transient_storage.for_each_cookie([&](HTTP::Cookie::Cookie& cookie) {
if (cookie.partition_key != partition_key)
return;
- if (!HTTP::Cookie::cookie_matches_url(cookie, url, *retrieval_host_canonical, source))
+ if (!HTTP::Cookie::cookie_matches_url(cookie, url, *retrieval_host_canonical, source, same_site_context))
return;
// NOTE: The WebDriver spec expects only step 1 above to be executed to match cookies.
@@ -820,7 +828,7 @@ void CookieJar::TransientStorage::send_cookie_changed_notifications(ReadonlySpan
// NB: Changes go to the view's top-level document, a first-party context for its URL, which never sees the
// cookies set in third-party contexts.
- if (cookie.value.partition_key.is_empty() && HTTP::Cookie::cookie_matches_url(cookie.value, view.url(), *retrieval_host_canonical))
+ if (cookie.value.partition_key.is_empty() && HTTP::Cookie::cookie_matches_url(cookie.value, view.url(), *retrieval_host_canonical, HTTP::Cookie::Source::NonHttp, HTTP::Cookie::SameSiteContext::same_site()))
page_cookies.append(cookie.value);
if (cookie.value.host_only) {
diff --git a/Libraries/LibWebView/CookieJar.h b/Libraries/LibWebView/CookieJar.h
index a988d0612bb..ec855988361 100644
--- a/Libraries/LibWebView/CookieJar.h
+++ b/Libraries/LibWebView/CookieJar.h
@@ -46,15 +46,15 @@ public:
// A context of nothing stands for a first-party context, as for the UI process's own requests. A third-party context
// only uses the cookies set in a third-party context under the same top-level site. See HTTP::Cookie::PartitionContext.
- String get_cookie(URL::URL const& url, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const&);
- void set_cookie(URL::URL const& url, HTTP::Cookie::ParsedCookie const& parsed_cookie, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const&);
+ String get_cookie(URL::URL const& url, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const&, HTTP::Cookie::SameSiteContext);
+ void set_cookie(URL::URL const& url, HTTP::Cookie::ParsedCookie const& parsed_cookie, HTTP::Cookie::Source source, Optional<HTTP::Cookie::PartitionContext> const&, HTTP::Cookie::SameSiteContext);
void update_cookie(HTTP::Cookie::Cookie);
ErrorOr<void> set_cookie_from_devtools(URL::URL const&, Optional<CookieStorageKey> old_key, HTTP::Cookie::Cookie);
bool delete_cookie(CookieStorageKey const&);
void dump_cookies();
Vector<HTTP::Cookie::Cookie> get_all_cookies();
Vector<HTTP::Cookie::Cookie> get_all_cookies_webdriver(URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const& = {});
- Vector<HTTP::Cookie::Cookie> get_all_cookies_cookiestore(URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const&);
+ Vector<HTTP::Cookie::Cookie> get_all_cookies_cookiestore(URL::URL const& url, Optional<HTTP::Cookie::PartitionContext> const&, HTTP::Cookie::SameSiteContext);
Optional<HTTP::Cookie::Cookie> get_named_cookie(URL::URL const& url, StringView name);
void expire_cookies_with_time_offset(AK::Duration);
void delete_all_cookies(URL::URL const&);
@@ -131,7 +131,7 @@ private:
WebDriver,
};
- Vector<HTTP::Cookie::Cookie> get_matching_cookies(URL::URL const& url, HTTP::Cookie::Source source, Utf16String const& partition_key, MatchingCookiesSpecMode mode = MatchingCookiesSpecMode::RFC6265);
+ Vector<HTTP::Cookie::Cookie> get_matching_cookies(URL::URL const& url, HTTP::Cookie::Source source, Utf16String const& partition_key, HTTP::Cookie::SameSiteContext, MatchingCookiesSpecMode mode = MatchingCookiesSpecMode::RFC6265);
Optional<PersistedStorage> m_persisted_storage;
TransientStorage m_transient_storage;
diff --git a/Libraries/LibWebView/DownloadStore.cpp b/Libraries/LibWebView/DownloadStore.cpp
index 210b88a0de3..accbe0d9213 100644
--- a/Libraries/LibWebView/DownloadStore.cpp
+++ b/Libraries/LibWebView/DownloadStore.cpp
@@ -16,6 +16,7 @@ namespace WebView {
static constexpr u32 DOWNLOAD_SCHEMA_BASELINE_VERSION = 1u;
static constexpr u32 DOWNLOAD_SCHEMA_RESTARTABILITY_VERSION = 2u;
static constexpr u32 DOWNLOAD_SCHEMA_REPLACEMENT_VERSION = 3u;
+static constexpr u32 DOWNLOAD_SCHEMA_SAME_SITE_CONTEXT_VERSION = 4u;
static String serialize_segments(Vector<DownloadSegmentRecord> const& segments)
{
@@ -103,6 +104,14 @@ ErrorOr<Database::MigrationOutcome> DownloadStore::migrate_schema(Database::Data
ALTER TABLE Downloads ADD COLUMN may_replace_destination INTEGER NOT NULL DEFAULT 0;
)#"sv,
},
+ {
+ .version = DOWNLOAD_SCHEMA_SAME_SITE_CONTEXT_VERSION,
+ .sql = R"#(
+ ALTER TABLE Downloads ADD COLUMN same_site INTEGER NOT NULL DEFAULT 1;
+ ALTER TABLE Downloads ADD COLUMN top_level_navigation INTEGER NOT NULL DEFAULT 0;
+ ALTER TABLE Downloads ADD COLUMN safe_method INTEGER NOT NULL DEFAULT 0;
+ )#"sv,
+ },
});
return database.migrate("Downloads"sv, migrations, mode);
@@ -125,10 +134,13 @@ ErrorOr<NonnullOwnPtr<DownloadStore>> DownloadStore::create(Database::Database&
segments,
can_restart_from_zero,
may_replace_destination,
+ same_site,
+ top_level_navigation,
+ safe_method,
created_time,
updated_time
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
url = excluded.url,
display_url = excluded.display_url,
@@ -140,6 +152,9 @@ ErrorOr<NonnullOwnPtr<DownloadStore>> DownloadStore::create(Database::Database&
segments = excluded.segments,
can_restart_from_zero = excluded.can_restart_from_zero,
may_replace_destination = excluded.may_replace_destination,
+ same_site = excluded.same_site,
+ top_level_navigation = excluded.top_level_navigation,
+ safe_method = excluded.safe_method,
updated_time = excluded.updated_time;
)#"sv));
@@ -149,7 +164,7 @@ ErrorOr<NonnullOwnPtr<DownloadStore>> DownloadStore::create(Database::Database&
)#"sv));
statements.list_downloads = TRY(database.prepare_statement(R"#(
- SELECT id, url, display_url, destination, temporary_destination, total_size, etag, last_modified, segments, can_restart_from_zero, created_time, may_replace_destination
+ SELECT id, url, display_url, destination, temporary_destination, total_size, etag, last_modified, segments, can_restart_from_zero, created_time, may_replace_destination, same_site, top_level_navigation, safe_method
FROM Downloads
ORDER BY id ASC;
)#"sv));
@@ -196,6 +211,9 @@ void DownloadStore::save_download(DownloadRecord const& download, UnixDateTime u
serialize_segments(download.segments),
download.can_restart_from_zero,
download.may_replace_destination,
+ download.same_site_context.status == HTTP::Cookie::SameSiteStatus::SameSite,
+ download.same_site_context.is_top_level_navigation,
+ download.same_site_context.is_safe_method,
download.created_time,
updated_at);
}
@@ -243,6 +261,11 @@ Vector<DownloadRecord> DownloadStore::resumable_downloads()
.created_time = m_database->result_column<UnixDateTime>(statement_id, 10),
.can_restart_from_zero = m_database->result_column<bool>(statement_id, 9),
.may_replace_destination = m_database->result_column<bool>(statement_id, 11),
+ .same_site_context = {
+ .status = m_database->result_column<bool>(statement_id, 12) ? HTTP::Cookie::SameSiteStatus::SameSite : HTTP::Cookie::SameSiteStatus::CrossSite,
+ .is_top_level_navigation = m_database->result_column<bool>(statement_id, 13),
+ .is_safe_method = m_database->result_column<bool>(statement_id, 14),
+ },
});
return {};
diff --git a/Libraries/LibWebView/DownloadStore.h b/Libraries/LibWebView/DownloadStore.h
index b698742ea40..070ff7cdadd 100644
--- a/Libraries/LibWebView/DownloadStore.h
+++ b/Libraries/LibWebView/DownloadStore.h
@@ -13,6 +13,7 @@
#include <AK/Time.h>
#include <AK/Vector.h>
#include <LibDatabase/Forward.h>
+#include <LibHTTP/Cookie/Cookie.h>
#include <LibWebView/Export.h>
namespace WebView {
@@ -40,6 +41,7 @@ struct WEBVIEW_API DownloadRecord {
bool can_restart_from_zero { false };
// Whether the user chose to replace a file at the destination.
bool may_replace_destination { false };
+ HTTP::Cookie::SameSiteContext same_site_context { HTTP::Cookie::SameSiteContext::same_site() };
};
class WEBVIEW_API DownloadStore {
diff --git a/Libraries/LibWebView/FileDownloader.cpp b/Libraries/LibWebView/FileDownloader.cpp
index 99ce1923184..4d90f8b46d8 100644
--- a/Libraries/LibWebView/FileDownloader.cpp
+++ b/Libraries/LibWebView/FileDownloader.cpp
@@ -132,6 +132,8 @@ struct FileDownloader::ActiveDownload {
u32 redirect_count { 0 };
bool can_issue_own_requests { false };
bool can_restart_from_zero { false };
+ // The context of the request that started the download, so later requests send the same cookies.
+ HTTP::Cookie::SameSiteContext same_site_context { HTTP::Cookie::SameSiteContext::same_site() };
DownloadRangeSupport range_support;
bool segmentation_abandoned { false };
bool restored_from_disk { false };
@@ -246,7 +248,7 @@ void FileDownloader::start_download_request(u64 download_id, URL::URL const& url
fail_download(download_id, MUST(String::formatted("Unable to launch RequestServer: {}", client.error())));
return;
}
- auto request = client.value()->start_request("GET"sv, url, *request_headers, {}, HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::No, 0u);
+ auto request = client.value()->start_request("GET"sv, url, active->same_site_context, *request_headers, {}, HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::No, 0u);
if (!request) {
fail_download(download_id, "Unable to start request to download file"_string);
return;
@@ -285,7 +287,7 @@ void FileDownloader::follow_download_redirect(u64 download_id, HTTP::HeaderList
start_download_request(download_id, redirect_url.release_value());
}
-u64 FileDownloader::adopt_download(IsPrivate is_private, URL::URL const& url, LexicalPath destination, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data,
+u64 FileDownloader::adopt_download(IsPrivate is_private, URL::URL const& url, LexicalPath destination, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data,
ResponseFinished on_response_finished)
{
ScopeGuard report_failure = [&] {
@@ -300,6 +302,7 @@ u64 FileDownloader::adopt_download(IsPrivate is_private, URL::URL const& url, Le
active->effective_url = url;
active->can_issue_own_requests = true;
+ active->same_site_context = same_site_context;
if (!initial_data.is_empty()) {
append_download_data(download_id, initial_data);
@@ -634,7 +637,7 @@ void FileDownloader::start_segment_request(u64 download_id, size_t segment_index
fail_download(download_id, MUST(String::formatted("Unable to launch RequestServer: {}", client.error())));
return;
}
- auto request = client.value()->start_request("GET"sv, active->effective_url, *request_headers, {}, HTTP::CacheMode::NoStore, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::No, static_cast<u32>(segment_index));
+ auto request = client.value()->start_request("GET"sv, active->effective_url, active->same_site_context, *request_headers, {}, HTTP::CacheMode::NoStore, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::No, static_cast<u32>(segment_index));
if (!request) {
fail_download(download_id, "Unable to start request to download file"_string);
return;
@@ -1372,6 +1375,7 @@ void FileDownloader::persist_download_snapshot(u64 id, PersistUrgency urgency)
.created_time = active->created_time,
.can_restart_from_zero = active->can_restart_from_zero,
.may_replace_destination = active->may_replace_destination,
+ .same_site_context = active->same_site_context,
};
record.segments.ensure_capacity(active->segments.size());
@@ -1470,6 +1474,7 @@ bool FileDownloader::restore_persisted_download(DownloadRecord& record)
active->can_issue_own_requests = true;
active->can_restart_from_zero = record.can_restart_from_zero;
active->may_replace_destination = record.may_replace_destination;
+ active->same_site_context = record.same_site_context;
active->created_time = record.created_time;
active->restored_from_disk = true;
active->range_support.supports_ranges = true;
diff --git a/Libraries/LibWebView/FileDownloader.h b/Libraries/LibWebView/FileDownloader.h
index 88e7ac77df2..03e053a7506 100644
--- a/Libraries/LibWebView/FileDownloader.h
+++ b/Libraries/LibWebView/FileDownloader.h
@@ -19,6 +19,7 @@
#include <AK/Time.h>
#include <AK/WeakPtr.h>
#include <AK/Weakable.h>
+#include <LibHTTP/Cookie/Cookie.h>
#include <LibHTTP/Forward.h>
#include <LibRequests/CacheState.h>
#include <LibRequests/Forward.h>
@@ -91,7 +92,7 @@ public:
u64 download_file(IsPrivate, URL::URL const&, LexicalPath, MayReplaceDestination = MayReplaceDestination::No);
using ResponseFinished = Function<void(u64 decoded_body_size, Requests::RequestTimingInfo const*,
Optional<StringView> error)>;
- u64 adopt_download(IsPrivate, URL::URL const&, LexicalPath, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data = {}, ResponseFinished = {});
+ u64 adopt_download(IsPrivate, URL::URL const&, LexicalPath, Optional<u64> total_size, HTTP::Cookie::SameSiteContext, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data = {}, ResponseFinished = {});
u64 start_download(IsPrivate, URL::URL const&, LexicalPath, Optional<u64> total_size = {}, MayReplaceDestination = MayReplaceDestination::No);
bool has_active_downloads() const;
bool has_unresumable_downloads() const;
diff --git a/Libraries/LibWebView/ReportSubmission.cpp b/Libraries/LibWebView/ReportSubmission.cpp
index 7fedc56c430..da26777c255 100644
--- a/Libraries/LibWebView/ReportSubmission.cpp
+++ b/Libraries/LibWebView/ReportSubmission.cpp
@@ -378,7 +378,7 @@ void ReportSubmission::post(StringView path, StringView activity, StringView con
fail("Could not start the report request."_string, ShouldRetry::Yes);
return;
}
- m_request = request_client.value()->start_request("POST"sv, *url, *headers, body.bytes(),
+ m_request = request_client.value()->start_request("POST"sv, *url, {}, *headers, body.bytes(),
HTTP::CacheMode::NoStore, HTTP::Cookie::IncludeCredentials::No);
if (!m_request) {
fail("Could not connect to the report server."_string, ShouldRetry::Yes);
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 2dfab976fdc..8cc634c84f2 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -735,7 +735,7 @@ Messages::WebContentClient::DidRequestCookieResponse WebContentClient::did_reque
return HTTP::Cookie::VersionedCookie {};
HTTP::Cookie::VersionedCookie cookie;
- cookie.cookie = m_session->cookie_jar->get_cookie(url, source, {});
+ cookie.cookie = m_session->cookie_jar->get_cookie(url, source, {}, HTTP::Cookie::SameSiteContext::same_site());
return cookie;
}
@@ -820,10 +820,10 @@ Messages::WebContentClient::DidStartDownloadWithoutRequestResponse WebContentCli
return Optional<u64> {};
}
-Messages::WebContentClient::DidStartDownloadResponse WebContentClient::did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
+Messages::WebContentClient::DidStartDownloadResponse WebContentClient::did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
{
if (auto* page = this->page(page_id))
- return page->did_start_download(navigable_id, move(navigation_id), move(url), move(suggested_filename), total_size, request_server_client_id, request_server_request_id, move(initial_data), move(network_response));
+ return page->did_start_download(navigable_id, move(navigation_id), move(url), move(suggested_filename), total_size, same_site_context, request_server_client_id, request_server_request_id, move(initial_data), move(network_response));
return Optional<u64> {};
}
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index df0579baf6b..b3951e52e92 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -235,7 +235,7 @@ private:
virtual void storage_area_write_refused(Web::StorageAPI::StorageAreaId, Vector<StorageItem>) override;
virtual void storage_area_reset(Web::StorageAPI::StorageAreaId, Vector<StorageItem>) override;
virtual Messages::WebContentClient::DidStartDownloadWithoutRequestResponse did_start_download_without_request(Web::PageId page_id, URL::URL, ByteString suggested_filename, Optional<u64> total_size) override;
- virtual Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;
+ virtual Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL, ByteString suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;
virtual Messages::WebContentClient::DidRequestNewWebViewResponse did_request_new_web_view(Web::PageId page_id, Web::HTML::ActivateTab, Web::HTML::WebViewHints, Web::HTML::CrossProcessId current_navigable_id, Utf16String name, bool no_opener, Optional<URL::URL> current_document_base_url) override;
virtual Messages::WebContentClient::StartWorkerAgentResponse start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) override;
virtual void register_dedicated_worker(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport) override;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 47ce16ead8c..5decf361a95 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -2806,7 +2806,7 @@ Messages::WebContentClient::DidStartDownloadWithoutRequestResponse WebContentPag
return { download_id };
}
-Messages::WebContentClient::DidStartDownloadResponse WebContentPage::did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
+Messages::WebContentClient::DidStartDownloadResponse WebContentPage::did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
{
// A download taking over an in-flight population's response body ends that navigation without a document;
// the reporting process ends its side when its population output says the download was handled. The body
@@ -2858,7 +2858,7 @@ Messages::WebContentClient::DidStartDownloadResponse WebContentPage::did_start_d
}
auto& file_downloader = Application::the().file_downloader();
- auto download_id = file_downloader.adopt_download(client().is_private(), url, destination.release_value(), total_size, request_server_client_id, request_server_request_id, initial_data.bytes(),
+ auto download_id = file_downloader.adopt_download(client().is_private(), url, destination.release_value(), total_size, same_site_context, request_server_client_id, request_server_request_id, initial_data.bytes(),
move(on_response_finished));
if (!is_download_in_progress(file_downloader, download_id))
return { Optional<u64> {} };
@@ -3653,7 +3653,7 @@ void WebContentPage::did_set_cookie(Optional<Web::HTML::EnvironmentId> environme
client().did_misbehave("did_set_cookie"sv, "HTTP cookie source"sv);
return;
}
- client().session().cookie_jar->set_cookie(url, cookie, source, {});
+ client().session().cookie_jar->set_cookie(url, cookie, source, {}, HTTP::Cookie::SameSiteContext::same_site());
return;
}
@@ -3661,7 +3661,7 @@ void WebContentPage::did_set_cookie(Optional<Web::HTML::EnvironmentId> environme
if (!partition_context.has_value())
return;
- client().session().cookie_jar->set_cookie(url, cookie, source, partition_context);
+ client().session().cookie_jar->set_cookie(url, cookie, source, partition_context, HTTP::Cookie::non_http_same_site_context(*partition_context));
}
Messages::WebContentClient::DidRequestAllCookiesCookiestoreResponse WebContentPage::did_request_all_cookies_cookiestore(Web::HTML::EnvironmentId const& environment_id, URL::URL url)
@@ -3670,21 +3670,23 @@ Messages::WebContentClient::DidRequestAllCookiesCookiestoreResponse WebContentPa
if (!partition_context.has_value())
return Vector<HTTP::Cookie::Cookie> {};
- return client().session().cookie_jar->get_all_cookies_cookiestore(url, partition_context);
+ return client().session().cookie_jar->get_all_cookies_cookiestore(url, partition_context, HTTP::Cookie::non_http_same_site_context(*partition_context));
}
Messages::WebContentClient::DidRequestCookieResponse WebContentPage::did_request_cookie(Optional<Web::HTML::EnvironmentId> const& environment_id, URL::URL url, HTTP::Cookie::Source source)
{
// NB: Only WebDriver reads cookies like HTTP does, for the top-level documents it drives.
Optional<HTTP::Cookie::PartitionContext> partition_context;
+ auto same_site_context = HTTP::Cookie::SameSiteContext::same_site();
if (source == HTTP::Cookie::Source::NonHttp) {
partition_context = cookie_partition_context_for(*this, environment_id, url);
if (!partition_context.has_value())
return HTTP::Cookie::VersionedCookie {};
+ same_site_context = HTTP::Cookie::non_http_same_site_context(*partition_context);
}
HTTP::Cookie::VersionedCookie cookie;
- cookie.cookie = client().session().cookie_jar->get_cookie(url, source, partition_context);
+ cookie.cookie = client().session().cookie_jar->get_cookie(url, source, partition_context, same_site_context);
if (source == HTTP::Cookie::Source::NonHttp)
cookie.cookie_version = view().document_cookie_version(url);
return cookie;
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 301218c74d7..a522aebf946 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -357,7 +357,7 @@ private:
virtual void did_forward_pinch_event_to_child_frame(Web::HTML::CrossProcessId frame_id, Web::PinchEvent) override;
virtual void did_destroy_child_frame(Web::HTML::CrossProcessId frame_id) override;
Messages::WebContentClient::DidStartDownloadWithoutRequestResponse did_start_download_without_request(URL::URL url, ByteString suggested_filename, Optional<u64> total_size);
- Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data,
+ Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data,
JsonValue network_response);
virtual void did_receive_download_data(u64 download_id, ByteBuffer data) override;
virtual void did_finish_download(u64 download_id) override;
diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cpp
index 632ab48b541..dca0d55cade 100644
--- a/Libraries/LibWebView/WebWorkerClient.cpp
+++ b/Libraries/LibWebView/WebWorkerClient.cpp
@@ -153,7 +153,7 @@ Messages::WebWorkerClient::DidRequestCookieResponse WebWorkerClient::did_request
HTTP::Cookie::PartitionContext partition_context { top_level_site.release_value(), m_inside_settings->has_cross_site_ancestor() };
HTTP::Cookie::VersionedCookie cookie;
if (auto session = m_session.strong_ref())
- cookie.cookie = session->cookie_jar->get_cookie(url, source, partition_context);
+ cookie.cookie = session->cookie_jar->get_cookie(url, source, partition_context, HTTP::Cookie::non_http_same_site_context(partition_context));
return cookie;
}
diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cpp
index bc3ebf79762..18ac916d8af 100644
--- a/Services/RequestServer/ConnectionFromClient.cpp
+++ b/Services/RequestServer/ConnectionFromClient.cpp
@@ -291,7 +291,7 @@ bool ConnectionFromClient::is_live_request_id(u64 request_id) const
return m_active_requests.contains(request_id) || m_request_transfer_leases.contains({ client_id(), request_id });
}
-void ConnectionFromClient::start_request(u64 request_id, ByteString method, URL::URL url, Vector<HTTP::Header> request_headers, ByteBuffer request_body, HTTP::CacheMode cache_mode, Optional<HTTP::NetworkIsolationKey> network_isolation_key, HTTP::Cookie::IncludeCredentials include_credentials, bool create_transfer_lease, Optional<u32> address_selection_hint, bool notify_on_cache_miss, i32 originating_process_id, u64 originating_page_id)
+void ConnectionFromClient::start_request(u64 request_id, ByteString method, URL::URL url, Vector<HTTP::Header> request_headers, ByteBuffer request_body, HTTP::CacheMode cache_mode, Optional<HTTP::NetworkIsolationKey> network_isolation_key, HTTP::Cookie::IncludeCredentials include_credentials, bool create_transfer_lease, Optional<u32> address_selection_hint, bool notify_on_cache_miss, i32 originating_process_id, u64 originating_page_id, HTTP::Cookie::SameSiteContext same_site_context)
{
note_event_tick("ipc-start-request"sv);
dbgln_if(REQUESTSERVER_DEBUG, "RequestServer: start_request({}, {})", request_id, url);
@@ -343,7 +343,7 @@ void ConnectionFromClient::start_request(u64 request_id, ByteString method, URL:
auto transfer_lease = create_transfer_lease
? Optional<Requests::RequestTransferLeaseKey> { lease_key }
: Optional<Requests::RequestTransferLeaseKey> {};
- auto request = Request::fetch(request_id, m_disk_cache, move(network_isolation_key), cache_mode, *this, m_curl_multi, m_resolver, move(url), move(method), HTTP::HeaderList::create(move(request_headers)), move(request_body), include_credentials, transfer_lease, address_selection_hint, notify_on_cache_miss);
+ auto request = Request::fetch(request_id, m_disk_cache, move(network_isolation_key), cache_mode, *this, m_curl_multi, m_resolver, move(url), move(method), HTTP::HeaderList::create(move(request_headers)), move(request_body), include_credentials, same_site_context, transfer_lease, address_selection_hint, notify_on_cache_miss);
request->set_performance_origin(originating_process_id, originating_page_id);
m_active_requests.set(request_id, move(request));
@@ -430,14 +430,14 @@ void ConnectionFromClient::release_request_transfer_lease(int source_client_id,
}
}
-void ConnectionFromClient::start_revalidation_request(Badge<Request>, HTTP::NetworkIsolationKey network_isolation_key, ByteString method, URL::URL url, NonnullRefPtr<HTTP::HeaderList> request_headers, ByteBuffer request_body, HTTP::Cookie::IncludeCredentials include_credentials)
+void ConnectionFromClient::start_revalidation_request(Badge<Request>, HTTP::NetworkIsolationKey network_isolation_key, ByteString method, URL::URL url, NonnullRefPtr<HTTP::HeaderList> request_headers, ByteBuffer request_body, HTTP::Cookie::IncludeCredentials include_credentials, HTTP::Cookie::SameSiteContext same_site_context)
{
note_event_tick("ipc-start-revalidation"sv);
auto request_id = m_next_revalidation_request_id++;
dbgln_if(REQUESTSERVER_DEBUG, "RequestServer: start_revalidation_request({}, {})", request_id, url);
- auto request = Request::revalidate(request_id, m_disk_cache, move(network_isolation_key), *this, m_curl_multi, m_resolver, move(url), move(method), move(request_headers), move(request_body), include_credentials);
+ auto request = Request::revalidate(request_id, m_disk_cache, move(network_isolation_key), *this, m_curl_multi, m_resolver, move(url), move(method), move(request_headers), move(request_body), include_credentials, same_site_context);
m_active_revalidation_requests.set(request_id, move(request));
}
@@ -847,7 +847,7 @@ size_t ConnectionFromClient::total_websocket_count() const
return count;
}
-void ConnectionFromClient::websocket_connect(u64 websocket_id, URL::URL url, Optional<HTTP::NetworkIsolationKey> network_isolation_key, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers)
+void ConnectionFromClient::websocket_connect(u64 websocket_id, URL::URL url, Optional<HTTP::NetworkIsolationKey> network_isolation_key, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, HTTP::Cookie::SameSiteContext same_site_context)
{
if (m_pending_websockets.contains(websocket_id) || m_websockets.contains(websocket_id)) {
did_misbehave("reused live WebSocket ID");
@@ -916,7 +916,7 @@ void ConnectionFromClient::websocket_connect(u64 websocket_id, URL::URL url, Opt
Optional<HTTP::Cookie::PartitionContext> partition_context;
if (network_isolation_key.has_value())
partition_context = HTTP::Cookie::PartitionContext { network_isolation_key->top_level_site, network_isolation_key->has_cross_site_ancestor };
- control_connection->async_retrieve_http_cookie(client_id(), websocket_id, RequestType::WebSocket, cookie_request_id, url, move(partition_context));
+ control_connection->async_retrieve_http_cookie(client_id(), websocket_id, RequestType::WebSocket, cookie_request_id, url, move(partition_context), same_site_context);
}
bool ConnectionFromClient::websocket_retrieved_http_cookie(Badge<ControlConnectionFromClient>, u64 websocket_id, u64 cookie_request_id, String cookie)
diff --git a/Services/RequestServer/ConnectionFromClient.h b/Services/RequestServer/ConnectionFromClient.h
index e03c57ca5fc..25d84e5e6a8 100644
--- a/Services/RequestServer/ConnectionFromClient.h
+++ b/Services/RequestServer/ConnectionFromClient.h
@@ -75,7 +75,7 @@ public:
// frame site of nothing stands for documents with opaque origins.
void bind_to_site(Badge<ControlConnectionFromClient>, Utf16String const& top_level_site, Optional<Utf16String> const& frame_site);
- void start_revalidation_request(Badge<Request>, HTTP::NetworkIsolationKey, ByteString method, URL::URL, NonnullRefPtr<HTTP::HeaderList> request_headers, ByteBuffer request_body, HTTP::Cookie::IncludeCredentials);
+ void start_revalidation_request(Badge<Request>, HTTP::NetworkIsolationKey, ByteString method, URL::URL, NonnullRefPtr<HTTP::HeaderList> request_headers, ByteBuffer request_body, HTTP::Cookie::IncludeCredentials, HTTP::Cookie::SameSiteContext);
void request_complete(Badge<Request>, Request const&);
void fetch_aia_intermediate(Badge<Request>, ByteString const& url, u64 for_request_id);
@@ -86,7 +86,7 @@ private:
virtual Messages::RequestServer::IsSupportedProtocolResponse is_supported_protocol(ByteString) override;
virtual Messages::RequestServer::GetClientIdResponse get_client_id() override;
- virtual void start_request(u64 request_id, ByteString, URL::URL, Vector<HTTP::Header>, ByteBuffer, HTTP::CacheMode, Optional<HTTP::NetworkIsolationKey>, HTTP::Cookie::IncludeCredentials, bool create_transfer_lease, Optional<u32> address_selection_hint, bool notify_on_cache_miss, i32 originating_process_id, u64 originating_page_id) override;
+ virtual void start_request(u64 request_id, ByteString, URL::URL, Vector<HTTP::Header>, ByteBuffer, HTTP::CacheMode, Optional<HTTP::NetworkIsolationKey>, HTTP::Cookie::IncludeCredentials, bool create_transfer_lease, Optional<u32> address_selection_hint, bool notify_on_cache_miss, i32 originating_process_id, u64 originating_page_id, HTTP::Cookie::SameSiteContext) override;
virtual void adopt_request(int source_client_id, u64 source_request_id, u64 target_request_id, bool preserve_transfer_lease) override;
virtual void release_request_transfer_lease(int source_client_id, u64 source_request_id) override;
virtual Messages::RequestServer::StopRequestResponse stop_request(u64 request_id) override;
@@ -95,7 +95,7 @@ private:
virtual void ensure_connection(u64 request_id, URL::URL url, ::RequestServer::CacheLevel cache_level) override;
virtual void resolve_host(u64 lookup_id, ByteString host) override;
- virtual void websocket_connect(u64 websocket_id, URL::URL, Optional<HTTP::NetworkIsolationKey>, ByteString, Vector<ByteString>, Vector<ByteString>, Vector<HTTP::Header>) override;
+ virtual void websocket_connect(u64 websocket_id, URL::URL, Optional<HTTP::NetworkIsolationKey>, ByteString, Vector<ByteString>, Vector<ByteString>, Vector<HTTP::Header>, HTTP::Cookie::SameSiteContext) override;
virtual void websocket_send(u64 websocket_id, bool, ByteBuffer) override;
virtual void websocket_send_shared(u64 websocket_id, bool, Core::AnonymousBuffer) override;
virtual void websocket_close(u64 websocket_id, u16, ByteString) override;
diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cpp
index 69648fb17e3..a9c6b2631e0 100644
--- a/Services/RequestServer/Request.cpp
+++ b/Services/RequestServer/Request.cpp
@@ -438,11 +438,12 @@ NonnullOwnPtr<Request> Request::fetch(
NonnullRefPtr<HTTP::HeaderList> request_headers,
ByteBuffer request_body,
HTTP::Cookie::IncludeCredentials include_credentials,
+ HTTP::Cookie::SameSiteContext same_site_context,
Optional<Requests::RequestTransferLeaseKey> transfer_lease,
Optional<u32> address_selection_hint,
bool notify_on_cache_miss)
{
- auto request = adopt_own(*new Request { request_id, RequestType::Fetch, disk_cache, move(network_isolation_key), cache_mode, client, curl_multi, resolver, move(url), move(method), move(request_headers), move(request_body), include_credentials, move(transfer_lease) });
+ auto request = adopt_own(*new Request { request_id, RequestType::Fetch, disk_cache, move(network_isolation_key), cache_mode, client, curl_multi, resolver, move(url), move(method), move(request_headers), move(request_body), include_credentials, same_site_context, move(transfer_lease) });
request->m_address_selection_hint = address_selection_hint;
request->m_notify_on_cache_miss = notify_on_cache_miss;
request->process();
@@ -475,12 +476,13 @@ NonnullOwnPtr<Request> Request::revalidate(
ByteString method,
NonnullRefPtr<HTTP::HeaderList> request_headers,
ByteBuffer request_body,
- HTTP::Cookie::IncludeCredentials include_credentials)
+ HTTP::Cookie::IncludeCredentials include_credentials,
+ HTTP::Cookie::SameSiteContext same_site_context)
{
// Revalidation headers must not leak into the initiating request.
request_headers = HTTP::HeaderList::create(request_headers->headers());
- auto request = adopt_own(*new Request { request_id, RequestType::BackgroundRevalidation, disk_cache, move(network_isolation_key), HTTP::CacheMode::Default, client, curl_multi, resolver, move(url), move(method), move(request_headers), move(request_body), include_credentials });
+ auto request = adopt_own(*new Request { request_id, RequestType::BackgroundRevalidation, disk_cache, move(network_isolation_key), HTTP::CacheMode::Default, client, curl_multi, resolver, move(url), move(method), move(request_headers), move(request_body), include_credentials, same_site_context });
request->process();
return request;
@@ -500,6 +502,7 @@ Request::Request(
NonnullRefPtr<HTTP::HeaderList> request_headers,
ByteBuffer request_body,
HTTP::Cookie::IncludeCredentials include_credentials,
+ HTTP::Cookie::SameSiteContext same_site_context,
Optional<Requests::RequestTransferLeaseKey> transfer_lease)
: m_request_id(request_id)
, m_type(type)
@@ -515,6 +518,7 @@ Request::Request(
, m_request_headers(move(request_headers))
, m_request_body(move(request_body))
, m_include_credentials(include_credentials)
+ , m_same_site_context(same_site_context)
, m_response_headers(HTTP::HeaderList::create())
, m_transfer_lease(move(transfer_lease))
{
@@ -568,7 +572,7 @@ NonnullOwnPtr<Request> Request::import(
Requests::ExportedRequest exported,
Optional<Requests::RequestTransferLeaseKey> transfer_lease)
{
- auto request = adopt_own(*new Request { request_id, RequestType::Imported, disk_cache, move(exported.network_isolation_key), HTTP::CacheMode::Default, client, nullptr, resolver, move(exported.url), move(exported.method), HTTP::HeaderList::create(move(exported.request_headers)), ByteBuffer {}, HTTP::Cookie::IncludeCredentials::No, move(transfer_lease) });
+ auto request = adopt_own(*new Request { request_id, RequestType::Imported, disk_cache, move(exported.network_isolation_key), HTTP::CacheMode::Default, client, nullptr, resolver, move(exported.url), move(exported.method), HTTP::HeaderList::create(move(exported.request_headers)), ByteBuffer {}, HTTP::Cookie::IncludeCredentials::No, {}, move(transfer_lease) });
request->m_request_start_time = exported.request_start_time;
request->m_status_code = exported.status_code;
request->m_reason_phrase = move(exported.reason_phrase);
@@ -705,7 +709,7 @@ void Request::request_response_storage(ControlConnectionFromClient& connection)
static u64 s_next_response_storage_request_id = 0;
m_response_storage_request_id = s_next_response_storage_request_id++;
- connection.async_store_response_cookies_and_hsts_policy(m_client->client_id(), m_request_id, *m_response_storage_request_id, m_url, cookie_partition_context(), m_pending_response_storage->cookies, m_pending_response_storage->hsts_policy);
+ connection.async_store_response_cookies_and_hsts_policy(m_client->client_id(), m_request_id, *m_response_storage_request_id, m_url, cookie_partition_context(), m_same_site_context, m_pending_response_storage->cookies, m_pending_response_storage->hsts_policy);
}
bool Request::notify_stored_response_cookies_and_hsts_policy(Badge<ControlConnectionFromClient>, u64 store_request_id)
@@ -1028,7 +1032,7 @@ void Request::handle_initial_state()
if (m_cache_entry_reader.has_value()) {
if (m_cache_entry_reader->revalidation_type() == HTTP::CacheEntryReader::RevalidationType::StaleWhileRevalidate)
- m_client->start_revalidation_request({}, *m_network_isolation_key, m_method, m_url, m_request_headers, m_request_body, m_include_credentials);
+ m_client->start_revalidation_request({}, *m_network_isolation_key, m_method, m_url, m_request_headers, m_request_body, m_include_credentials, m_same_site_context);
if (is_revalidation_request())
transition_to_state(State::DNSLookup);
@@ -1358,7 +1362,7 @@ void Request::handle_retrieve_cookie_state()
static u64 s_next_cookie_request_id = 0;
m_cookie_request_id = s_next_cookie_request_id++;
mark_lifecycle_event(this, &WireStats::cookie_started_at);
- connection->async_retrieve_http_cookie(m_client->client_id(), m_request_id, m_type, *m_cookie_request_id, m_url, cookie_partition_context());
+ connection->async_retrieve_http_cookie(m_client->client_id(), m_request_id, m_type, *m_cookie_request_id, m_url, cookie_partition_context(), m_same_site_context);
} else {
m_network_error = Requests::NetworkError::RequestServerDied;
transition_to_state(State::Error);
diff --git a/Services/RequestServer/Request.h b/Services/RequestServer/Request.h
index 43116378933..53e15d8e439 100644
--- a/Services/RequestServer/Request.h
+++ b/Services/RequestServer/Request.h
@@ -62,6 +62,7 @@ public:
NonnullRefPtr<HTTP::HeaderList> request_headers,
ByteBuffer request_body,
HTTP::Cookie::IncludeCredentials include_credentials,
+ HTTP::Cookie::SameSiteContext,
Optional<Requests::RequestTransferLeaseKey>,
Optional<u32> address_selection_hint,
bool notify_on_cache_miss);
@@ -85,7 +86,8 @@ public:
ByteString method,
NonnullRefPtr<HTTP::HeaderList> request_headers,
ByteBuffer request_body,
- HTTP::Cookie::IncludeCredentials include_credentials);
+ HTTP::Cookie::IncludeCredentials include_credentials,
+ HTTP::Cookie::SameSiteContext);
static NonnullOwnPtr<Request> import(
u64 request_id,
@@ -209,6 +211,7 @@ private:
NonnullRefPtr<HTTP::HeaderList> request_headers,
ByteBuffer request_body,
HTTP::Cookie::IncludeCredentials include_credentials,
+ HTTP::Cookie::SameSiteContext,
Optional<Requests::RequestTransferLeaseKey> = {});
Request(
@@ -357,6 +360,7 @@ private:
Optional<MonotonicTime> m_last_request_body_report_time;
HTTP::Cookie::IncludeCredentials m_include_credentials { HTTP::Cookie::IncludeCredentials::Yes };
+ HTTP::Cookie::SameSiteContext m_same_site_context;
Optional<AlternativeService> m_alternative_service;
bool m_alternative_services_disabled { false };
diff --git a/Services/RequestServer/RequestServer.ipc b/Services/RequestServer/RequestServer.ipc
index b3568f4987f..c81ea13fb5e 100644
--- a/Services/RequestServer/RequestServer.ipc
+++ b/Services/RequestServer/RequestServer.ipc
@@ -1,5 +1,6 @@
#include <LibCore/AnonymousBuffer.h>
#include <LibHTTP/Cache/CacheMode.h>
+#include <LibHTTP/Cookie/Cookie.h>
#include <LibHTTP/Cookie/IncludeCredentials.h>
#include <LibHTTP/Header.h>
#include <LibHTTP/NetworkIsolationKey.h>
@@ -16,7 +17,7 @@ endpoint RequestServer
is_supported_protocol(ByteString protocol) => (bool supported)
get_client_id() => (int client_id)
- start_request(u64 request_id, ByteString method, URL::URL url, Vector<HTTP::Header> request_headers, ByteBuffer request_body, HTTP::CacheMode cache_mode, Optional<HTTP::NetworkIsolationKey> network_isolation_key, HTTP::Cookie::IncludeCredentials include_credentials, bool create_transfer_lease, Optional<u32> address_selection_hint, bool notify_on_cache_miss, i32 originating_process_id, u64 originating_page_id) =|
+ start_request(u64 request_id, ByteString method, URL::URL url, Vector<HTTP::Header> request_headers, ByteBuffer request_body, HTTP::CacheMode cache_mode, Optional<HTTP::NetworkIsolationKey> network_isolation_key, HTTP::Cookie::IncludeCredentials include_credentials, bool create_transfer_lease, Optional<u32> address_selection_hint, bool notify_on_cache_miss, i32 originating_process_id, u64 originating_page_id, HTTP::Cookie::SameSiteContext same_site_context) =|
adopt_request(int source_client_id, u64 source_request_id, u64 target_request_id, bool preserve_transfer_lease) =|
release_request_transfer_lease(int source_client_id, u64 source_request_id) =|
stop_request(u64 request_id) => (bool success)
@@ -33,7 +34,7 @@ endpoint RequestServer
resolve_host(u64 lookup_id, ByteString host) =|
// Websocket Connection API
- websocket_connect(u64 websocket_id, URL::URL url, Optional<HTTP::NetworkIsolationKey> network_isolation_key, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers) =|
+ websocket_connect(u64 websocket_id, URL::URL url, Optional<HTTP::NetworkIsolationKey> network_isolation_key, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, HTTP::Cookie::SameSiteContext same_site_context) =|
websocket_send(u64 websocket_id, bool is_text, ByteBuffer data) =|
websocket_send_shared(u64 websocket_id, bool is_text, Core::AnonymousBuffer data) =|
websocket_close(u64 websocket_id, u16 code, ByteString reason) =|
diff --git a/Services/RequestServer/RequestServerControlClient.ipc b/Services/RequestServer/RequestServerControlClient.ipc
index 2a5798b21b3..0d76a27bfca 100644
--- a/Services/RequestServer/RequestServerControlClient.ipc
+++ b/Services/RequestServer/RequestServerControlClient.ipc
@@ -13,8 +13,8 @@ endpoint RequestServerControlClient
client_disconnected(int client_id) =|
// The partition context comes from the request's network isolation key, and is nothing for a request without one.
- retrieve_http_cookie(int client_id, u64 request_id, ::RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context) =|
- store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy) =|
+ retrieve_http_cookie(int client_id, u64 request_id, ::RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context) =|
+ store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy) =|
network_usage(Vector<Requests::NetworkUsage> usage, u64 interval_microseconds) =|
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index ad260cd0e30..d496a5585d5 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -1054,9 +1054,9 @@ void PageClient::page_did_finish_loading(Web::HTML::CrossProcessId navigable_id,
client().async_did_finish_loading(m_id, navigable_id, document_id);
}
-Optional<u64> PageClient::page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const& url, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
+Optional<u64> PageClient::page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const& url, ByteString const& suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
{
- auto response = client().send_sync<Messages::WebContentClient::DidStartDownload>(m_id, navigable_id, navigation_id, url, suggested_filename, total_size, request_server_client_id, request_server_request_id, move(initial_data), move(network_response));
+ auto response = client().send_sync<Messages::WebContentClient::DidStartDownload>(m_id, navigable_id, navigation_id, url, suggested_filename, total_size, same_site_context, request_server_client_id, request_server_request_id, move(initial_data), move(network_response));
return response->download_id();
}
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 8b61464718b..039e45d3811 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -278,7 +278,7 @@ private:
virtual void page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document&) override;
virtual void page_did_change_active_document_in_child_navigable(Web::DOM::Document&) override;
virtual void page_did_finish_loading(Web::HTML::CrossProcessId, Web::HTML::CrossProcessId) override;
- virtual Optional<u64> page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;
+ virtual Optional<u64> page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;
virtual Optional<u64> page_did_start_download(URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size) override;
virtual void page_did_receive_download_data(u64 download_id, ByteBuffer data) override;
virtual void page_did_finish_download(u64 download_id) override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 6abae9e37d7..0d50f6982b0 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -115,7 +115,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_destroy_child_frame(Web::PageId page_id, Web::HTML::CrossProcessId frame_id) =|
did_finish_loading(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId document_id) =|
[NotRouted] did_start_download_without_request(Web::PageId page_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size) => (Optional<u64> download_id)
- [NotRouted] did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) => (Optional<u64> download_id)
+ [NotRouted] did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, HTTP::Cookie::SameSiteContext same_site_context, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) => (Optional<u64> download_id)
did_receive_download_data(Web::PageId page_id, u64 download_id, ByteBuffer data) =|
did_finish_download(Web::PageId page_id, u64 download_id) =|
did_fail_download(Web::PageId page_id, u64 download_id, String error) =|
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 972d0c16cf4..626987af935 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -79,6 +79,12 @@ Text/input/css/canvas-font-display.html
Ref/input/font-display-periods.html
Ref/expected/font-display-periods-ref.html
; Tests cookies.
+Text/input/Fetch/fetch-cors-credentials-flag.html
+Text/input/Fetch/fetch-worker-response-set-cookie.html
+Text/input/Fetch/malformed-content-encoding-cookies.html
+Text/input/Fetch/unsupported-content-encoding-retry-stores-cookies.html
+Text/input/Fetch/cookie-header-non-ascii.html
+Text/input/WebSocket/handshake-cookie.html
Text/input/cookie-cache-invalidation.html
Text/input/cookie-working.html
Text/input/cookie-store-empty-domain.html
@@ -1258,6 +1264,24 @@ Text/input/SVG/use-element-relative-external-reference-after-adoption.html
Text/input/SVG/use-element-repeated-href-changes-on-stalled-sprite.html
Text/input/SVG/use-element-same-document-href-stops-delaying-load.html
+[LoadFromHttpsServer]
+Text/input/SiteIsolation/iframe/embedded-page-cookie-request.html
+Text/input/third-party-cookies-are-partitioned.html
+Text/input/cookies-of-a-frame-with-a-cross-site-ancestor-are-partitioned.html
+Text/input/document-cookie-uses-the-partition-of-the-asking-document.html
+Text/input/cookie-change-events-skip-other-partitions.html
+Text/input/SiteIsolation/iframe/removing-remote-iframe-aborts-its-navigation-api.html
+Text/input/SiteIsolation/iframe/unload-runs-in-remote-iframe-when-parent-navigates.html
+Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-its-parent-hosts-it.html
+Text/input/SiteIsolation/iframe/local-iframe-unloads-before-another-process-hosts-it.html
+Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-another-process-hosts-it.html
+Text/input/SiteIsolation/iframe/iframe-stays-scriptable-after-its-document-unloads-for-another-process.html
+Text/input/SiteIsolation/iframe/unload-runs-across-processes-on-iframe-removal.html
+Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-navigate.html
+Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-back.html
+Text/input/shared-worker-is-not-shared-across-top-level-sites.html
+Text/input/wpt-import/cookies/samesite/
+
[CapFrameRate]
; Ends a smooth scroll once 20 frames see no change, which frames faster than the compositor's ticks do
Text/input/wpt-import/css/cssom-view/scroll-behavior-default-css.html
diff --git a/Tests/LibWeb/Text/expected/navigation/reload-after-javascript-url-sends-strict-cookies.txt b/Tests/LibWeb/Text/expected/navigation/reload-after-javascript-url-sends-strict-cookies.txt
new file mode 100644
index 00000000000..3c9f1704cb3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigation/reload-after-javascript-url-sends-strict-cookies.txt
@@ -0,0 +1 @@
+Reload sends the SameSite=Strict cookie: true
diff --git a/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/fetch.https.txt b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/fetch.https.txt
new file mode 100644
index 00000000000..a09c474ec81
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/fetch.https.txt
@@ -0,0 +1,18 @@
+Harness status: OK
+
+Found 12 tests
+
+8 Pass
+4 Fail
+Pass Same-host fetches are strictly same-site
+Pass Subdomain fetches are strictly same-site
+Fail Cross-site fetches are cross-site
+Pass Same-host redirecting to same-host fetches are strictly same-site
+Pass Subdomain redirecting to same-host fetches are strictly same-site
+Pass Cross-site redirecting to same-host fetches are cross-site
+Pass Same-host redirecting to subdomain fetches are strictly same-site
+Pass Subdomain redirecting to subdomain fetches are strictly same-site
+Pass Cross-site redirecting to subdomain fetches are cross-site
+Fail Same-host redirecting to cross-site fetches are cross-site
+Fail Subdomain redirecting to cross-site fetches are cross-site
+Fail Cross-site redirecting to cross-site fetches are cross-site
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/form-get-blank.https.txt b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/form-get-blank.https.txt
new file mode 100644
index 00000000000..1409a5ea0ff
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/form-get-blank.https.txt
@@ -0,0 +1,17 @@
+Harness status: OK
+
+Found 12 tests
+
+12 Pass
+Pass Same-host top-level form GETs are strictly same-site
+Pass Subdomain top-level form GETs are strictly same-site
+Pass Cross-site top-level form GETs are laxly same-site
+Pass Same-host redirecting to same-host top-level form GETs are strictly same-site
+Pass Subdomain redirecting to same-host top-level form GETs are strictly same-site
+Pass Cross-site redirecting to same-host top-level form GETs are laxly same-site
+Pass Same-host redirecting to subdomain top-level form GETs are strictly same-site
+Pass Subdomain redirecting to subdomain top-level form GETs are strictly same-site
+Pass Cross-site redirecting to subdomain top-level form GETs are laxly same-site
+Pass Same-host redirecting to cross-site top-level form GETs are laxly same-site
+Pass Subdomain redirecting to cross-site top-level form GETs are laxly same-site
+Pass Cross-site redirecting to cross-site top-level form GETs are laxly same-site
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/form-post-blank.https.txt b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/form-post-blank.https.txt
new file mode 100644
index 00000000000..c3c2b3e9e3a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/form-post-blank.https.txt
@@ -0,0 +1,17 @@
+Harness status: OK
+
+Found 12 tests
+
+12 Pass
+Pass Same-host top-level form POSTs are strictly same-site
+Pass Subdomain top-level form POSTs are strictly same-site
+Pass Cross-site top-level form POSTs are cross-site
+Pass Same-host redirecting to same-host top-level form POSTs are strictly same-site
+Pass Subdomain redirecting to same-host top-level form POSTs are strictly same-site
+Pass Cross-site redirecting to same-host top-level form POSTs are cross-site
+Pass Same-host redirecting to subdomain top-level form POSTs are strictly same-site
+Pass Subdomain redirecting to subdomain top-level form POSTs are strictly same-site
+Pass Cross-site redirecting to subdomain top-level form POSTs are cross-site
+Pass Same-host redirecting to cross-site top-level form POSTs are cross-site
+Pass Subdomain redirecting to cross-site top-level form POSTs are cross-site
+Pass Cross-site redirecting to cross-site top-level form POSTs are cross-site
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/setcookie-navigation.https.txt b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/setcookie-navigation.https.txt
new file mode 100644
index 00000000000..bcdd72f59a7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/cookies/samesite/setcookie-navigation.https.txt
@@ -0,0 +1,13 @@
+Harness status: OK
+
+Found 8 tests
+
+8 Pass
+Pass Same-site top-level navigation should be able to set SameSite=* cookies.
+Pass Cross-site top-level navigation should be able to set SameSite=* cookies.
+Pass Same-site top-level POST should be able to set SameSite=* cookies.
+Pass Cross-site top-level POST should be able to set SameSite=* cookies.
+Pass Same-site to same-site iframe navigation should be able to set SameSite=* cookies.
+Pass Cross-site to same-site iframe navigation should only be able to set SameSite=None cookies.
+Pass Same-site to cross-site-site iframe navigation should only be able to set SameSite=None cookies.
+Pass Cross-site to cross-site iframe navigation should only be able to set SameSite=None cookies.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/Fetch/cookie-header-non-ascii.html b/Tests/LibWeb/Text/input/Fetch/cookie-header-non-ascii.html
index 9ae5bcbaa11..4098d2cf4fa 100644
--- a/Tests/LibWeb/Text/input/Fetch/cookie-header-non-ascii.html
+++ b/Tests/LibWeb/Text/input/Fetch/cookie-header-non-ascii.html
@@ -3,44 +3,32 @@
<script>
// Cookie names and values may contain non-ASCII characters. They must reach the server as the same characters, and
// must never turn into bytes that end the Cookie field (U+010D and U+010A would narrow to CR and LF), or into an
- // ASCII name that the cookie was never allowed to have (U+015F would narrow to "_"). The echo server is reached
- // through unique host names so that cookie tests running in parallel cannot delete the cookies.
+ // ASCII name that the cookie was never allowed to have (U+015F would narrow to "_").
const utf8AsLatin1 = string => unescape(encodeURIComponent(string));
- const headers = {
- "Access-Control-Allow-Origin": location.origin,
- "Access-Control-Allow-Credentials": "true",
- };
-
async function requestHeadersAfterSettingCookie(name, cookie) {
const httpServer = httpTestServer();
- const hostname = uniqueLocalhostHostname(name);
- const withHostname = url => {
- const result = new URL(url);
- result.hostname = hostname;
- return result.href;
- };
-
- const setURL = withHostname(await httpServer.createEcho("GET", `/${name}-set`, {
+ const path = new URL(httpServer.echoURL(`/${name}/`)).pathname;
+ const setURL = await httpServer.createEcho("GET", `/${name}/set`, {
status: 200,
- headers: { ...headers, "Set-Cookie": utf8AsLatin1(cookie) },
- }));
- await fetch(setURL, { credentials: "include" });
+ headers: { "Set-Cookie": utf8AsLatin1(`${cookie}; Path=${path}`) },
+ });
+ await fetch(setURL);
- const reflectURL = withHostname(await httpServer.createEcho("GET", `/${name}-reflect`, {
+ const reflectURL = await httpServer.createEcho("GET", `/${name}/reflect`, {
status: 200,
- headers,
+ headers: { "Content-Type": "application/json" },
reflect_headers_in_body: true,
- }));
- return await (await fetch(reflectURL, { credentials: "include" })).json();
+ });
+ return await (await fetch(reflectURL)).json();
}
promiseTest(async () => {
- const injection = await requestHeadersAfterSettingCookie("cookie-header-non-ascii-value", "injected=ačĊX-Injected: 1; Path=/");
+ const injection = await requestHeadersAfterSettingCookie("cookie-header-non-ascii-value", "injected=ačĊX-Injected: 1");
println(`Injected header reached the server: ${"X-Injected" in injection}`);
println(`Value arrived as UTF-8: ${(injection["Cookie"] ?? []).includes(utf8AsLatin1("injected=ačĊX-Injected: 1"))}`);
- const prefix = await requestHeadersAfterSettingCookie("cookie-header-non-ascii-name", "ş_Host-session=attacker; Path=/");
+ const prefix = await requestHeadersAfterSettingCookie("cookie-header-non-ascii-name", "ş_Host-session=attacker");
println(`__Host- name reached the server: ${(prefix["Cookie"] ?? []).some(cookie => cookie.includes("__Host-session"))}`);
println(`Name arrived as UTF-8: ${(prefix["Cookie"] ?? []).includes(utf8AsLatin1("ş_Host-session=attacker"))}`);
});
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-worker-response-set-cookie.html b/Tests/LibWeb/Text/input/Fetch/fetch-worker-response-set-cookie.html
index 4952e61746f..ea074fc7912 100644
--- a/Tests/LibWeb/Text/input/Fetch/fetch-worker-response-set-cookie.html
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-worker-response-set-cookie.html
@@ -8,25 +8,15 @@
promiseTest(async () => {
const httpServer = httpTestServer();
- const headers = {
- "Access-Control-Allow-Origin": location.origin,
- "Access-Control-Allow-Credentials": "true",
- };
- const hostname = uniqueLocalhostHostname("worker-response-set-cookie");
- const withHostname = url => {
- const result = new URL(url);
- result.hostname = hostname;
- return result.href;
- };
- const setURL = withHostname(await httpServer.createEcho("GET", "/fetch-worker-response-set-cookie-set", {
+ const setURL = await httpServer.createEcho("GET", "/fetch-worker-response-set-cookie-set", {
status: 200,
- headers: { ...headers, "Set-Cookie": `${COOKIE_NAME}=stored` },
- }));
- const reflectURL = withHostname(await httpServer.createEcho("GET", "/fetch-worker-response-set-cookie-reflect", {
+ headers: { "Set-Cookie": `${COOKIE_NAME}=stored; SameSite=Strict` },
+ });
+ const reflectURL = await httpServer.createEcho("GET", "/fetch-worker-response-set-cookie-reflect", {
status: 200,
- headers,
+ headers: { "Content-Type": "application/json" },
reflect_headers_in_body: true,
- }));
+ });
const workerScript = `
self.onmessage = async (e) => {
@@ -43,14 +33,15 @@
worker.onmessage = e => resolve(e.data);
worker.postMessage(setURL);
});
- worker.terminate();
if (workerResult !== "fetched") {
+ worker.terminate();
println(workerResult);
return;
}
const response = await fetch(reflectURL, { credentials: "include" });
const body = await response.json();
+ worker.terminate();
const cookie = body["Cookie"]?.find(cookie => cookie.trim().startsWith(`${COOKIE_NAME}=`));
println(cookie ? `Cookie sent: ${cookie.trim()}` : "Cookie not sent");
});
diff --git a/Tests/LibWeb/Text/input/Fetch/malformed-content-encoding-cookies.html b/Tests/LibWeb/Text/input/Fetch/malformed-content-encoding-cookies.html
index 80d24454f11..b4e1878c8bd 100644
--- a/Tests/LibWeb/Text/input/Fetch/malformed-content-encoding-cookies.html
+++ b/Tests/LibWeb/Text/input/Fetch/malformed-content-encoding-cookies.html
@@ -3,20 +3,17 @@
<script>
promiseTest(async () => {
for (const method of ["GET", "POST"]) {
- const host = uniqueLocalhostHostname(`malformed-content-encoding-${method.toLowerCase()}`);
- const responseURL = new URL(await httpTestServer().createEcho(method, `/malformed-content-encoding-${method}`, {
+ const cookieName = `malformedbodycookie-${method.toLowerCase()}`;
+ const responseURL = await httpTestServer().createEcho(method, `/malformed-content-encoding-${method}`, {
status: 200,
headers: {
- "Access-Control-Allow-Origin": location.origin,
- "Access-Control-Allow-Credentials": "true",
"Content-Type": "text/plain",
"Content-Encoding": "gzip",
- "Set-Cookie": "malformedbodycookie=stored; Path=/",
+ "Set-Cookie": `${cookieName}=stored; Path=/`,
"Cache-Control": "no-store",
},
body: "not actually gzip",
- }));
- responseURL.hostname = host;
+ });
try {
const response = await fetch(responseURL, { method, credentials: "include" });
println(`${method} status: ${response.status}`);
@@ -26,19 +23,14 @@
} catch (error) {
println(`${method} body: ${error.name}`);
}
- const echoURL = new URL(await httpTestServer().createEcho("GET", `/malformed-content-encoding-cookie-${method}`, {
+ const echoURL = await httpTestServer().createEcho("GET", `/malformed-content-encoding-cookie-${method}`, {
status: 200,
- headers: {
- "Access-Control-Allow-Origin": location.origin,
- "Access-Control-Allow-Credentials": "true",
- "Content-Type": "application/json",
- },
+ headers: { "Content-Type": "application/json" },
body: "$HEADERS",
reflect_headers_in_body: true,
- }));
- echoURL.hostname = host;
+ });
const headers = await (await fetch(echoURL, { credentials: "include" })).json();
- const cookie = headers["Cookie"]?.some(value => value.includes("malformedbodycookie=stored"));
+ const cookie = headers["Cookie"]?.some(value => value.includes(`${cookieName}=stored`));
println(`${method} cookie stored: ${!!cookie}`);
} catch (error) {
println(`${method} fetch: ${error.name}`);
diff --git a/Tests/LibWeb/Text/input/Fetch/unsupported-content-encoding-retry-stores-cookies.html b/Tests/LibWeb/Text/input/Fetch/unsupported-content-encoding-retry-stores-cookies.html
index 1b4d2df4859..208350d285d 100644
--- a/Tests/LibWeb/Text/input/Fetch/unsupported-content-encoding-retry-stores-cookies.html
+++ b/Tests/LibWeb/Text/input/Fetch/unsupported-content-encoding-retry-stores-cookies.html
@@ -7,19 +7,16 @@
const COOKIE_NAME = "decodingretrycookie";
promiseTest(async () => {
- const url = new URL(await httpTestServer().createEcho("GET", "/unsupported-content-encoding-retry-stores-cookies", {
+ const url = await httpTestServer().createEcho("GET", "/unsupported-content-encoding-retry-stores-cookies", {
status: 200,
headers: {
- "Access-Control-Allow-Origin": location.origin,
- "Access-Control-Allow-Credentials": "true",
"Content-Encoding": "base64",
"Content-Type": "application/json",
"Set-Cookie": `${COOKIE_NAME}=stored; Path=/`,
},
body: "$HEADERS",
reflect_headers_in_body: true,
- }));
- url.hostname = uniqueLocalhostHostname("unsupported-content-encoding-retry");
+ });
const requestHeaders = await (await fetch(url, { credentials: "include" })).json();
const cookie = requestHeaders["Cookie"]?.find(cookie => cookie.trim().startsWith(`${COOKIE_NAME}=`));
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-back.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-back.html
index afd1097b810..16e0c6598ec 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-back.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-back.html
@@ -12,8 +12,8 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
- document.cookie = "secondLoaded=1; path=/";
- addEventListener("beforeunload", () => { document.cookie = "secondBeforeUnload=1; path=/"; });
+ document.cookie = "secondLoaded=1; path=/; SameSite=None; Secure";
+ addEventListener("beforeunload", () => { document.cookie = "secondBeforeUnload=1; path=/; SameSite=None; Secure"; });
setTimeout(() => history.back(), 0);
<\/script>`,
})
@@ -26,7 +26,7 @@
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
const match = document.cookie.match(/firstVisits=(\\d+)/);
- document.cookie = "firstVisits=" + (match ? Number(match[1]) + 1 : 1) + "; path=/";
+ document.cookie = "firstVisits=" + (match ? Number(match[1]) + 1 : 1) + "; path=/; SameSite=None; Secure";
if (!match)
addEventListener("load", () => setTimeout(() => { location.href = "${secondUrl}"; }, 0));
<\/script>`,
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-navigate.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-navigate.html
index 8057a8a95d4..644b419141a 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-navigate.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/beforeunload-consulted-in-remote-iframe-on-navigate.html
@@ -13,8 +13,8 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
- addEventListener("beforeunload", () => { document.cookie = "grandchildBeforeUnload=1; path=/"; });
- document.cookie = "grandchildLoaded=1; path=/";
+ addEventListener("beforeunload", () => { document.cookie = "grandchildBeforeUnload=1; path=/; SameSite=None; Secure"; });
+ document.cookie = "grandchildLoaded=1; path=/; SameSite=None; Secure";
<\/script>`,
})
);
@@ -23,14 +23,14 @@
const secondUrl = await httpServer.createEcho("GET", "/oop-beforeunload-navigate-second", {
status: 200,
headers: { "Content-Type": "text/html" },
- body: `<!DOCTYPE html><script>document.cookie = "secondLoaded=1; path=/";<\/script>`,
+ body: `<!DOCTYPE html><script>document.cookie = "secondLoaded=1; path=/; SameSite=None; Secure";<\/script>`,
});
const firstUrl = await httpServer.createEcho("GET", "/oop-beforeunload-navigate-first", {
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><iframe src="${grandchildUrl}"></iframe><script>
- addEventListener("beforeunload", () => { document.cookie = "childBeforeUnload=1; path=/"; });
+ addEventListener("beforeunload", () => { document.cookie = "childBeforeUnload=1; path=/; SameSite=None; Secure"; });
addEventListener("message", () => { location.href = "${secondUrl}"; });
<\/script>`,
});
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/embedded-page-cookie-request.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/embedded-page-cookie-request.html
index 53bf327944a..4634d524f4b 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/embedded-page-cookie-request.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/embedded-page-cookie-request.html
@@ -7,9 +7,9 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!doctype html><script>
- document.cookie = "embedded-page-cookie=allowed";
+ document.cookie = "embedded-page-cookie=allowed; SameSite=None; Secure";
const result = document.cookie.includes("embedded-page-cookie=allowed") ? "allowed" : "unavailable";
- document.cookie = "embedded-page-cookie-result=" + result;
+ document.cookie = "embedded-page-cookie-result=" + result + "; SameSite=None; Secure";
<\/script>`,
}));
childUrl.hostname = uniqueLocalhostHostname("embedded-page-cookie");
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/iframe-stays-scriptable-after-its-document-unloads-for-another-process.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/iframe-stays-scriptable-after-its-document-unloads-for-another-process.html
index 7e4970c3d19..d4cef603416 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/iframe-stays-scriptable-after-its-document-unloads-for-another-process.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/iframe-stays-scriptable-after-its-document-unloads-for-another-process.html
@@ -19,7 +19,7 @@
};
const firstUrl = await remoteUrl(
"first",
- `<!DOCTYPE html><script>document.cookie = "loaded=1; path=/";<\/script>`
+ `<!DOCTYPE html><script>document.cookie = "loaded=1; path=/; SameSite=None; Secure";<\/script>`
);
const secondUrl = await remoteUrl("second", "<!DOCTYPE html>second");
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/local-iframe-unloads-before-another-process-hosts-it.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/local-iframe-unloads-before-another-process-hosts-it.html
index e26280a5f10..7de710dfd07 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/local-iframe-unloads-before-another-process-hosts-it.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/local-iframe-unloads-before-another-process-hosts-it.html
@@ -12,8 +12,8 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
- addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/"; });
- document.cookie = "loaded=1; path=/";
+ addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/; SameSite=None; Secure"; });
+ document.cookie = "loaded=1; path=/; SameSite=None; Secure";
<\/script>`,
})
);
@@ -24,7 +24,7 @@
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
const firstUnloaded = internals.hasCookieForURL(${JSON.stringify(firstUrl.href)}, "unloadPing", "1");
- document.cookie = "order=" + (firstUnloaded ? "unload-first" : "activate-first") + "; path=/";
+ document.cookie = "order=" + (firstUnloaded ? "unload-first" : "activate-first") + "; path=/; SameSite=None; Secure";
<\/script>`,
})
);
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-another-process-hosts-it.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-another-process-hosts-it.html
index fe53f76927b..df9e8705765 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-another-process-hosts-it.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-another-process-hosts-it.html
@@ -11,8 +11,8 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
- addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/"; });
- document.cookie = "loaded=1; path=/";
+ addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/; SameSite=None; Secure"; });
+ document.cookie = "loaded=1; path=/; SameSite=None; Secure";
<\/script>`,
})
);
@@ -24,7 +24,7 @@
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
const firstUnloaded = internals.hasCookieForURL(${JSON.stringify(firstUrl.href)}, "unloadPing", "1");
- document.cookie = "order=" + (firstUnloaded ? "unload-first" : "activate-first") + "; path=/";
+ document.cookie = "order=" + (firstUnloaded ? "unload-first" : "activate-first") + "; path=/; SameSite=None; Secure";
<\/script>`,
})
);
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-its-parent-hosts-it.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-its-parent-hosts-it.html
index cda2cb88b7f..2f7fba00434 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-its-parent-hosts-it.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/remote-iframe-unloads-before-its-parent-hosts-it.html
@@ -11,8 +11,8 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
- addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/"; });
- document.cookie = "loaded=1; path=/";
+ addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/; SameSite=None; Secure"; });
+ document.cookie = "loaded=1; path=/; SameSite=None; Secure";
<\/script>`,
})
);
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/removing-remote-iframe-aborts-its-navigation-api.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/removing-remote-iframe-aborts-its-navigation-api.html
index 23faae29510..7bdcb791f70 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/removing-remote-iframe-aborts-its-navigation-api.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/removing-remote-iframe-aborts-its-navigation-api.html
@@ -16,9 +16,9 @@
});
const { finished } = navigation.navigate("#intercepted");
finished
- .catch(error => { document.cookie = "aborted=" + error.name + "; path=/"; })
- .finally(() => { document.cookie = "settled=1; path=/"; });
- document.cookie = "loaded=1; path=/";
+ .catch(error => { document.cookie = "aborted=" + error.name + "; path=/; SameSite=None; Secure"; })
+ .finally(() => { document.cookie = "settled=1; path=/; SameSite=None; Secure"; });
+ document.cookie = "loaded=1; path=/; SameSite=None; Secure";
<\/script>`,
})
);
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-across-processes-on-iframe-removal.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-across-processes-on-iframe-removal.html
index 054c56878ed..abc55674dbf 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-across-processes-on-iframe-removal.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-across-processes-on-iframe-removal.html
@@ -11,8 +11,8 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
- addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/"; });
- document.cookie = "loaded=1; path=/";
+ addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/; SameSite=None; Secure"; });
+ document.cookie = "loaded=1; path=/; SameSite=None; Secure";
<\/script>`,
})
);
@@ -25,9 +25,9 @@
body: `<!DOCTYPE html><script>
addEventListener("unload", () => {
const grandchildUnloaded = internals.hasCookieForURL(${JSON.stringify(grandchildUrl.href)}, "unloadPing", "1");
- document.cookie = "unloadOrder=" + (grandchildUnloaded ? "grandchild-first" : "child-first") + "; path=/";
+ document.cookie = "unloadOrder=" + (grandchildUnloaded ? "grandchild-first" : "child-first") + "; path=/; SameSite=None; Secure";
});
- document.cookie = "loaded=1; path=/";
+ document.cookie = "loaded=1; path=/; SameSite=None; Secure";
<\/script><iframe src="${grandchildUrl}"></iframe>`,
})
);
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-in-remote-iframe-when-parent-navigates.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-in-remote-iframe-when-parent-navigates.html
index 76c88aabc35..6ac60368b41 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-in-remote-iframe-when-parent-navigates.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/unload-runs-in-remote-iframe-when-parent-navigates.html
@@ -11,8 +11,8 @@
status: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html><script>
- addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/"; });
- document.cookie = "loaded=1; path=/";
+ addEventListener("unload", () => { document.cookie = "unloadPing=1; path=/; SameSite=None; Secure"; });
+ document.cookie = "loaded=1; path=/; SameSite=None; Secure";
<\/script>`,
})
);
@@ -23,7 +23,7 @@
await httpServer.createEcho("GET", "/oop-nav-parent-next", {
status: 200,
headers: { "Content-Type": "text/html" },
- body: `<!DOCTYPE html><script>document.cookie = "committed=1; path=/";<\/script>`,
+ body: `<!DOCTYPE html><script>document.cookie = "committed=1; path=/; SameSite=None; Secure";<\/script>`,
})
);
nextParentUrl.hostname = parentHostname;
@@ -38,7 +38,7 @@
body: `<!DOCTYPE html><script>
addEventListener("message", () => { location.href = "${nextParentUrl}"; });
addEventListener("load", () => {
- document.cookie = "shown=1; path=/";
+ document.cookie = "shown=1; path=/; SameSite=None; Secure";
const frame = document.createElement("iframe");
frame.src = "${childUrl}";
document.body.appendChild(frame);
diff --git a/Tests/LibWeb/Text/input/WebSocket/handshake-cookie.html b/Tests/LibWeb/Text/input/WebSocket/handshake-cookie.html
index b8da2072bcd..acce2b94006 100644
--- a/Tests/LibWeb/Text/input/WebSocket/handshake-cookie.html
+++ b/Tests/LibWeb/Text/input/WebSocket/handshake-cookie.html
@@ -5,19 +5,15 @@
// reached through a unique host name so that cookie tests running in parallel cannot delete the cookie.
promiseTest(async () => {
const httpServer = httpTestServer();
- const hostname = uniqueLocalhostHostname("websocket-handshake-cookie");
- const setURL = new URL(await httpServer.createEcho("GET", "/websocket-handshake-cookie-set", {
+ const setURL = await httpServer.createEcho("GET", "/websocket-handshake-cookie-set", {
status: 200,
headers: {
- "Access-Control-Allow-Origin": location.origin,
- "Access-Control-Allow-Credentials": "true",
- "Set-Cookie": "websockethandshakecookie=stored; Path=/; HttpOnly",
+ "Set-Cookie": "websockethandshakecookie=stored; Path=/; HttpOnly; SameSite=Strict",
},
- }));
- setURL.hostname = hostname;
- await fetch(setURL, { credentials: "include" });
+ });
+ await fetch(setURL);
- const ws = new WebSocket(`ws://${hostname}:${internals.getEchoServerPort()}/reflect-websocket-cookie`);
+ const ws = new WebSocket(`ws://${location.host}/reflect-websocket-cookie`);
const cookie = await new Promise(resolve => {
ws.onmessage = e => resolve(e.data);
ws.onerror = () => resolve("error");
diff --git a/Tests/LibWeb/Text/input/cookie-change-events-skip-other-partitions.html b/Tests/LibWeb/Text/input/cookie-change-events-skip-other-partitions.html
index 32c9513d225..ba4526666ef 100644
--- a/Tests/LibWeb/Text/input/cookie-change-events-skip-other-partitions.html
+++ b/Tests/LibWeb/Text/input/cookie-change-events-skip-other-partitions.html
@@ -36,7 +36,7 @@
);
const frameURL = await htmlEcho(
"frame",
- `document.cookie = "partitioned=1; path=/";
+ `document.cookie = "partitioned=1; path=/; SameSite=None; Secure";
parent.postMessage("frame-set-cookie", "*");`
);
diff --git a/Tests/LibWeb/Text/input/cookies-of-a-frame-with-a-cross-site-ancestor-are-partitioned.html b/Tests/LibWeb/Text/input/cookies-of-a-frame-with-a-cross-site-ancestor-are-partitioned.html
index 4d37642b1bc..4985188fd5c 100644
--- a/Tests/LibWeb/Text/input/cookies-of-a-frame-with-a-cross-site-ancestor-are-partitioned.html
+++ b/Tests/LibWeb/Text/input/cookies-of-a-frame-with-a-cross-site-ancestor-are-partitioned.html
@@ -25,7 +25,7 @@
site,
"inner",
`<script>
- document.cookie = "nested=1; path=/";
+ document.cookie = "nested=1; path=/; SameSite=None; Secure";
top.opener.postMessage({ inner: document.cookie }, "*");
<\/script>`
);
diff --git a/Tests/LibWeb/Text/input/document-cookie-uses-the-partition-of-the-asking-document.html b/Tests/LibWeb/Text/input/document-cookie-uses-the-partition-of-the-asking-document.html
index 6f9ebba2ab0..0f6a5fd9b06 100644
--- a/Tests/LibWeb/Text/input/document-cookie-uses-the-partition-of-the-asking-document.html
+++ b/Tests/LibWeb/Text/input/document-cookie-uses-the-partition-of-the-asking-document.html
@@ -24,7 +24,7 @@
const frameURL = await htmlEcho(
"frame",
- `document.cookie = "frame=1; path=/";
+ `document.cookie = "frame=1; path=/; SameSite=None; Secure";
window.addEventListener("message", () => parent.postMessage({ frame: document.cookie }, "*"));
parent.postMessage("frame-ready", "*");`
);
diff --git a/Tests/LibWeb/Text/input/navigation/reload-after-javascript-url-sends-strict-cookies.html b/Tests/LibWeb/Text/input/navigation/reload-after-javascript-url-sends-strict-cookies.html
new file mode 100644
index 00000000000..e8ee5220c62
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigation/reload-after-javascript-url-sends-strict-cookies.html
@@ -0,0 +1,37 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A javascript: URL document keeps the URL of the entry it replaces, so reloading it from the browser fetches that
+ // URL again. The reload is same-site if the replaced document was navigated to same-site, and sends its
+ // SameSite=Strict cookies.
+ async function pageScript() {
+ if (!sessionStorage.getItem("reloaded")) {
+ sessionStorage.setItem("reloaded", "1");
+ document.cookie = "strict=1; SameSite=Strict; Path=/";
+ const reloadDocument = `<body onload="internals.reloadThroughUIProcess()">`;
+ location.href = `javascript:${encodeURIComponent(JSON.stringify(reloadDocument))}`;
+ return;
+ }
+
+ const response = await fetch(`/recorded-request-headers${location.pathname}`, { cache: "no-store" });
+ const headers = Object.fromEntries(
+ Object.entries(await response.json()).map(([name, values]) => [name.toLowerCase(), values])
+ );
+ const sent = (headers["cookie"]?.[0] ?? "").split("; ").includes("strict=1");
+ document.cookie = "strict=; Max-Age=0; Path=/";
+ internals.signalTestIsDone(`Reload sends the SameSite=Strict cookie: ${sent}\n`);
+ }
+
+ asyncTest(async () => {
+ const server = httpTestServer();
+ const pageURL = new URL(
+ await server.createEcho("GET", "/reload-after-javascript-url-sends-strict-cookies", {
+ status: 200,
+ headers: { "Cache-Control": "no-store", "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>(${pageScript})();<\/script>`,
+ })
+ );
+ pageURL.hostname = uniqueLocalhostHostname("reload-after-javascript-url");
+ internals.loadURL(pageURL.href);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/shared-worker-is-not-shared-across-top-level-sites.html b/Tests/LibWeb/Text/input/shared-worker-is-not-shared-across-top-level-sites.html
index a0db9032362..5bcd2466789 100644
--- a/Tests/LibWeb/Text/input/shared-worker-is-not-shared-across-top-level-sites.html
+++ b/Tests/LibWeb/Text/input/shared-worker-is-not-shared-across-top-level-sites.html
@@ -36,7 +36,7 @@
);
// Sets a cookie, then reports the cookies that the shared worker's requests carry.
- const pageScript = cookie => `document.cookie = "${cookie}; path=/";
+ const pageScript = cookie => `document.cookie = "${cookie}; path=/; SameSite=None; Secure";
const worker = new SharedWorker(${JSON.stringify(workerURL)}, "partitioned-worker");
worker.port.onmessage = event => (window.opener ?? window.parent).postMessage({ cookies: event.data }, "*");
worker.port.postMessage("report");`;
diff --git a/Tests/LibWeb/Text/input/third-party-cookies-are-partitioned.html b/Tests/LibWeb/Text/input/third-party-cookies-are-partitioned.html
index 96e2c250cc4..c11ea0b70f9 100644
--- a/Tests/LibWeb/Text/input/third-party-cookies-are-partitioned.html
+++ b/Tests/LibWeb/Text/input/third-party-cookies-are-partitioned.html
@@ -23,7 +23,7 @@
const setFrameCookieURL = onCookieSite(
await server.createEcho("GET", `/partitioned-cookies/${runId}/set-frame-cookie`, {
status: 200,
- headers: { "Set-Cookie": "frame=1; Path=/", "Cache-Control": "no-store" },
+ headers: { "Set-Cookie": "frame=1; Path=/; SameSite=None; Secure", "Cache-Control": "no-store" },
})
);
const setTopLevelCookieURL = onCookieSite(
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/resources/cookie-helper.sub.js b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/cookie-helper.sub.js
new file mode 100644
index 00000000000..15a191c2105
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/cookie-helper.sub.js
@@ -0,0 +1,286 @@
+// Set up exciting global variables for cookie tests.
+(_ => {
+ var HOST = "{{host}}";
+ var INSECURE_PORT = ":{{ports[http][0]}}";
+ var SECURE_PORT = ":{{ports[https][0]}}";
+ var CROSS_ORIGIN_HOST = "{{hosts[alt][]}}";
+
+ window.INSECURE_ORIGIN = "http://" + HOST + INSECURE_PORT;
+
+ //For secure cookie verification
+ window.SECURE_ORIGIN = "https://" + HOST + SECURE_PORT;
+
+ //standard references
+ window.SECURE_SUBDOMAIN_ORIGIN = "https://{{domains[www1]}}" + SECURE_PORT;
+ window.SECURE_CROSS_SITE_ORIGIN = "https://" + CROSS_ORIGIN_HOST + SECURE_PORT;
+ window.CROSS_SITE_HOST = CROSS_ORIGIN_HOST;
+
+ // Set the global cookie name.
+ window.HTTP_COOKIE = "cookie_via_http";
+})();
+
+// A tiny helper which returns the result of fetching |url| with credentials.
+function credFetch(url) {
+ return fetch(url, {"credentials": "include"})
+ .then(response => {
+ if (response.status !== 200) {
+ throw new Error(response.statusText);
+ }
+ return response;
+ });
+}
+
+// Returns a URL on |origin| which redirects to a given absolute URL.
+function redirectTo(origin, url) {
+ return origin + "/cookies/resources/redirectWithCORSHeaders.py?status=307&location=" + encodeURIComponent(url);
+}
+
+// Returns a URL on |origin| which navigates the window to the given URL (by
+// setting window.location).
+function navigateTo(origin, url) {
+ return origin + "/cookies/resources/navigate.html?location=" + encodeURIComponent(url);
+}
+
+// Returns whether a cookie with name `name` with value `value` is in the cookie
+// string (presumably obtained via document.cookie).
+function cookieStringHasCookie(name, value, cookieString) {
+ return new RegExp(`(?:^|; )${name}=${value}(?:$|;)`).test(cookieString);
+}
+
+// Asserts that `document.cookie` contains or does not contain (according to
+// the value of |present|) a cookie named |name| with a value of |value|.
+function assert_dom_cookie(name, value, present) {
+ assert_equals(cookieStringHasCookie(name, value, document.cookie), present, "`" + name + "=" + value + "` in `document.cookie`");
+}
+
+function assert_cookie(origin, obj, name, value, present) {
+ assert_equals(obj[name], present ? value : undefined, "`" + name + "=" + value + "` in request to `" + origin + "`.");
+}
+
+// Remove the cookie named |name| from |origin|, then set it on |origin| anew.
+// If |origin| matches `self.origin`, also assert (via `document.cookie`) that
+// the cookie was correctly removed and reset.
+async function create_cookie(origin, name, value, extras) {
+ alert("Create_cookie: " + origin + "/cookies/resources/drop.py?name=" + name);
+ await credFetch(origin + "/cookies/resources/drop.py?name=" + name);
+ if (origin == self.origin)
+ assert_dom_cookie(name, value, false);
+ await credFetch(origin + "/cookies/resources/set.py?" + name + "=" + value + ";path=/;" + extras);
+ if (origin == self.origin)
+ assert_dom_cookie(name, value, true);
+}
+
+//
+// Prefix-specific test helpers
+//
+window.dom_prefix_counter = 0;
+function set_prefixed_cookie_via_dom_test(options) {
+ promise_test(t => {
+ var name = options.prefix + "prefixtestcookie";
+ erase_cookie_from_js(name, options.params);
+ t.add_cleanup(() => erase_cookie_from_js(name, options.params));
+ var value = "foo" + ++window.dom_prefix_counter;
+ document.cookie = name + "=" + value + ";" + options.params;
+
+ assert_dom_cookie(name, value, options.shouldExistInDOM);
+
+ return credFetch("/cookies/resources/list.py")
+ .then(r => r.json())
+ .then(cookies => assert_equals(cookies[name], options.shouldExistViaHTTP ? value : undefined));
+ }, options.title);
+}
+
+window.http_prefix_counter = 0;
+function set_prefixed_cookie_via_http_test(options) {
+ promise_test(t => {
+ var name = options.prefix + "prefixtestcookie";
+ var value = "bar" + ++window.http_prefix_counter;
+
+ t.add_cleanup(() => {
+ var cookie = name + "=0;expires=" + new Date(0).toUTCString() + ";" +
+ options.params;
+
+ return credFetch(options.origin + "/cookies/resources/set.py?" + cookie);
+ });
+
+ return credFetch(options.origin + "/cookies/resources/set.py?" + name + "=" + value + ";" + options.params)
+ .then(_ => credFetch(options.origin + "/cookies/resources/list.py"))
+ .then(r => r.json())
+ .then(cookies => assert_equals(cookies[name], options.shouldExistViaHTTP ? value : undefined));
+ }, options.title);
+}
+
+//
+// SameSite-specific test helpers:
+//
+
+// status for "network" cookies.
+window.SameSiteStatus = {
+ CROSS_SITE: "cross-site",
+ LAX: "lax",
+ STRICT: "strict"
+};
+// status for "document.cookie".
+window.DomSameSiteStatus = {
+ CROSS_SITE: "cross-site",
+ SAME_SITE: "same-site",
+};
+
+const wait_for_message = (type, origin) => {
+ return new Promise((resolve, reject) => {
+ window.addEventListener('message', e => {
+ if (origin && e.origin != origin) {
+ reject("Message from unexpected origin in wait_for_message:" + e.origin);
+ return;
+ }
+
+ if (e.data.type && e.data.type === type)
+ resolve(e);
+ }, { once: true });
+ });
+};
+
+// Reset SameSite test cookies on |origin|. If |origin| matches `self.origin`, assert
+// (via `document.cookie`) that they were properly removed and reset.
+async function resetSameSiteCookies(origin, value) {
+ let w = window.open(origin + "/cookies/samesite/resources/puppet.html");
+ try {
+ await wait_for_message("READY", origin);
+ w.postMessage({type: "drop", useOwnOrigin: true}, "*");
+ await wait_for_message("drop-complete", origin);
+ if (origin == self.origin) {
+ assert_dom_cookie("samesite_strict", value, false);
+ assert_dom_cookie("samesite_lax", value, false);
+ assert_dom_cookie("samesite_none", value, false);
+ assert_dom_cookie("samesite_unspecified", value, false);
+ }
+
+ w.postMessage({type: "set", value: value, useOwnOrigin: true}, "*");
+ await wait_for_message("set-complete", origin);
+ if (origin == self.origin) {
+ assert_dom_cookie("samesite_strict", value, true);
+ assert_dom_cookie("samesite_lax", value, true);
+ assert_dom_cookie("samesite_none", value, true);
+ assert_dom_cookie("samesite_unspecified", value, true);
+ }
+ } finally {
+ w.close();
+ }
+}
+
+// Given an |expectedStatus| and |expectedValue|, assert the |cookies| contains
+// the proper set of cookie names and values. Expects SameSite-Lax-by-default.
+function verifySameSiteCookieState(expectedStatus, expectedValue, cookies, domCookieStatus) {
+ assert_equals(cookies["samesite_none"], expectedValue, "SameSite=None cookies are always sent.");
+ if (expectedStatus == SameSiteStatus.CROSS_SITE) {
+ assert_not_equals(cookies["samesite_strict"], expectedValue, "SameSite=Strict cookies are not sent with cross-site requests.");
+ assert_not_equals(cookies["samesite_lax"], expectedValue, "SameSite=Lax cookies are not sent with cross-site requests.");
+ assert_not_equals(cookies["samesite_unspecified"], expectedValue, "Unspecified-SameSite cookies are not sent with cross-site requests.");
+ } else if (expectedStatus == SameSiteStatus.LAX) {
+ assert_not_equals(cookies["samesite_strict"], expectedValue, "SameSite=Strict cookies are not sent with lax requests.");
+ assert_equals(cookies["samesite_lax"], expectedValue, "SameSite=Lax cookies are sent with lax requests.");
+ assert_equals(cookies["samesite_unspecified"], expectedValue, "Unspecified-SameSite cookies are are sent with lax requests.")
+ } else if (expectedStatus == SameSiteStatus.STRICT) {
+ assert_equals(cookies["samesite_strict"], expectedValue, "SameSite=Strict cookies are sent with strict requests.");
+ assert_equals(cookies["samesite_lax"], expectedValue, "SameSite=Lax cookies are sent with strict requests.");
+ assert_equals(cookies["samesite_unspecified"], expectedValue, "Unspecified-SameSite cookies are are sent with strict requests.")
+ }
+
+ if (cookies["domcookies"]) {
+ verifyDocumentCookieSameSite(domCookieStatus, expectedValue, cookies['domcookies']);
+ }
+}
+
+function verifyDocumentCookieSameSite(expectedStatus, expectedValue, domcookies) {
+ const cookies = domcookies.split(";")
+ .map(cookie => cookie.trim().split("="))
+ .reduce((obj, cookie) => {
+ obj[cookie[0]] = cookie[1];
+ return obj;
+ }, {});
+
+ if (expectedStatus == DomSameSiteStatus.SAME_SITE) {
+ assert_equals(cookies["samesite_none"], expectedValue, "SameSite=None cookies are always included in document.cookie.");
+ assert_equals(cookies["samesite_unspecified"], expectedValue, "Unspecified-SameSite cookies are always included in document.cookie.");
+ assert_equals(cookies["samesite_strict"], expectedValue, "SameSite=Strict cookies are always included in document.cookie.");
+ assert_equals(cookies["samesite_lax"], expectedValue, "SameSite=Lax cookies are always included in document.cookie.");
+ } else if (expectedStatus == DomSameSiteStatus.CROSS_SITE) {
+ assert_equals(cookies["samesite_none"], expectedValue, "SameSite=None cookies are always included in document.cookie.");
+ assert_not_equals(cookies["samesite_unspecified"], expectedValue, "Unspecified-SameSite cookies are not included in document.cookie when cross-site.");
+ assert_not_equals(cookies["samesite_strict"], expectedValue, "SameSite=Strict cookies are not included in document.cookie when cross-site.");
+ assert_not_equals(cookies["samesite_lax"], expectedValue, "SameSite=Lax cookies are not included in document.cookie when cross-site.");
+ }
+}
+
+//
+// LeaveSecureCookiesAlone-specific test helpers:
+//
+
+window.SecureStatus = {
+ INSECURE_COOKIE_ONLY: "1",
+ BOTH_COOKIES: "2",
+};
+
+//Reset SameSite test cookies on |origin|. If |origin| matches `self.origin`, assert
+//(via `document.cookie`) that they were properly removed and reset.
+function resetSecureCookies(origin, value) {
+return credFetch(origin + "/cookies/resources/dropSecure.py")
+ .then(_ => {
+ if (origin == self.origin) {
+ assert_dom_cookie("alone_secure", value, false);
+ assert_dom_cookie("alone_insecure", value, false);
+ }
+ })
+ .then(_ => {
+ return credFetch(origin + "/cookie/resources/setSecure.py?" + value)
+ })
+}
+
+// Reset SameSite=None test cookies on |origin|. If |origin| matches
+// `self.origin`, assert (via `document.cookie`) that they were properly
+// removed.
+function resetSameSiteNoneCookies(origin, value) {
+ return credFetch(origin + "/cookies/resources/dropSameSiteNone.py")
+ .then(_ => {
+ if (origin == self.origin) {
+ assert_dom_cookie("samesite_none_insecure", value, false);
+ assert_dom_cookie("samesite_none_secure", value, false);
+ }
+ })
+ .then(_ => {
+ return credFetch(origin + "/cookies/resources/setSameSiteNone.py?" + value);
+ })
+}
+
+// Reset test cookies with multiple SameSite attributes on |origin|.
+// If |origin| matches `self.origin`, assert (via `document.cookie`)
+// that they were properly removed.
+function resetSameSiteMultiAttributeCookies(origin, value) {
+ return credFetch(origin + "/cookies/resources/dropSameSiteMultiAttribute.py")
+ .then(_ => {
+ if (origin == self.origin) {
+ assert_dom_cookie("samesite_unsupported", value, false);
+ assert_dom_cookie("samesite_unsupported_none", value, false);
+ assert_dom_cookie("samesite_unsupported_lax", value, false);
+ assert_dom_cookie("samesite_unsupported_strict", value, false);
+ assert_dom_cookie("samesite_none_unsupported", value, false);
+ assert_dom_cookie("samesite_lax_unsupported", value, false);
+ assert_dom_cookie("samesite_strict_unsupported", value, false);
+ assert_dom_cookie("samesite_lax_none", value, false);
+ }
+ })
+ .then(_ => {
+ return credFetch(origin + "/cookies/resources/setSameSiteMultiAttribute.py?" + value);
+ })
+}
+
+//
+// DOM based cookie manipulation APIs
+//
+
+// erase cookie value and set for expiration
+function erase_cookie_from_js(name, params) {
+ document.cookie = `${name}=0; expires=${new Date(0).toUTCString()}; ${params};`;
+ var re = new RegExp("(?:^|; )" + name);
+ assert_equals(re.test(document.cookie), false, "Sanity check: " + name + " has been deleted.");
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/resources/dropSameSite.py b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/dropSameSite.py
new file mode 100644
index 00000000000..a0aa83558db
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/dropSameSite.py
@@ -0,0 +1,13 @@
+from cookies.resources.helpers import makeDropCookie, setNoCacheAndCORSHeaders
+
+def main(request, response):
+ """Respond to `/cookie/same-site/resources/dropSameSite.py by dropping the
+ four cookies set by setSameSiteCookies.py"""
+ headers = setNoCacheAndCORSHeaders(request, response)
+
+ # Expire the cookies, and return a JSON-encoded success code.
+ headers.append(makeDropCookie(b"samesite_strict", False))
+ headers.append(makeDropCookie(b"samesite_lax", False))
+ headers.append(makeDropCookie(b"samesite_none", False))
+ headers.append(makeDropCookie(b"samesite_unspecified", False))
+ return headers, b'{"success": true}'
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/resources/list.py b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/list.py
new file mode 100644
index 00000000000..4cb6639659a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/list.py
@@ -0,0 +1,10 @@
+import json
+from cookies.resources import helpers
+
+from wptserve.utils import isomorphic_decode
+
+def main(request, response):
+ headers = helpers.setNoCacheAndCORSHeaders(request, response)
+ cookies = helpers.readCookies(request)
+ decoded_cookies = {isomorphic_decode(key): isomorphic_decode(val) for key, val in cookies.items()}
+ return headers, json.dumps(decoded_cookies)
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/resources/postToParent.py b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/postToParent.py
new file mode 100644
index 00000000000..43f7d679fbc
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/postToParent.py
@@ -0,0 +1,39 @@
+import json
+from cookies.resources import helpers
+
+from wptserve.utils import isomorphic_decode
+
+def main(request, response):
+ headers = helpers.setNoCacheAndCORSHeaders(request, response)
+ cookies = helpers.readCookies(request)
+ headers.append((b"Content-Type", b"text/html; charset=utf-8"))
+
+ tmpl = u"""
+<!DOCTYPE html>
+<script>
+ var data = %s;
+ data.type = "COOKIES";
+
+ try {
+ data.domcookies = document.cookie;
+ } catch (e) {}
+
+ if (window.parent != window) {
+ window.parent.postMessage(data, "*");
+ if (window.top != window.parent)
+ window.top.postMessage(data, "*");
+ }
+
+
+ if (window.opener)
+ window.opener.postMessage(data, "*");
+
+ window.addEventListener("message", e => {
+ console.log(e);
+ if (e.data == "reload")
+ window.location.reload();
+ });
+</script>
+"""
+ decoded_cookies = {isomorphic_decode(key): isomorphic_decode(val) for key, val in cookies.items()}
+ return headers, tmpl % json.dumps(decoded_cookies)
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/resources/redirectWithCORSHeaders.py b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/redirectWithCORSHeaders.py
new file mode 100644
index 00000000000..0af14da3e9c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/redirectWithCORSHeaders.py
@@ -0,0 +1,22 @@
+from cookies.resources.helpers import setNoCacheAndCORSHeaders
+
+def main(request, response):
+ """Simple handler that causes redirection.
+
+ The request should typically have two query parameters:
+ status - The status to use for the redirection. Defaults to 302.
+ location - The resource to redirect to.
+ """
+ status = 302
+ if b"status" in request.GET:
+ try:
+ status = int(request.GET.first(b"status"))
+ except ValueError:
+ pass
+ headers = setNoCacheAndCORSHeaders(request, response)
+
+ location = request.GET.first(b"location")
+
+ headers.append((b"Location", location))
+
+ return status, headers, b""
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/resources/setSameSite.py b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/setSameSite.py
new file mode 100644
index 00000000000..05f09670887
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/resources/setSameSite.py
@@ -0,0 +1,32 @@
+from cookies.resources.helpers import makeCookieHeader, setNoCacheAndCORSHeaders
+
+from wptserve.utils import isomorphic_encode
+
+def main(request, response):
+ """Respond to `/cookie/set/samesite?{value}` by setting four cookies:
+ 1. `samesite_strict={value};SameSite=Strict;path=/`
+ 2. `samesite_lax={value};SameSite=Lax;path=/`
+ 3. `samesite_none={value};SameSite=None;path=/`
+ 4. `samesite_unspecified={value};path=/`
+ Then navigate to a page that will post a message back to the opener with the set cookies"""
+ headers = setNoCacheAndCORSHeaders(request, response)
+ value = isomorphic_encode(request.url_parts.query)
+
+ headers.append((b"Content-Type", b"text/html; charset=utf-8"))
+ headers.append(makeCookieHeader(b"samesite_strict", value, {b"SameSite":b"Strict", b"path":b"/"}))
+ headers.append(makeCookieHeader(b"samesite_lax", value, {b"SameSite":b"Lax", b"path":b"/"}))
+ # SameSite=None cookies must be Secure.
+ headers.append(makeCookieHeader(b"samesite_none", value, {b"SameSite":b"None", b"path":b"/", b"Secure": b""}))
+ headers.append(makeCookieHeader(b"samesite_unspecified", value, {b"path":b"/"}))
+
+ document = b"""
+<!DOCTYPE html>
+<script>
+ // A same-site navigation, which should attach all cookies including SameSite ones.
+ // This is necessary because this page may have been reached via a cross-site navigation, so
+ // we might not have access to some SameSite cookies from here.
+ window.location = "../samesite/resources/echo-cookies.html";
+</script>
+"""
+
+ return headers, document
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/fetch.https.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/fetch.https.html
new file mode 100644
index 00000000000..ef91f02d92c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/fetch.https.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<meta charset="utf-8"/>
+<meta name="timeout" content="long">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../../cookies/resources/cookie-helper.sub.js"></script>
+<script>
+ function create_test(origin, target, expectedStatus, title) {
+ promise_test(t => {
+ var value = "" + Math.random();
+ return resetSameSiteCookies(origin, value)
+ .then(_ => {
+ return credFetch(target + "/cookies/resources/list.py")
+
+ .then(r => r.json())
+ .then(cookies => verifySameSiteCookieState(expectedStatus, value, cookies, DomSameSiteStatus.SAME_SITE));
+ });
+ }, title);
+ }
+
+ // No redirect:
+ create_test(SECURE_ORIGIN, SECURE_ORIGIN, SameSiteStatus.STRICT, "Same-host fetches are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, SECURE_SUBDOMAIN_ORIGIN, SameSiteStatus.STRICT, "Subdomain fetches are strictly same-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN, SameSiteStatus.CROSS_SITE, "Cross-site fetches are cross-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to same-host:
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_ORIGIN), SameSiteStatus.STRICT, "Same-host redirecting to same-host fetches are strictly same-site");
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_ORIGIN), SameSiteStatus.STRICT, "Subdomain redirecting to same-host fetches are strictly same-site");
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_ORIGIN), SameSiteStatus.CROSS_SITE, "Cross-site redirecting to same-host fetches are cross-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to same-host:
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.STRICT, "Same-host redirecting to subdomain fetches are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.STRICT, "Subdomain redirecting to subdomain fetches are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.CROSS_SITE, "Cross-site redirecting to subdomain fetches are cross-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to cross-site:
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.CROSS_SITE, "Same-host redirecting to cross-site fetches are cross-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.CROSS_SITE, "Subdomain redirecting to cross-site fetches are cross-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.CROSS_SITE, "Cross-site redirecting to cross-site fetches are cross-site");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/form-get-blank.https.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/form-get-blank.https.html
new file mode 100644
index 00000000000..d1719241a1a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/form-get-blank.https.html
@@ -0,0 +1,68 @@
+<!DOCTYPE html>
+<meta charset="utf-8"/>
+<meta name="timeout" content="long">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../../cookies/resources/cookie-helper.sub.js"></script>
+<script>
+ function create_test(origin, target, expectedStatus, title) {
+ promise_test(t => {
+ var value = "" + Math.random();
+ return resetSameSiteCookies(origin, value)
+ .then(_ => {
+ return new Promise((resolve, reject) => {
+ var f = document.createElement('form');
+ f.action = target + "/cookies/resources/postToParent.py";
+ f.target = "_blank";
+ f.method = "GET";
+ f.rel = "opener";
+
+ // If |target| contains a `redir` parameter, extract it, and add it
+ // to the form so it doesn't get dropped in the submission.
+ var url = new URL(f.action);
+ if (url.pathname == "/cookies/resources/redirectWithCORSHeaders.py") {
+ var i = document.createElement("input");
+ i.name = "location";
+ i.type="hidden";
+ i.value = url.searchParams.get("location");
+ f.appendChild(i);
+ }
+
+ var msgHandler = e => {
+ window.removeEventListener("message", msgHandler);
+ e.source.close();
+ try {
+ verifySameSiteCookieState(expectedStatus, value, e.data, DomSameSiteStatus.SAME_SITE);
+ resolve("Popup received the cookie.");
+ } catch (e) {
+ reject(e);
+ }
+ };
+ window.addEventListener("message", msgHandler);
+ document.body.appendChild(f);
+ f.submit();
+ });
+ });
+ }, title);
+ }
+
+ // No redirect:
+ create_test(SECURE_ORIGIN, SECURE_ORIGIN, SameSiteStatus.STRICT, "Same-host top-level form GETs are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, SECURE_SUBDOMAIN_ORIGIN, SameSiteStatus.STRICT, "Subdomain top-level form GETs are strictly same-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN, SameSiteStatus.LAX, "Cross-site top-level form GETs are laxly same-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to same-host:
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_ORIGIN), SameSiteStatus.STRICT, "Same-host redirecting to same-host top-level form GETs are strictly same-site");
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_ORIGIN), SameSiteStatus.STRICT, "Subdomain redirecting to same-host top-level form GETs are strictly same-site");
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_ORIGIN), SameSiteStatus.LAX, "Cross-site redirecting to same-host top-level form GETs are laxly same-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to same-host:
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.STRICT, "Same-host redirecting to subdomain top-level form GETs are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.STRICT, "Subdomain redirecting to subdomain top-level form GETs are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.LAX, "Cross-site redirecting to subdomain top-level form GETs are laxly same-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to cross-site:
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.LAX, "Same-host redirecting to cross-site top-level form GETs are laxly same-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.LAX, "Subdomain redirecting to cross-site top-level form GETs are laxly same-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.LAX, "Cross-site redirecting to cross-site top-level form GETs are laxly same-site");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/form-post-blank.https.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/form-post-blank.https.html
new file mode 100644
index 00000000000..b6d437e9dcd
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/form-post-blank.https.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<meta charset="utf-8"/>
+<meta name="timeout" content="long">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../../cookies/resources/cookie-helper.sub.js"></script>
+<script>
+ function create_test(origin, target, expectedStatus, title) {
+ promise_test(t => {
+ var value = "" + Math.random();
+ return resetSameSiteCookies(origin, value)
+ .then(_ => {
+ return new Promise((resolve, reject) => {
+ var f = document.createElement('form');
+ f.action = target + "/cookies/resources/postToParent.py";
+ f.target = "_blank";
+ f.method = "POST";
+ f.rel = "opener";
+
+ var msgHandler = e => {
+ window.removeEventListener("message", msgHandler);
+ e.source.close();
+ try {
+ verifySameSiteCookieState(expectedStatus, value, e.data, DomSameSiteStatus.SAME_SITE);
+ resolve("Popup received the cookie.");
+ } catch (e) {
+ reject(e);
+ }
+ };
+ window.addEventListener("message", msgHandler);
+ document.body.appendChild(f);
+ f.submit();
+ });
+ });
+ }, title);
+ }
+
+ // No redirect:
+ create_test(SECURE_ORIGIN, SECURE_ORIGIN, SameSiteStatus.STRICT, "Same-host top-level form POSTs are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, SECURE_SUBDOMAIN_ORIGIN, SameSiteStatus.STRICT, "Subdomain top-level form POSTs are strictly same-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN, SameSiteStatus.CROSS_SITE, "Cross-site top-level form POSTs are cross-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to same-host:
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_ORIGIN), SameSiteStatus.STRICT, "Same-host redirecting to same-host top-level form POSTs are strictly same-site");
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_ORIGIN), SameSiteStatus.STRICT, "Subdomain redirecting to same-host top-level form POSTs are strictly same-site");
+ create_test(SECURE_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_ORIGIN), SameSiteStatus.CROSS_SITE, "Cross-site redirecting to same-host top-level form POSTs are cross-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to same-host:
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.STRICT, "Same-host redirecting to subdomain top-level form POSTs are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.STRICT, "Subdomain redirecting to subdomain top-level form POSTs are strictly same-site");
+ create_test(SECURE_SUBDOMAIN_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_SUBDOMAIN_ORIGIN), SameSiteStatus.CROSS_SITE, "Cross-site redirecting to subdomain top-level form POSTs are cross-site");
+
+ // Redirect from {same-host,subdomain,cross-site} to cross-site:
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.CROSS_SITE, "Same-host redirecting to cross-site top-level form POSTs are cross-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_SUBDOMAIN_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.CROSS_SITE, "Subdomain redirecting to cross-site top-level form POSTs are cross-site");
+ create_test(SECURE_CROSS_SITE_ORIGIN, redirectTo(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN), SameSiteStatus.CROSS_SITE, "Cross-site redirecting to cross-site top-level form POSTs are cross-site");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/echo-cookies.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/echo-cookies.html
new file mode 100644
index 00000000000..a1b29b9b03c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/echo-cookies.html
@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<script>
+ if (window.opener)
+ window.opener.postMessage({ type: 'COOKIES_SET', cookies: document.cookie }, '*');
+ if (window.parent !== window)
+ window.parent.postMessage({ type: 'FRAME_COOKIES_SET', cookies: document.cookie }, '*');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/navigate-iframe.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/navigate-iframe.html
new file mode 100644
index 00000000000..98ad6264fab
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/navigate-iframe.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<script src="/cookies/resources/cookie-helper.sub.js"></script>
+<script>
+ window.addEventListener('load', function() {
+ window.opener.postMessage({ type: 'LOADED' }, '*');
+ });
+
+ window.addEventListener('message', function(e) {
+ if (SECURE_ORIGIN !== window.location.origin)
+ return;
+
+ if (e.data.type === "initialize-iframe")
+ window.frames[0].location = e.data.url;
+ if (e.data.type === "navigate-iframe")
+ window.frames[0].postMessage({ type: 'navigate', url: e.data.url }, '*');
+
+ // Relay messages sent by the subframe to the opener.
+ if (e.data.type === 'FRAME_READY')
+ window.opener.postMessage({ type: 'FRAME_READY' }, '*');
+
+ if (e.data.type === 'FRAME_COOKIES_SET')
+ window.opener.postMessage({ type: 'FRAME_COOKIES_SET', cookies: e.data.cookies }, '*');
+ });
+</script>
+<iframe></iframe>
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/navigate.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/navigate.html
new file mode 100644
index 00000000000..88de6dff92e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/navigate.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<script src="/cookies/resources/cookie-helper.sub.js"></script>
+<script>
+ window.addEventListener('load', function() {
+ if (window.opener)
+ window.opener.postMessage({ type: 'READY' }, '*');
+ if (window.parent !== window)
+ window.parent.postMessage({ type: 'FRAME_READY' }, '*');
+ });
+
+ window.addEventListener('message', function(e) {
+ if (e.data.type === "navigate") {
+ window.location = e.data.url;
+ }
+
+ if (e.data.type === "post-form") {
+ var f = document.createElement('form');
+ f.action = e.data.url;
+ f.method = "POST";
+ document.body.appendChild(f);
+ f.submit();
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/puppet.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/puppet.html
new file mode 100644
index 00000000000..6d36132d3a8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/resources/puppet.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<script src="/cookies/resources/cookie-helper.sub.js"></script>
+<script>
+ // Helper to either set or clear some cookies on its own origin, or
+ // (potentially) cross-site on SECURE_ORIGIN.
+ window.onmessage = e => {
+ var originToUse = SECURE_ORIGIN;
+ if (e.data.useOwnOrigin)
+ originToUse = self.origin;
+
+ if (e.data.type === "set") {
+ credFetch(originToUse + "/cookies/resources/setSameSite.py?" + e.data.value)
+ .then(_ => {
+ e.source.postMessage({
+ type: "set-complete",
+ value: e.data.value
+ }, "*");
+ });
+ }
+
+ if (e.data.type === "drop") {
+ credFetch(originToUse + "/cookies/resources/dropSameSite.py")
+ .then(_ => {
+ e.source.postMessage({type: "drop-complete"}, "*");
+ });
+ }
+ };
+
+ window.opener.postMessage({
+ type: "READY"
+ }, "*");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/setcookie-navigation.https.html b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/setcookie-navigation.https.html
new file mode 100644
index 00000000000..7b050e4db26
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/cookies/samesite/setcookie-navigation.https.html
@@ -0,0 +1,81 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<meta name="timeout" content="long">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../../cookies/resources/cookie-helper.sub.js"></script>
+<script>
+ // Asserts that cookies are present or not present (according to `expectation`)
+ // in the cookie string `cookies` with the correct names and value.
+ function assert_cookies_present(cookies, value, expected_cookie_names, expectation) {
+ for (name of expected_cookie_names) {
+ let re = new RegExp("(?:^|; )" + name + "=" + value + "(?:$|;)");
+ let assertion = expectation ? assert_true : assert_false;
+ assertion(re.test(cookies), "`" + name + "=" + value + "` in cookies");
+ }
+ }
+
+ // Navigate from ORIGIN to |origin_to|, expecting the navigation to set SameSite
+ // cookies on |origin_to|.
+ function navigate_test(method, origin_to, title) {
+ promise_test(async function(t) {
+ // The cookies don't need to be cleared on each run because |value| is
+ // a new random value on each run, so on each run we are overwriting and
+ // checking for a cookie with a different random value.
+ let value = "" + Math.random();
+ let url_from = SECURE_ORIGIN + "/cookies/samesite/resources/navigate.html";
+ let url_to = origin_to + "/cookies/resources/setSameSite.py?" + value;
+ var w = window.open(url_from);
+ await wait_for_message('READY', SECURE_ORIGIN);
+ assert_equals(SECURE_ORIGIN, window.origin);
+ assert_equals(SECURE_ORIGIN, w.origin);
+ let command = (method === "POST") ? "post-form" : "navigate";
+ w.postMessage({ type: command, url: url_to }, "*");
+ let message = await wait_for_message('COOKIES_SET', origin_to);
+ let samesite_cookie_names = ['samesite_strict', 'samesite_lax', 'samesite_none', 'samesite_unspecified'];
+ assert_cookies_present(message.data.cookies, value, samesite_cookie_names, true);
+ w.close();
+ }, title);
+ }
+
+ // Opens a page on origin SECURE_ORIGIN containing an iframe on `iframe_origin_from`,
+ // then navigates that iframe to `iframe_origin_to`. Expects that navigation to set
+ // some subset of SameSite cookies.
+ function navigate_iframe_test(iframe_origin_from, iframe_origin_to, cross_site, title) {
+ promise_test(async function(t) {
+ // The cookies don't need to be cleared on each run because |value| is
+ // a new random value on each run, so on each run we are overwriting and
+ // checking for a cookie with a different random value.
+ let value = "" + Math.random();
+ let parent_url = SECURE_ORIGIN + "/cookies/samesite/resources/navigate-iframe.html";
+ let iframe_url_from = iframe_origin_from + "/cookies/samesite/resources/navigate.html";
+ let iframe_url_to = iframe_origin_to + "/cookies/resources/setSameSite.py?" + value;
+ var w = window.open(parent_url);
+ await wait_for_message('LOADED', SECURE_ORIGIN);
+ assert_equals(SECURE_ORIGIN, window.origin);
+ assert_equals(SECURE_ORIGIN, w.origin);
+ // Navigate the frame to its starting location.
+ w.postMessage({ type: 'initialize-iframe', url: iframe_url_from }, '*');
+ await wait_for_message('FRAME_READY', SECURE_ORIGIN);
+ // Have the frame navigate itself, possibly cross-site.
+ w.postMessage({ type: 'navigate-iframe', url: iframe_url_to }, '*');
+ let message = await wait_for_message('FRAME_COOKIES_SET', SECURE_ORIGIN);
+ // Check for the proper cookies.
+ let samesite_none_cookies = ['samesite_none'];
+ let samesite_cookies = ['samesite_strict', 'samesite_lax', 'samesite_unspecified'];
+ assert_cookies_present(message.data.cookies, value, samesite_none_cookies, true);
+ assert_cookies_present(message.data.cookies, value, samesite_cookies, !cross_site);
+ w.close();
+ }, title);
+ }
+
+ navigate_test("GET", SECURE_ORIGIN, "Same-site top-level navigation should be able to set SameSite=* cookies.");
+ navigate_test("GET", SECURE_CROSS_SITE_ORIGIN, "Cross-site top-level navigation should be able to set SameSite=* cookies.");
+ navigate_test("POST", SECURE_ORIGIN, "Same-site top-level POST should be able to set SameSite=* cookies.");
+ navigate_test("POST", SECURE_CROSS_SITE_ORIGIN, "Cross-site top-level POST should be able to set SameSite=* cookies.");
+
+ navigate_iframe_test(SECURE_ORIGIN, SECURE_ORIGIN, false, "Same-site to same-site iframe navigation should be able to set SameSite=* cookies.");
+ navigate_iframe_test(SECURE_CROSS_SITE_ORIGIN, SECURE_ORIGIN, true, "Cross-site to same-site iframe navigation should only be able to set SameSite=None cookies.");
+ navigate_iframe_test(SECURE_ORIGIN, SECURE_CROSS_SITE_ORIGIN, true, "Same-site to cross-site-site iframe navigation should only be able to set SameSite=None cookies.");
+ navigate_iframe_test(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN, true, "Cross-site to cross-site iframe navigation should only be able to set SameSite=None cookies.");
+</script>
diff --git a/Tests/LibWebView/TestBrowserHistoryTraversal.cpp b/Tests/LibWebView/TestBrowserHistoryTraversal.cpp
index 3610e256fc5..7b284fa8459 100644
--- a/Tests/LibWebView/TestBrowserHistoryTraversal.cpp
+++ b/Tests/LibWebView/TestBrowserHistoryTraversal.cpp
@@ -306,7 +306,7 @@ TEST_CASE(browser_history_traversal)
auto cookie_url = URL::Parser::basic_parse("https://example.com/"sv).release_value();
HTTP::Cookie::ParsedCookie cookie { .name = "page-lifecycle"_string, .value = "preserved"_string };
auto& cookie_jar = *client.session().cookie_jar;
- cookie_jar.set_cookie(cookie_url, cookie, HTTP::Cookie::Source::Http, {});
+ cookie_jar.set_cookie(cookie_url, cookie, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
VERIFY(cookie_jar.get_named_cookie(cookie_url, cookie.name).has_value());
auto& stub = static_cast<WebContentClientStub&>(client);
auto new_tab_requests = app->new_tab_requests();
@@ -315,7 +315,7 @@ TEST_CASE(browser_history_traversal)
VERIFY(stub.did_request_cookie(popup_page_id, {}, cookie_url, HTTP::Cookie::Source::Http).cookie().cookie == "page-lifecycle=preserved"sv);
stub.did_request_delete_all_cookies(popup_page_id, 0, cookie_url);
VERIFY(!cookie_jar.get_named_cookie(cookie_url, cookie.name).has_value());
- cookie_jar.set_cookie(cookie_url, cookie, HTTP::Cookie::Source::Http, {});
+ cookie_jar.set_cookie(cookie_url, cookie, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
client.page(popup_page_id)->set_detached_close_pending(true);
popup.clear();
VERIFY(!client.page(popup_page_id));
diff --git a/Tests/LibWebView/TestCookieJar.cpp b/Tests/LibWebView/TestCookieJar.cpp
index b7250e205d0..8b3f718465e 100644
--- a/Tests/LibWebView/TestCookieJar.cpp
+++ b/Tests/LibWebView/TestCookieJar.cpp
@@ -22,7 +22,7 @@ static URL::URL parse_url(StringView url)
static bool stores_cookie(URL::URL const& url, HTTP::Cookie::ParsedCookie cookie, HTTP::Cookie::Source source)
{
auto jar = WebView::CookieJar::create();
- jar->set_cookie(url, cookie, source, {});
+ jar->set_cookie(url, cookie, source, {}, HTTP::Cookie::SameSiteContext::same_site());
return !jar->get_all_cookies().is_empty();
}
@@ -39,7 +39,7 @@ TEST_CASE(cookies_round_trip_on_fresh_database)
.value = "bar"_string,
.expiry_time_from_expires_attribute = UnixDateTime::now() + AK::Duration::from_seconds(3600),
};
- jar->set_cookie(parse_url("https://example.com/"sv), cookie, HTTP::Cookie::Source::Http, {});
+ jar->set_cookie(parse_url("https://example.com/"sv), cookie, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
// The jar flushes dirty cookies to the database on destruction.
}
@@ -52,6 +52,44 @@ TEST_CASE(cookies_round_trip_on_fresh_database)
EXPECT_EQ(cookies[0].value, "bar"_string);
}
+TEST_CASE(same_site_cookie_storage_and_retrieval)
+{
+ using namespace HTTP::Cookie;
+
+ auto url = parse_url("https://example.com/"sv);
+ auto jar = WebView::CookieJar::create();
+ auto strict_cookie = parse_cookie(url, "strict=1; SameSite=Strict; HttpOnly"sv).release_value();
+ auto lax_cookie = parse_cookie(url, "lax=1; SameSite=Lax"sv).release_value();
+ auto default_cookie = parse_cookie(url, "default=1"sv).release_value();
+ auto none_cookie = parse_cookie(url, "none=1; SameSite=None; Secure"sv).release_value();
+
+ SameSiteContext cross_site_fetch { .status = SameSiteStatus::CrossSite, .is_safe_method = true };
+ SameSiteContext cross_site_post { .status = SameSiteStatus::CrossSite, .is_top_level_navigation = true };
+ SameSiteContext cross_site_get { .status = SameSiteStatus::CrossSite, .is_top_level_navigation = true, .is_safe_method = true };
+ SameSiteContext same_site_fetch { .status = SameSiteStatus::SameSite };
+
+ jar->set_cookie(url, strict_cookie, Source::Http, {}, cross_site_fetch);
+ jar->set_cookie(url, lax_cookie, Source::Http, {}, cross_site_fetch);
+ jar->set_cookie(url, default_cookie, Source::NonHttp, {}, cross_site_fetch);
+ jar->set_cookie(url, none_cookie, Source::Http, {}, cross_site_fetch);
+ EXPECT_EQ(jar->get_cookie(url, Source::Http, {}, same_site_fetch), "none=1"_string);
+
+ jar->set_cookie(url, strict_cookie, Source::Http, {}, cross_site_post);
+ jar->set_cookie(url, lax_cookie, Source::Http, {}, cross_site_post);
+ jar->set_cookie(url, default_cookie, Source::Http, {}, cross_site_post);
+ EXPECT_EQ(jar->get_all_cookies().size(), 4uz);
+
+ EXPECT_EQ(jar->get_cookie(url, Source::Http, {}, cross_site_fetch), "none=1"_string);
+ EXPECT_EQ(jar->get_cookie(url, Source::Http, {}, cross_site_post), "none=1"_string);
+ auto navigation_cookies = jar->get_cookie(url, Source::Http, {}, cross_site_get);
+ EXPECT(navigation_cookies.contains("none=1"sv));
+ EXPECT(navigation_cookies.contains("lax=1"sv));
+ EXPECT(navigation_cookies.contains("default=1"sv));
+ EXPECT(!navigation_cookies.contains("strict=1"sv));
+ EXPECT_EQ(jar->get_cookie(url, Source::NonHttp, {}, cross_site_get), "none=1"_string);
+ EXPECT(jar->get_cookie(url, Source::Http, {}, same_site_fetch).contains("strict=1"sv));
+}
+
TEST_CASE(http_cookie_prefixes_require_secure_http_provenance)
{
auto http_url = parse_url("http://attacker.example.com/"sv);
@@ -191,25 +229,25 @@ TEST_CASE(third_party_cookies_are_partitioned_by_top_level_site)
.value = "1"_string,
.path = "/"_string,
};
- jar->set_cookie(url, cookie, HTTP::Cookie::Source::Http, partition_context);
+ jar->set_cookie(url, cookie, HTTP::Cookie::Source::Http, partition_context, HTTP::Cookie::SameSiteContext::same_site());
};
set_cookie("embedded"sv, first_top_level_site);
set_cookie("first-party"sv, widget_site);
set_cookie("nested"sv, widget_site_with_cross_site_ancestor);
- EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, first_top_level_site), "embedded=1"_string);
- EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, second_top_level_site), String {});
- EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, widget_site), "first-party=1"_string);
+ EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, first_top_level_site, HTTP::Cookie::SameSiteContext::same_site()), "embedded=1"_string);
+ EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, second_top_level_site, HTTP::Cookie::SameSiteContext::same_site()), String {});
+ EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, widget_site, HTTP::Cookie::SameSiteContext::same_site()), "first-party=1"_string);
// A context with a cross-site ancestor is third-party even under a top-level document of its own site.
- EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, widget_site_with_cross_site_ancestor), "nested=1"_string);
+ EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, widget_site_with_cross_site_ancestor, HTTP::Cookie::SameSiteContext::same_site()), "nested=1"_string);
// A context of nothing is a first-party context, as for the UI process's own requests.
- EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, {}), "first-party=1"_string);
+ EXPECT_EQ(jar->get_cookie(url, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site()), "first-party=1"_string);
// A WebSocket handshake to the widget's site is a first-party request under the widget's top-level documents.
- EXPECT_EQ(jar->get_cookie(parse_url("wss://widget.example/"sv), HTTP::Cookie::Source::Http, widget_site), "first-party=1"_string);
+ EXPECT_EQ(jar->get_cookie(parse_url("wss://widget.example/"sv), HTTP::Cookie::Source::Http, widget_site, HTTP::Cookie::SameSiteContext::same_site()), "first-party=1"_string);
auto cookies = jar->get_all_cookies();
EXPECT_EQ(cookies.size(), 3uz);
@@ -237,7 +275,7 @@ TEST_CASE(host_only_cookie_is_stored_apart_from_domain_cookie_for_same_host)
.domain = move(domain),
.path = "/"_string,
};
- jar.set_cookie(url, cookie, HTTP::Cookie::Source::NonHttp, {});
+ jar.set_cookie(url, cookie, HTTP::Cookie::Source::NonHttp, {}, HTTP::Cookie::SameSiteContext::same_site());
};
auto values = [](WebView::CookieJar& jar) {
Vector<String> values;
@@ -264,6 +302,6 @@ TEST_CASE(host_only_cookie_is_stored_apart_from_domain_cookie_for_same_host)
.domain = "www.example.com"_string,
.path = "/"_string,
};
- jar->set_cookie(url, expired_cookie, HTTP::Cookie::Source::NonHttp, {});
+ jar->set_cookie(url, expired_cookie, HTTP::Cookie::Source::NonHttp, {}, HTTP::Cookie::SameSiteContext::same_site());
EXPECT_EQ(values(*jar), Vector { "host-only"_string });
}
diff --git a/Tests/LibWebView/TestDownloadStore.cpp b/Tests/LibWebView/TestDownloadStore.cpp
index f16ca61ac0f..ac80e3f5dc0 100644
--- a/Tests/LibWebView/TestDownloadStore.cpp
+++ b/Tests/LibWebView/TestDownloadStore.cpp
@@ -35,6 +35,7 @@ static WebView::DownloadRecord example_download(i64 id = 7)
.created_time = UnixDateTime::from_seconds_since_epoch(1000),
.can_restart_from_zero = true,
.may_replace_destination = true,
+ .same_site_context = { .status = HTTP::Cookie::SameSiteStatus::CrossSite, .is_top_level_navigation = true, .is_safe_method = true },
};
}
@@ -60,6 +61,9 @@ TEST_CASE(downloads_round_trip)
EXPECT_EQ(download.created_time, UnixDateTime::from_seconds_since_epoch(1000));
EXPECT(download.can_restart_from_zero);
EXPECT(download.may_replace_destination);
+ EXPECT_EQ(download.same_site_context.status, HTTP::Cookie::SameSiteStatus::CrossSite);
+ EXPECT(download.same_site_context.is_top_level_navigation);
+ EXPECT(download.same_site_context.is_safe_method);
EXPECT_EQ(download.segments.size(), 2u);
EXPECT_EQ(download.segments[0].start_offset, 0u);
diff --git a/Tests/LibWebView/TestFileDownloader.cpp b/Tests/LibWebView/TestFileDownloader.cpp
index d6647960831..587c2ecae9f 100644
--- a/Tests/LibWebView/TestFileDownloader.cpp
+++ b/Tests/LibWebView/TestFileDownloader.cpp
@@ -15,12 +15,14 @@
#include <LibCore/File.h>
#include <LibCore/System.h>
#include <LibCore/Timer.h>
+#include <LibHTTP/Cookie/ParsedCookie.h>
#include <LibRequests/Request.h>
#include <LibRequests/RequestClient.h>
#include <LibTest/TestCase.h>
#include <LibThreading/Thread.h>
#include <LibURL/Parser.h>
#include <LibWebView/Application.h>
+#include <LibWebView/CookieJar.h>
#include <LibWebView/FileDownloader.h>
#include <signal.h>
#include <stdlib.h>
@@ -114,6 +116,12 @@ public:
return m_request_count;
}
+ Vector<ByteString> request_cookies()
+ {
+ MutexLocker locker { m_mutex };
+ return m_request_cookies;
+ }
+
size_t refused_count()
{
MutexLocker locker { m_mutex };
@@ -160,9 +168,12 @@ private:
}
Optional<ByteString> range_header;
+ ByteString cookie_header;
for (auto line : request.string_view().split_view("\r\n"sv)) {
if (line.starts_with("Range:"sv, CaseSensitivity::CaseInsensitive))
range_header = line.substring_view(6).trim_whitespace();
+ else if (line.starts_with("Cookie:"sv, CaseSensitivity::CaseInsensitive))
+ cookie_header = line.substring_view(7).trim_whitespace();
}
{
@@ -170,6 +181,7 @@ private:
++m_request_count;
if (range_header.has_value())
m_range_requests.append(*range_header);
+ m_request_cookies.append(move(cookie_header));
}
if (range_header.has_value() && m_range_request_behavior != RangeRequestBehavior::Serve) {
@@ -291,6 +303,7 @@ private:
Mutex m_mutex;
Vector<ByteString> m_range_requests;
+ Vector<ByteString> m_request_cookies;
size_t m_request_count { 0 };
size_t m_refused_count { 0 };
};
@@ -403,7 +416,7 @@ void expect_request_can_be_released_from_finish_callback(TestHttpServer& server,
auto url = URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/file", server.port()));
VERIFY(url.has_value());
- auto request = MUST(WebView::Application::request_server_client())->start_request("GET"sv, *url);
+ auto request = MUST(WebView::Application::request_server_client())->start_request("GET"sv, *url, HTTP::Cookie::SameSiteContext::same_site());
VERIFY(request);
size_t delivered_size = 0;
@@ -440,7 +453,7 @@ void expect_request_can_be_exported_from_headers_callback(TestHttpServer& server
auto url = URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/file", server.port()));
VERIFY(url.has_value());
- auto request = request_client.start_request("GET"sv, *url, {}, {}, HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::Yes);
+ auto request = request_client.start_request("GET"sv, *url, HTTP::Cookie::SameSiteContext::same_site(), {}, {}, HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::Yes);
VERIFY(request);
size_t delivered_size = 0;
@@ -489,7 +502,7 @@ void expect_leased_request_is_torn_down_when_transferred_after_finishing(TestHtt
auto url = URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/file", server.port()));
VERIFY(url.has_value());
- auto request = request_client.start_request("GET"sv, *url, {}, {}, HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::Yes);
+ auto request = request_client.start_request("GET"sv, *url, HTTP::Cookie::SameSiteContext::same_site(), {}, {}, HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::Yes);
VERIFY(request);
bool finished = false;
@@ -553,6 +566,48 @@ void expect_leased_request_is_torn_down_when_transferred_after_finishing(TestHtt
VERIFY(delivered_size == expected_body_size);
}
+ByteString run_adopted_cross_site_download(TestHttpServer& server, StringView destination_directory, ByteBuffer const& body)
+{
+ auto& request_client = *MUST(WebView::Application::request_server_client());
+ auto url = URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/file", server.port()));
+ VERIFY(url.has_value());
+
+ auto& cookie_jar = *WebView::Application::default_session().cookie_jar;
+ for (auto cookie_string : { "strict=1; SameSite=Strict"sv, "lax=1; SameSite=Lax"sv }) {
+ auto cookie = HTTP::Cookie::parse_cookie(*url, cookie_string);
+ VERIFY(cookie.has_value());
+ cookie_jar.set_cookie(*url, *cookie, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
+ }
+
+ HTTP::Cookie::SameSiteContext cross_site_navigation { .status = HTTP::Cookie::SameSiteStatus::CrossSite, .is_top_level_navigation = true, .is_safe_method = true };
+ auto request = request_client.start_request("GET"sv, *url, cross_site_navigation, {}, {}, HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials::Yes, Requests::RequestClient::TransferLease::Yes);
+ VERIFY(request);
+
+ bool received_headers = false;
+ request->set_body_delivery_paused(true);
+ request->set_unbuffered_request_callbacks(
+ [&](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Requests::CacheState) {
+ received_headers = true;
+ },
+ [](Requests::ResponseData) {
+ },
+ [](Core::ImmutableBytes) {
+ },
+ [](u64, Requests::RequestTimingInfo const&, Optional<Requests::NetworkError>) {
+ });
+ Core::EventLoop::current().spin_until([&] { return received_headers; });
+
+ DownloadWatcher watcher;
+ auto destination = LexicalPath::join(destination_directory, "adopted-cross-site.bin"sv);
+ auto download_id = WebView::Application::the().file_downloader().adopt_download(WebView::IsPrivate::No, *url, destination, body.size(), cross_site_navigation, request_client.request_server_client_id(), request->id());
+ watcher.watch(download_id);
+
+ Core::EventLoop::current().spin_until([&] { return watcher.is_finished(); });
+ VERIFY(watcher.status() == WebView::FileDownloader::DownloadStatus::Completed);
+
+ return destination.string();
+}
+
}
TEST_CASE(file_downloader)
@@ -763,6 +818,20 @@ TEST_CASE(file_downloader)
VERIFY(server.request_count() <= 8);
}
+ {
+ TestHttpServer server { body, RangeSupport::Yes };
+
+ auto path = run_adopted_cross_site_download(server, test_directory, body);
+ expect_file_matches(path, body.bytes());
+
+ // Requests the downloader makes itself send what the cross-site navigation sent.
+ auto request_cookies = server.request_cookies();
+ outln("adopted cross-site: {} requests, {} of them ranged", request_cookies.size(), server.range_requests().size());
+ VERIFY(!server.range_requests().is_empty());
+ for (auto const& cookies : request_cookies)
+ VERIFY(cookies == "lax=1"sv);
+ }
+
{
TestHttpServer server { body, RangeSupport::Yes, RangeRequestBehavior::Serve, Validator::No };
diff --git a/Tests/LibWebView/TestProfile.cpp b/Tests/LibWebView/TestProfile.cpp
index e980437a580..9f2ffff2112 100644
--- a/Tests/LibWebView/TestProfile.cpp
+++ b/Tests/LibWebView/TestProfile.cpp
@@ -204,7 +204,7 @@ TEST_CASE(profile_databases_are_isolated)
.value = "first"_string,
.expiry_time_from_expires_attribute = UnixDateTime::now() + AK::Duration::from_seconds(3600),
};
- cookie_jar->set_cookie(url, cookie, HTTP::Cookie::Source::Http, {});
+ cookie_jar->set_cookie(url, cookie, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
auto hsts_store = TRY_OR_FAIL(WebView::HSTSStore::create(*database));
hsts_store->store_policy("profile-isolation.example"_string, HTTP::HSTS::ParsedHSTSPolicy { AK::Duration::from_seconds(3600), false });
diff --git a/Tests/LibWebView/TestRendererCookieAccess.cpp b/Tests/LibWebView/TestRendererCookieAccess.cpp
index 970c7f299f8..303dc121e2e 100644
--- a/Tests/LibWebView/TestRendererCookieAccess.cpp
+++ b/Tests/LibWebView/TestRendererCookieAccess.cpp
@@ -81,13 +81,13 @@ TEST_CASE(renderer_cookie_access)
auto view = create_view();
auto& cookie_jar = *view->page().client().session().cookie_jar;
- cookie_jar.set_cookie(victim_url, HTTP::Cookie::ParsedCookie { .name = "session"_string, .value = "secret"_string, .http_only_attribute_present = true }, HTTP::Cookie::Source::Http, {});
+ cookie_jar.set_cookie(victim_url, HTTP::Cookie::ParsedCookie { .name = "session"_string, .value = "secret"_string, .http_only_attribute_present = true }, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
VERIFY(victim_cookie_value(cookie_jar) == "secret"sv);
// Script reaches cookies through a document the process hosts, and only those of such a document's origin. Any
// other access sees and changes nothing, but is not misbehavior: a document can outlive the UI process's record
// of it.
- cookie_jar.set_cookie(victim_url, HTTP::Cookie::ParsedCookie { .name = "visible"_string, .value = "secret"_string }, HTTP::Cookie::Source::Http, {});
+ cookie_jar.set_cookie(victim_url, HTTP::Cookie::ParsedCookie { .name = "visible"_string, .value = "secret"_string }, HTTP::Cookie::Source::Http, {}, HTTP::Cookie::SameSiteContext::same_site());
auto& stub = static_cast<WebContentClientStub&>(view->page().client());
auto page_id = view->page().id();
auto page_environment_id = view->traversable().active_document().relevant_global_object().relevant_settings_object().id();
diff --git a/Tests/RequestServer/TestContentCodingRetry.cpp b/Tests/RequestServer/TestContentCodingRetry.cpp
index f6258da81a7..2c34d8cf117 100644
--- a/Tests/RequestServer/TestContentCodingRetry.cpp
+++ b/Tests/RequestServer/TestContentCodingRetry.cpp
@@ -105,7 +105,7 @@ TEST_CASE(content_coding_retry_keeps_client_supplied_cookie_header)
UnsupportedCodingServer server;
auto message = make<Messages::RequestServer::StartRequest>(
0, ByteString { "GET" }, server.url(), Vector<HTTP::Header> { { "Cookie", "supplied=by-the-client" } }, ByteBuffer {},
- HTTP::CacheMode::NoStore, Optional<HTTP::NetworkIsolationKey> {}, HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0);
+ HTTP::CacheMode::NoStore, Optional<HTTP::NetworkIsolationKey> {}, HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0, HTTP::Cookie::SameSiteContext {});
VERIFY(!MUST(static_cast<RequestServerEndpoint::Stub&>(*connection).handle(move(message))));
event_loop.spin_until([&] { return server.request_heads().size() >= 2; });
diff --git a/Tests/RequestServer/TestCookieResponses.cpp b/Tests/RequestServer/TestCookieResponses.cpp
index b70b9fdae81..fb3bb06a544 100644
--- a/Tests/RequestServer/TestCookieResponses.cpp
+++ b/Tests/RequestServer/TestCookieResponses.cpp
@@ -169,14 +169,14 @@ public:
void start_request(u64 request_id, Optional<URL::URL> target_url = {}, ByteString method = "GET"sv, Vector<HTTP::Header> headers = {}, Optional<HTTP::NetworkIsolationKey> network_isolation_key = {})
{
auto url = target_url.value_or(URL::Parser::basic_parse("http://localhost"sv).release_value());
- auto message = make<Messages::RequestServer::StartRequest>(request_id, move(method), move(url), move(headers), ByteBuffer {}, HTTP::CacheMode::Default, move(network_isolation_key), HTTP::Cookie::IncludeCredentials::Yes, true, Optional<u32> {}, false, 0, 0);
+ auto message = make<Messages::RequestServer::StartRequest>(request_id, move(method), move(url), move(headers), ByteBuffer {}, HTTP::CacheMode::Default, move(network_isolation_key), HTTP::Cookie::IncludeCredentials::Yes, true, Optional<u32> {}, false, 0, 0, HTTP::Cookie::SameSiteContext {});
auto response = dispatch(move(message));
VERIFY(!response);
}
void websocket_connect(u64 websocket_id, URL::URL url, ByteString origin = "http://localhost"sv, Vector<ByteString> protocols = {}, Vector<HTTP::Header> headers = {})
{
- auto message = make<Messages::RequestServer::WebsocketConnect>(websocket_id, move(url), Optional<HTTP::NetworkIsolationKey> {}, move(origin), move(protocols), Vector<ByteString> {}, move(headers));
+ auto message = make<Messages::RequestServer::WebsocketConnect>(websocket_id, move(url), Optional<HTTP::NetworkIsolationKey> {}, move(origin), move(protocols), Vector<ByteString> {}, move(headers), HTTP::Cookie::SameSiteContext {});
auto response = dispatch(move(message));
VERIFY(!response);
}
diff --git a/Tests/RequestServer/TestDiskCacheWaiters.cpp b/Tests/RequestServer/TestDiskCacheWaiters.cpp
index ab0f027f3a1..dfd3e9be469 100644
--- a/Tests/RequestServer/TestDiskCacheWaiters.cpp
+++ b/Tests/RequestServer/TestDiskCacheWaiters.cpp
@@ -249,7 +249,7 @@ public:
{ ByteString { HTTP::TEST_CACHE_ENABLED_HEADER }, "1"sv },
};
- auto message = make<Messages::RequestServer::StartRequest>(request_id, move(method), move(url), move(request_headers), ByteBuffer {}, HTTP::CacheMode::Default, test_network_isolation_key(), HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0);
+ auto message = make<Messages::RequestServer::StartRequest>(request_id, move(method), move(url), move(request_headers), ByteBuffer {}, HTTP::CacheMode::Default, test_network_isolation_key(), HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0, HTTP::Cookie::SameSiteContext {});
auto response = MUST(static_cast<RequestServerEndpoint::Stub&>(*m_connection).handle(move(message)));
VERIFY(!response);
}
diff --git a/Tests/RequestServer/TestExportImport.cpp b/Tests/RequestServer/TestExportImport.cpp
index fbc03bf01b1..374e3253e52 100644
--- a/Tests/RequestServer/TestExportImport.cpp
+++ b/Tests/RequestServer/TestExportImport.cpp
@@ -92,7 +92,7 @@ public:
void start_request(u64 request_id, URL::URL url, HTTP::NetworkIsolationKey network_isolation_key, bool create_transfer_lease)
{
- auto message = make<Messages::RequestServer::StartRequest>(request_id, ByteString { "GET" }, move(url), cacheable_request_headers(), ByteBuffer {}, HTTP::CacheMode::Default, move(network_isolation_key), HTTP::Cookie::IncludeCredentials::No, create_transfer_lease, Optional<u32> {}, false, 0, 0);
+ auto message = make<Messages::RequestServer::StartRequest>(request_id, ByteString { "GET" }, move(url), cacheable_request_headers(), ByteBuffer {}, HTTP::CacheMode::Default, move(network_isolation_key), HTTP::Cookie::IncludeCredentials::No, create_transfer_lease, Optional<u32> {}, false, 0, 0, HTTP::Cookie::SameSiteContext {});
VERIFY(!dispatch(move(message)));
}
diff --git a/Tests/RequestServer/TestRequestTimingInfo.cpp b/Tests/RequestServer/TestRequestTimingInfo.cpp
index 6dc9f407a50..a91ae8ff129 100644
--- a/Tests/RequestServer/TestRequestTimingInfo.cpp
+++ b/Tests/RequestServer/TestRequestTimingInfo.cpp
@@ -139,7 +139,7 @@ public:
auto started_at = MonotonicTime::now();
m_started_at.set(request_id, started_at);
- auto message = make<Messages::RequestServer::StartRequest>(request_id, ByteString { "GET" }, move(url), Vector<HTTP::Header> {}, ByteBuffer {}, HTTP::CacheMode::Default, Optional<HTTP::NetworkIsolationKey> {}, HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0);
+ auto message = make<Messages::RequestServer::StartRequest>(request_id, ByteString { "GET" }, move(url), Vector<HTTP::Header> {}, ByteBuffer {}, HTTP::CacheMode::Default, Optional<HTTP::NetworkIsolationKey> {}, HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0, HTTP::Cookie::SameSiteContext {});
auto response = MUST(static_cast<RequestServerEndpoint::Stub&>(*m_connection).handle(move(message)));
VERIFY(!response);
diff --git a/Tests/RequestServer/TestSiteBinding.cpp b/Tests/RequestServer/TestSiteBinding.cpp
index 55f6e45f8b9..7b41eae9b80 100644
--- a/Tests/RequestServer/TestSiteBinding.cpp
+++ b/Tests/RequestServer/TestSiteBinding.cpp
@@ -80,7 +80,7 @@ struct TestServer {
{
auto message = make<Messages::RequestServer::StartRequest>(
request_id, ByteString { "GET" }, URL::Parser::basic_parse(url).release_value(), Vector<HTTP::Header> {}, ByteBuffer {},
- HTTP::CacheMode::NoStore, network_isolation_key, HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0);
+ HTTP::CacheMode::NoStore, network_isolation_key, HTTP::Cookie::IncludeCredentials::No, false, Optional<u32> {}, false, 0, 0, HTTP::Cookie::SameSiteContext {});
VERIFY(!MUST(static_cast<RequestServerEndpoint::Stub&>(*connection).handle(move(message))));
}