Truly independent web browser
LibWeb: Use the HTTP cache without revalidation on history traversal
Andreas Klingd447854b26de
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 43c1e79da0c..90c551c4019 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -632,7 +632,15 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type|| navigation_params.request->text_directive_user_activation();navigation_params.request->set_text_directive_user_activation(false);document->m_browsing_context_group_has_remote_contexts = navigation_params.request->browsing_context_group_has_multiple_contexts();- document->m_navigation_bypassed_cache = navigation_params.request->cache_mode() == HTTP::CacheMode::Reload;+ if (auto cache_mode = navigation_params.request->cache_mode(); cache_mode == HTTP::CacheMode::Reload || cache_mode == HTTP::CacheMode::ForceCache)+ document->m_navigation_cache_mode = cache_mode;+ }++ // AD-HOC: A document that is not fetched, such as the one of a srcdoc iframe, loads the way its container document+ // does. Its requests use the same cache mode while it loads.+ if (!navigation_params.request) {+ if (auto container_document = navigation_params.navigable->container_document())+ document->m_navigation_cache_mode = container_document->cache_mode_while_loading();}// NOTE: Step 16 is treated as the else branch of step 15. Otherwise, redirectCount is undefined when the fetch@@ -6593,6 +6601,10 @@ void Document::abort()bool canceled_fetch = HTML::stop_body_delivery(m_ongoing_navigation_fetch);m_ongoing_navigation_fetch = Empty {};+ // NB: An aborted document may never become completely loaded. Its load is over, so the requests it makes from now+ // on must not use the cache mode of its navigation anymore.+ m_navigation_cache_mode = HTTP::CacheMode::Default;+auto cancel_fetch = [&](GC::Ptr<Fetch::Infrastructure::FetchController> controller) {if (!controller || controller->state() != Fetch::Infrastructure::FetchController::State::Ongoing)return;diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 27ecd9af068..11cb8803c7a 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -30,6 +30,7 @@#include <LibGC/Weak.h>#include <LibGC/WeakHashSet.h>#include <LibGfx/Point.h>+#include <LibHTTP/Cache/CacheMode.h>#include <LibJS/Forward.h>#include <LibURL/Origin.h>#include <LibURL/URL.h>@@ -955,10 +956,12 @@ public:bool browsing_context_group_has_multiple_contexts() const;bool browsing_context_group_has_remote_contexts() const { return m_browsing_context_group_has_remote_contexts; }- // AD-HOC: Whether this document is still loading after a navigation that bypassed the HTTP cache: a reload that- // bypasses it, or a child navigable's navigation while its container document loaded that way. Until it- // has completely loaded, the requests it makes without a cache mode of their own bypass the cache too.- bool is_loading_bypassing_cache() const { return m_navigation_bypassed_cache && !is_completely_loaded(); }+ // AD-HOC: The cache mode of the navigation that created this document, if that was a navigation that bypassed the+ // HTTP cache ("reload") or one that used it without revalidation ("force-cache"): a reload that bypasses+ // the cache, a history traversal, or a child navigable's navigation while its container document loaded+ // that way. Until the document has completely loaded, the requests it makes without a cache mode of their+ // own use this cache mode too. Otherwise, this is "default".+ HTTP::CacheMode cache_mode_while_loading() const { return is_completely_loaded() ? HTTP::CacheMode::Default : m_navigation_cache_mode; }GC::Ptr<Element> current_script() const { return m_current_script; }Variant<GC::Ref<HTML::HTMLScriptElement>, GC::Ref<SVG::SVGScriptElement>, Empty> current_script_for_bindings() const;@@ -2141,7 +2144,7 @@ private:// Each Document has a text directive user activation, which is a boolean, initially false.bool m_text_directive_user_activation { false };bool m_browsing_context_group_has_remote_contexts { false };- bool m_navigation_bypassed_cache { false };+ HTTP::CacheMode m_navigation_cache_mode { HTTP::CacheMode::Default };GC::Ptr<Element> m_current_script;u32 m_ignore_destructive_writes_counter { 0 };diff --git a/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cpp b/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cppindex f85bb9c7514..913e703b3c9 100644--- a/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/ClientContextSnapshots.cpp@@ -140,7 +140,7 @@ NonnullRefPtr<Infrastructure::ClientContextSnapshot const> snapshot_client_conte.cross_origin_isolated_capability = client.cross_origin_isolated_capability(),.is_secure_context = HTML::is_secure_context(client) ? Context::IsSecureContext::Yes : Context::IsSecureContext::No,.prohibits_mixed_security_contexts = MixedContent::does_settings_prohibit_mixed_security_contexts(client),- .is_loading_bypassing_cache = window && window->associated_document().is_loading_bypassing_cache() ? Context::IsLoadingBypassingCache::Yes : Context::IsLoadingBypassingCache::No,+ .cache_mode_while_loading = window ? window->associated_document().cache_mode_while_loading() : HTTP::CacheMode::Default,.time_origin = client.time_origin(),.navigable_id = navigable ? navigable->id() : Optional<HTML::CrossProcessId> {},.referrer_source = referrer_source_of_client(client),@@ -159,7 +159,7 @@ NonnullRefPtr<Infrastructure::ClientContextSnapshot const> snapshot_client_conte? window->associated_document.relevant_settings_object_is_secure_context: settings.global.get<HTML::SerializedWorkerGlobalScope>().relevant_settings_object_is_secure_context;- // NB: A client another process hosts is never treated as loading bypassing the HTTP cache.+ // NB: A client another process hosts is never treated as loading with the cache mode of its navigation.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,diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex fc15fb37761..68ed200398b 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -2557,12 +2557,12 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastruhttp_request->set_cache_mode(HTTP::CacheMode::NoStore);}- // AD-HOC: While a document loads bypassing the HTTP cache, so do the requests it makes without a cache mode of- // their own, as do its child navigables' navigations (see create navigation params by fetching).+ // AD-HOC: While a document loads after a navigation that bypassed the HTTP cache, or one that used the cache+ // without revalidation, the requests it makes without a cache mode of their own do the same, as do its+ // child navigables' navigations (see create navigation params by fetching).if (http_request->cache_mode() == HTTP::CacheMode::Default && http_request->mode() != Infrastructure::Request::Mode::Navigate) {- auto const& client_snapshot = http_request->client_snapshot();- if (client_snapshot && client_snapshot->is_loading_bypassing_cache == Infrastructure::ClientContext::IsLoadingBypassingCache::Yes)- http_request->set_cache_mode(HTTP::CacheMode::Reload);+ if (auto const& client_snapshot = http_request->client_snapshot())+ http_request->set_cache_mode(client_snapshot->cache_mode_while_loading);}// 17. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent no-cache cache-control headerdiff --git a/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h b/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.hindex 98c56553196..c8b37b3caba 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/ClientContextSnapshot.h@@ -9,6 +9,7 @@#include <AK/AtomicRefCounted.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>+#include <LibHTTP/Cache/CacheMode.h>#include <LibURL/Origin.h>#include <LibURL/URL.h>#include <LibWeb/Export.h>@@ -43,12 +44,6 @@ struct ClientContext {Yes,};- // Whether the global object is a Window whose associated Document is loading bypassing the HTTP cache.- enum class IsLoadingBypassingCache : u8 {- No,- Yes,- };-URL::Origin origin;URL::Origin site_for_cookies;URL::URL creation_url;@@ -60,7 +55,10 @@ struct ClientContext {HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability { HTML::CanUseCrossOriginIsolatedAPIs::No };IsSecureContext is_secure_context { IsSecureContext::No };MixedContent::ProhibitsMixedSecurityContexts prohibits_mixed_security_contexts { MixedContent::ProhibitsMixedSecurityContexts::DoesNotRestrictMixedSecurityContexts };- IsLoadingBypassingCache is_loading_bypassing_cache { IsLoadingBypassingCache::No };++ // The cache mode while loading of the associated Document, if the global object is a Window.+ HTTP::CacheMode cache_mode_while_loading { HTTP::CacheMode::Default };+double time_origin { 0 };// The navigable of the Window that is the global object, if it has one and this process hosts the Window.diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex e7e03e2a8b1..2008ecb2ed5 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -2723,13 +2723,26 @@ static void create_navigation_params_by_fetching(}// 8. Otherwise, if entry's document state's ever populated is true, then set request's history-navigation flag.- else if (document_state.ever_populated)+ else if (document_state.ever_populated) {request->set_history_navigation(true);- // AD-HOC: While a document loads bypassing the HTTP cache, so do the documents of its child navigables.- if (request->cache_mode() == HTTP::CacheMode::Default) {- if (auto container_document = navigable->container_document(); container_document && container_document->is_loading_bypassing_cache())- request->set_cache_mode(HTTP::CacheMode::Reload);+ // INTEROP: The specs don't define HTTP cache behavior for history traversals. But RFC 9111 says that a history+ // mechanism shows the representation as it was when it was retrieved, and that freshness doesn't apply+ // to it, and every major engine uses a stored response here without revalidating it. Use the+ // "force-cache" cache mode, with which Fetch "uses any response in the HTTP cache matching the+ // request, not paying attention to staleness. If there was no response, it creates a normal request+ // and updates the HTTP cache with the response."+ // https://httpwg.org/specs/rfc9111.html#history.lists+ request->set_cache_mode(HTTP::CacheMode::ForceCache);+ }++ // AD-HOC: While a document loads bypassing the HTTP cache, or using it without revalidation, so do the documents+ // of its child navigables. Bypassing the cache wins over a history traversal of the child navigable too.+ if (auto container_document = navigable->container_document()) {+ auto container_cache_mode = container_document->cache_mode_while_loading();+ if (request->cache_mode() == HTTP::CacheMode::Default+ || (request->cache_mode() == HTTP::CacheMode::ForceCache && container_cache_mode == HTTP::CacheMode::Reload))+ request->set_cache_mode(container_cache_mode);}// 9. If sourceSnapshotParams's has transient activation is true, then set request's user-activation to true.diff --git a/Tests/LibWeb/Text/expected/Cache/history-traversal-uses-cache-without-revalidation.txt b/Tests/LibWeb/Text/expected/Cache/history-traversal-uses-cache-without-revalidation.txtnew file mode 100644index 00000000000..d204634b0b6--- /dev/null+++ b/Tests/LibWeb/Text/expected/Cache/history-traversal-uses-cache-without-revalidation.txt@@ -0,0 +1,5 @@+loaded document with subresource+loaded other document+loaded document with subresource+Requests the server saw for the document: 1+Requests the server saw for the subresource: 1diff --git a/Tests/LibWeb/Text/input/Cache/history-traversal-uses-cache-without-revalidation.html b/Tests/LibWeb/Text/input/Cache/history-traversal-uses-cache-without-revalidation.htmlnew file mode 100644index 00000000000..d909fbe76e0--- /dev/null+++ b/Tests/LibWeb/Text/input/Cache/history-traversal-uses-cache-without-revalidation.html@@ -0,0 +1,82 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<iframe id="testFrame"></iframe>+<script>+ const server = httpTestServer();++ // In test mode, the disk cache only stores responses to requests carrying this header.+ const TEST_CACHE_ENABLED_HEADER = "X-Ladybird-Enable-Disk-Cache";++ // The echo path keys both the server-side request count and the disk cache entry. Give each run its own paths, so+ // parallel runner clones of this test don't count each other's requests.+ const id = uniqueID();++ // Both the document and the resource it fetches while it loads must be revalidated before a cache may use them+ // again. A history traversal back to the document must use the stored responses anyway.+ const MUST_REVALIDATE_HEADERS = {+ "Cache-Control": "no-cache",+ "Last-Modified": "Mon, 01 Jan 2024 00:00:00 GMT",+ };++ function nextMessage() {+ return new Promise(resolve => {+ window.addEventListener("message", event => resolve(event.data), { once: true });+ });+ }++ promiseTest(async () => {+ const requestCount = async url => (await fetch(server.recordedRequestCountURL(url))).json();++ const subresourceURL = await server.createEcho("GET", `/history-traversal-subresource-${id}`, {+ status: 200,+ headers: { ...MUST_REVALIDATE_HEADERS, "Content-Type": "text/plain" },+ body: "subresource",+ });++ const documentURL = await server.createEcho("GET", `/history-traversal-document-${id}`, {+ status: 200,+ headers: { ...MUST_REVALIDATE_HEADERS, "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>+ window.onmessage = event => { location.href = event.data; };+ fetch(${JSON.stringify(subresourceURL)}, { headers: { ${JSON.stringify(TEST_CACHE_ENABLED_HEADER)}: "1" } })+ .then(response => response.text())+ .then(text => parent.postMessage("loaded document with " + text, "*"));+ <\/script>`,+ });++ const otherDocumentURL = await server.createEcho("GET", `/history-traversal-other-document-${id}`, {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>+ window.onmessage = () => { history.back(); };+ parent.postMessage("loaded other document", "*");+ <\/script>`,+ });++ // A page cannot attach a header to a navigation request, so have every navigation request carry the one that+ // enables the disk cache. The document of the iframe is cached in a partition of its own, which no fetch from+ // this page can reach.+ const diskCacheWasEnabledForNavigations = internals.setDiskCacheEnabledForNavigations(true);++ // Navigate the iframe to the document, which caches both the document and its subresource.+ const frame = document.getElementById("testFrame");+ let message = nextMessage();+ frame.src = documentURL;+ println(await message);++ // Navigate the iframe away, and then traverse back. The iframe does both itself, so that this works regardless+ // of whether the test page and the echo server are same-origin.+ message = nextMessage();+ frame.contentWindow.postMessage(otherDocumentURL, "*");+ println(await message);++ message = nextMessage();+ frame.contentWindow.postMessage("back", "*");+ println(await message);++ internals.setDiskCacheEnabledForNavigations(diskCacheWasEnabledForNavigations);++ println(`Requests the server saw for the document: ${await requestCount(documentURL)}`);+ println(`Requests the server saw for the subresource: ${await requestCount(subresourceURL)}`);+ });+</script>