Skip to content

Truly independent web browser

LibWeb: Keep the insecure requests policy on the policy container

Luke Wildec9dd40cdc63f
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 78acb45ca99..4e21c91c061 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -269,7 +269,6 @@
#include <LibWeb/UIEvents/PointerTypes.h>
#include <LibWeb/UIEvents/TextEvent.h>
#include <LibWeb/UIEvents/TouchEvent.h>
-#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>
#include <LibWeb/ViewTransition/ViewTransition.h>
#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
@@ -543,8 +542,13 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type
// 10. Set window's associated Document to document.
window->set_associated_document(*document);
- // NB: Upgrade Insecure Requests has a new Document inherit its browsing context's insecure requests policy.
- UpgradeInsecureRequests::inherit_the_insecure_requests_policy_into_a_new_document(document->relevant_settings_object(), browsing_context);
+ // https://w3c.github.io/webappsec-upgrade-insecure-requests/#nesting
+ // AD-HOC: A Document in a child navigable inherits the insecure requests policy of its container's node document
+ // when it is created, as Chromium and WebKit do, instead of through its browsing context.
+ if (navigation_params.navigable->parent()) {
+ auto container_state = navigation_params.navigable->container_state();
+ document->policy_container()->inherit_insecure_requests_policy(container_state.document_insecure_requests_policy, container_state.document_upgrade_insecure_navigations_set);
+ }
// 11. Set document's internal ancestor origin objects list to the result of running the internal ancestor origin
// objects list creation steps given document and navigationParams's iframe element referrer policy.
diff --git a/Libraries/LibWeb/HTML/BrowsingContext.cpp b/Libraries/LibWeb/HTML/BrowsingContext.cpp
index b846807af08..159d1201d53 100644
--- a/Libraries/LibWeb/HTML/BrowsingContext.cpp
+++ b/Libraries/LibWeb/HTML/BrowsingContext.cpp
@@ -28,7 +28,6 @@
#include <LibWeb/Layout/Viewport.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Page/Page.h>
-#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>
#include <LibWebCommon/HTML/SandboxingFlagSet.h>
namespace Web::HTML {
@@ -79,13 +78,6 @@ BrowsingContext::BrowsingContextAndDocument BrowsingContext::create_a_new_browsi
// 1. Let browsingContext be a new browsing context.
GC::Ref<BrowsingContext> browsing_context = *GC::Heap::the().allocate<BrowsingContext>(page);
- // NB: Upgrade Insecure Requests has a nested browsing context inherit its embedding document's insecure requests
- // policy when it is created.
- if (embedder) {
- auto const& embedding_document_settings = embedder->document().relevant_settings_object();
- UpgradeInsecureRequests::inherit_the_insecure_requests_policy_into_a_nested_browsing_context(*browsing_context, embedding_document_settings.insecure_requests_policy(), embedding_document_settings.upgrade_insecure_navigations_set());
- }
-
// 2. Let unsafeContextCreationTime be the unsafe shared current time.
[[maybe_unused]] auto unsafe_context_creation_time = HighResolutionTime::unsafe_shared_current_time();
@@ -230,9 +222,6 @@ BrowsingContext::BrowsingContextAndDocument BrowsingContext::create_a_new_browsi
// custom element registry: A new CustomElementRegistry object.
document->set_custom_element_registry(CustomElementRegistry::create_global(*document));
- // NB: Upgrade Insecure Requests has a new Document inherit its browsing context's insecure requests policy.
- UpgradeInsecureRequests::inherit_the_insecure_requests_policy_into_a_new_document(document->relevant_settings_object(), browsing_context);
-
// 16. Let iframeReferrerPolicy be the result of determining the iframe element referrer policy given embedder.
auto iframe_referrer_policy = determine_iframe_element_referrer_policy(embedder);
diff --git a/Libraries/LibWeb/HTML/BrowsingContext.h b/Libraries/LibWeb/HTML/BrowsingContext.h
index af68d7c5231..5a7b64c1209 100644
--- a/Libraries/LibWeb/HTML/BrowsingContext.h
+++ b/Libraries/LibWeb/HTML/BrowsingContext.h
@@ -17,7 +17,6 @@
#include <LibWebCommon/HTML/BrowsingContext.h>
#include <LibWebCommon/HTML/CrossProcessId.h>
#include <LibWebCommon/HTML/SandboxingFlagSet.h>
-#include <LibWebCommon/UpgradeInsecureRequests/InsecureRequestsPolicy.h>
namespace Web::HTML {
@@ -82,14 +81,6 @@ public:
SandboxingFlagSet popup_sandboxing_flag_set() const { return m_popup_sandboxing_flag_set; }
void set_popup_sandboxing_flag_set(SandboxingFlagSet value) { m_popup_sandboxing_flag_set = value; }
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy
- UpgradeInsecureRequests::InsecureRequestsPolicy insecure_requests_policy() const { return m_insecure_requests_policy; }
- void set_insecure_requests_policy(UpgradeInsecureRequests::InsecureRequestsPolicy policy) { m_insecure_requests_policy = policy; }
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
- UpgradeInsecureRequests::UpgradeInsecureNavigationsSet const& upgrade_insecure_navigations_set() const { return m_upgrade_insecure_navigations_set; }
- void add_to_upgrade_insecure_navigations_set(UpgradeInsecureRequests::HostAndPort tuple) { m_upgrade_insecure_navigations_set.insert(move(tuple)); }
-
private:
explicit BrowsingContext(GC::Ref<Page>);
@@ -125,14 +116,6 @@ private:
// https://html.spec.whatwg.org/multipage/browsers.html#tlbc-group
Optional<u64> m_browsing_context_group_id;
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy
- // It is set to Do Not Upgrade unless otherwise specified.
- UpgradeInsecureRequests::InsecureRequestsPolicy m_insecure_requests_policy { UpgradeInsecureRequests::InsecureRequestsPolicy::DoNotUpgrade };
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
- // Its value is the empty set unless otherwise specified.
- UpgradeInsecureRequests::UpgradeInsecureNavigationsSet m_upgrade_insecure_navigations_set;
};
SandboxingFlagSet determine_the_creation_sandboxing_flags(BrowsingContext const&, GC::Ptr<DOM::Element> embedder);
diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
index 10e0351553c..fee09aec2c0 100644
--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp
@@ -456,7 +456,9 @@ GC::Ptr<Fetch::Infrastructure::Request> HTMLLinkElement::create_link_request(HTM
auto request = create_potential_CORS_request(*url, options.destination, options.crossorigin);
// 6. Set request's policy container to options's policy container.
- request->set_policy_container(options.policy_container);
+ // AD-HOC: A clone of it, so that the request and its redirects keep the policies its document had when the request
+ // was created, its CSP list included, as a request whose policy container is "client" keeps its client's.
+ request->set_policy_container(options.policy_container->clone());
// 7. Set request's integrity metadata to options's integrity.
request->set_integrity_metadata(options.integrity);
diff --git a/Libraries/LibWeb/HTML/HTMLMetaElement.cpp b/Libraries/LibWeb/HTML/HTMLMetaElement.cpp
index 42294056e7a..9167f9bbfc4 100644
--- a/Libraries/LibWeb/HTML/HTMLMetaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMetaElement.cpp
@@ -19,6 +19,8 @@
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/HTMLHeadElement.h>
#include <LibWeb/HTML/HTMLMetaElement.h>
+#include <LibWeb/HTML/Navigable.h>
+#include <LibWeb/HTML/NavigableContainer.h>
#include <LibWeb/HTML/PolicyContainers.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/Page/Page.h>
@@ -35,6 +37,16 @@ HTMLMetaElement::HTMLMetaElement(DOM::Document& document, DOM::QualifiedName qua
HTMLMetaElement::~HTMLMetaElement() = default;
+static void report_container_state_of_child_navigables(DOM::Document& document)
+{
+ // NB: Navigable containers in shadow trees have child navigables too.
+ document.for_each_shadow_including_descendant([&](DOM::Node& node) {
+ if (auto* container = as_if<NavigableContainer>(node); container && container->content_navigable())
+ document.page().client().page_did_change_navigable_container_state(container->content_navigable()->id(), container->replicated_container_state());
+ return TraversalDecision::Continue;
+ });
+}
+
Optional<HTMLMetaElement::HttpEquivAttributeState> HTMLMetaElement::http_equiv_state() const
{
auto value = get_attribute_ns({}, HTML::AttributeNames::http_equiv).value_or({});
@@ -220,6 +232,11 @@ void HTMLMetaElement::inserted()
// 5. Enforce the policy policy.
document().relevant_settings_object().policy_container()->csp_list.enforce_policy(policy);
+
+ // NB: A document created in a child navigable inherits the insecure requests policy of its container's
+ // node document, which a process hosting the child navigable reads from the container's state.
+ if (policy->contains_directive_with_name(ContentSecurityPolicy::Directives::Names::UpgradeInsecureRequests))
+ report_container_state_of_child_navigables(document());
break;
}
default:
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 2e8fbd0ac06..8f2464ca0d5 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -97,7 +97,6 @@
#include <LibWeb/UIEvents/EventNames.h>
#include <LibWeb/UIEvents/InputEvent.h>
#include <LibWeb/UIEvents/InputTypes.h>
-#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>
#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebDriver/BiDi/Network.h>
#include <LibWeb/WebIDL/Promise.h>
@@ -4539,12 +4538,10 @@ GC::Ref<LocalNavigable> LocalNavigable::create_stand_in(Badge<Page> badge, Remot
auto [browsing_context, document] = BrowsingContext::create_a_new_browsing_context_and_document(page, container ? GC::Ptr<DOM::Document> { container->document() } : nullptr, container, remote_navigable.window_proxy(), current_history_entry.document_state.origin);
if (!local_parent) {
- // NB: The browsing context of a navigable whose container is in another process inherits the insecure requests
- // policy that the container's process reports for its node document. So does the stand-in's document.
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#nesting
+ // NB: Like a document created in a child navigable, the stand-in's document inherits the insecure requests
+ // policy that the container's process reports for its node document.
auto const& container_state = remote_navigable.replicated_state().container;
- UpgradeInsecureRequests::inherit_the_insecure_requests_policy_into_a_nested_browsing_context(browsing_context, container_state.document_insecure_requests_policy, container_state.document_upgrade_insecure_navigations_set);
- UpgradeInsecureRequests::inherit_the_insecure_requests_policy_into_a_new_document(document->relevant_settings_object(), browsing_context);
+ document->policy_container()->inherit_insecure_requests_policy(container_state.document_insecure_requests_policy, container_state.document_upgrade_insecure_navigations_set);
page.ensure_compositor_host();
}
diff --git a/Libraries/LibWeb/HTML/NavigableContainer.cpp b/Libraries/LibWeb/HTML/NavigableContainer.cpp
index fdce96bf817..d7f06f706ac 100644
--- a/Libraries/LibWeb/HTML/NavigableContainer.cpp
+++ b/Libraries/LibWeb/HTML/NavigableContainer.cpp
@@ -623,9 +623,9 @@ ReplicatedContainerState NavigableContainer::replicated_container_state()
state.local_name = local_name();
state.iframe_referrer_policy = determine_iframe_element_referrer_policy(*this);
state.container_policy = process_permissions_policy_attributes();
- auto const& document_settings = document().relevant_settings_object();
- state.document_insecure_requests_policy = document_settings.insecure_requests_policy();
- state.document_upgrade_insecure_navigations_set = document_settings.upgrade_insecure_navigations_set();
+ auto document_policy_container = document().policy_container();
+ state.document_insecure_requests_policy = document_policy_container->insecure_requests_policy();
+ state.document_upgrade_insecure_navigations_set = document_policy_container->upgrade_insecure_navigations_set();
return state;
}
diff --git a/Libraries/LibWeb/HTML/PolicyContainers.cpp b/Libraries/LibWeb/HTML/PolicyContainers.cpp
index 4ca7266d112..7242847d487 100644
--- a/Libraries/LibWeb/HTML/PolicyContainers.cpp
+++ b/Libraries/LibWeb/HTML/PolicyContainers.cpp
@@ -8,6 +8,7 @@
#include <LibGC/Heap.h>
#include <LibURL/URL.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
+#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
#include <LibWeb/ContentSecurityPolicy/Policy.h>
#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
@@ -95,9 +96,76 @@ NonnullRefPtr<PolicyContainer> create_a_policy_container_from_serialized_policy_
result->embedder_policy = serialized_policy_container.embedder_policy;
result->referrer_policy = serialized_policy_container.referrer_policy;
result->force_load_at_top = serialized_policy_container.force_load_at_top;
+ // NB: A serialized policy container holds its effective insecure requests policy and set, which the result inherits.
+ result->inherit_insecure_requests_policy(serialized_policy_container.insecure_requests_policy, serialized_policy_container.upgrade_insecure_navigations_set);
return result;
}
+// https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery
+// AD-HOC: Enforcing the upgrade-insecure-requests directive sets the protected resource's settings' insecure requests
+// policy to "Upgrade", and inserts a tuple of the protected resource's URL's host and port into settings'
+// upgrade insecure navigations set. We instead derive both from the policies enforced in the policy
+// container's CSP list, whether they were delivered with a response or by a meta element, and use each
+// policy's self-origin as the protected resource's URL. Monitoring the directive has no effect, so only
+// enforced policies count. The stored values hold what the policy container inherited.
+template<typename Callback>
+static void for_each_enforced_policy_with_upgrade_insecure_requests(PolicyContainer const& policy_container, Callback callback)
+{
+ for (auto const& policy : policy_container.csp_list.policies()) {
+ if (policy->disposition() != ContentSecurityPolicy::Policy::Disposition::Enforce)
+ continue;
+ if (!policy->contains_directive_with_name(ContentSecurityPolicy::Directives::Names::UpgradeInsecureRequests))
+ continue;
+ if (callback(*policy) == IterationDecision::Break)
+ return;
+ }
+}
+
+UpgradeInsecureRequests::InsecureRequestsPolicy PolicyContainer::insecure_requests_policy() const
+{
+ auto result = m_insecure_requests_policy;
+ if (result == UpgradeInsecureRequests::InsecureRequestsPolicy::Upgrade)
+ return result;
+ for_each_enforced_policy_with_upgrade_insecure_requests(*this, [&](auto const&) {
+ result = UpgradeInsecureRequests::InsecureRequestsPolicy::Upgrade;
+ return IterationDecision::Break;
+ });
+ return result;
+}
+
+UpgradeInsecureRequests::UpgradeInsecureNavigationsSet PolicyContainer::upgrade_insecure_navigations_set() const
+{
+ auto result = m_upgrade_insecure_navigations_set;
+ for_each_enforced_policy_with_upgrade_insecure_requests(*this, [&](ContentSecurityPolicy::Policy const& policy) {
+ auto const& self_origin = policy.self_origin();
+ if (!self_origin.is_opaque())
+ result.insert({ self_origin.host(), self_origin.port() });
+ return IterationDecision::Continue;
+ });
+ return result;
+}
+
+// https://w3c.github.io/webappsec-upgrade-insecure-requests/#nesting
+// NB: These are the steps for a new Document. Callers pass the policy and set this policy container inherits, from its
+// owner's context or from a serialized policy container.
+void PolicyContainer::inherit_insecure_requests_policy(UpgradeInsecureRequests::InsecureRequestsPolicy policy, UpgradeInsecureRequests::UpgradeInsecureNavigationsSet const& upgrade_insecure_navigations_set)
+{
+ // 1. If context's insecure requests policy is Upgrade, then:
+ if (policy != UpgradeInsecureRequests::InsecureRequestsPolicy::Upgrade)
+ return;
+
+ // 1. Let settings be document's incumbent settings object.
+ // AD-HOC: Document's own policy container takes the policy, rather than its incumbent settings object. See
+ // https://github.com/w3c/webappsec-upgrade-insecure-requests/issues/17.
+ // 2. Set settings' insecure requests policy to Upgrade.
+ m_insecure_requests_policy = UpgradeInsecureRequests::InsecureRequestsPolicy::Upgrade;
+
+ // 3. For each value in context's upgrade insecure navigations set, add value to settings's upgrade insecure
+ // navigations set.
+ for (auto const& value : upgrade_insecure_navigations_set.tuples())
+ m_upgrade_insecure_navigations_set.insert(value);
+}
+
// https://html.spec.whatwg.org/multipage/browsers.html#clone-a-policy-container
NonnullRefPtr<PolicyContainer> PolicyContainer::clone() const
{
@@ -123,6 +191,11 @@ NonnullRefPtr<PolicyContainer> PolicyContainer::clone() const
// "force-load-at-top".
clone->force_load_at_top = force_load_at_top;
+ // AD-HOC: The clone holds the insecure requests policy and upgrade insecure navigations set that policyContainer
+ // inherited, as policy containers hold them instead of settings objects.
+ clone->m_insecure_requests_policy = m_insecure_requests_policy;
+ clone->m_upgrade_insecure_navigations_set = m_upgrade_insecure_navigations_set;
+
// 6. Return clone.
return clone;
}
@@ -134,6 +207,8 @@ SerializedPolicyContainer PolicyContainer::serialize() const
.embedder_policy = embedder_policy,
.referrer_policy = referrer_policy,
.force_load_at_top = force_load_at_top,
+ .insecure_requests_policy = insecure_requests_policy(),
+ .upgrade_insecure_navigations_set = upgrade_insecure_navigations_set(),
};
}
diff --git a/Libraries/LibWeb/HTML/PolicyContainers.h b/Libraries/LibWeb/HTML/PolicyContainers.h
index 0de66b11c52..9b3892473a0 100644
--- a/Libraries/LibWeb/HTML/PolicyContainers.h
+++ b/Libraries/LibWeb/HTML/PolicyContainers.h
@@ -18,6 +18,7 @@
#include <LibWeb/SRI/IntegrityPolicy.h>
#include <LibWebCommon/HTML/EmbedderPolicy.h>
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
+#include <LibWebCommon/UpgradeInsecureRequests/InsecureRequestsPolicy.h>
namespace Web::HTML {
@@ -51,11 +52,29 @@ struct PolicyContainer final : public AtomicRefCounted<PolicyContainer> {
// "force-load-at-top". Its type is boolean with default value false.
bool force_load_at_top { false };
+ // https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy
+ // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
+ // AD-HOC: Upgrade Insecure Requests defines these on settings objects and browsing contexts. A policy container
+ // holds them instead, so a request's clone of its client's policy container holds them for the whole fetch.
+ // See https://github.com/w3c/webappsec-upgrade-insecure-requests/issues/5.
+ [[nodiscard]] UpgradeInsecureRequests::InsecureRequestsPolicy insecure_requests_policy() const;
+ [[nodiscard]] UpgradeInsecureRequests::UpgradeInsecureNavigationsSet upgrade_insecure_navigations_set() const;
+ void inherit_insecure_requests_policy(UpgradeInsecureRequests::InsecureRequestsPolicy, UpgradeInsecureRequests::UpgradeInsecureNavigationsSet const&);
+
[[nodiscard]] NonnullRefPtr<PolicyContainer> clone() const;
[[nodiscard]] SerializedPolicyContainer serialize() const;
private:
PolicyContainer() = default;
+
+ // https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy
+ // It is set to Do Not Upgrade unless otherwise specified.
+ // NB: These hold what the policy container inherited. Its CSP list holds its own policies.
+ UpgradeInsecureRequests::InsecureRequestsPolicy m_insecure_requests_policy { UpgradeInsecureRequests::InsecureRequestsPolicy::DoNotUpgrade };
+
+ // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
+ // Its value is the empty set unless otherwise specified.
+ UpgradeInsecureRequests::UpgradeInsecureNavigationsSet m_upgrade_insecure_navigations_set;
};
// https://html.spec.whatwg.org/multipage/browsers.html#requires-storing-the-policy-container-in-history
diff --git a/Libraries/LibWeb/HTML/Scripting/EnvironmentSettingsSnapshot.cpp b/Libraries/LibWeb/HTML/Scripting/EnvironmentSettingsSnapshot.cpp
index 7e88cfd5eaf..32013049d55 100644
--- a/Libraries/LibWeb/HTML/Scripting/EnvironmentSettingsSnapshot.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/EnvironmentSettingsSnapshot.cpp
@@ -26,9 +26,6 @@ EnvironmentSettingsSnapshot::EnvironmentSettingsSnapshot(NonnullOwnPtr<JS::Execu
this->id = serialized_settings.id;
this->creation_url = serialized_settings.creation_url;
this->top_level_creation_url = serialized_settings.top_level_creation_url;
- set_insecure_requests_policy(serialized_settings.insecure_requests_policy);
- for (auto const& tuple : serialized_settings.upgrade_insecure_navigations_set.tuples())
- add_to_upgrade_insecure_navigations_set(tuple);
}
// Out of line to ensure this class has a key function
diff --git a/Libraries/LibWeb/HTML/Scripting/Environments.cpp b/Libraries/LibWeb/HTML/Scripting/Environments.cpp
index 81a9aeddbbd..42aa55c1b1d 100644
--- a/Libraries/LibWeb/HTML/Scripting/Environments.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/Environments.cpp
@@ -14,8 +14,6 @@
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
-#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
-#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
@@ -745,56 +743,10 @@ SerializedEnvironmentSettingsObject EnvironmentSettingsObject::serialize()
.agent_cluster_id = agent_cluster_id(),
.agent_cluster_cross_origin_isolation_mode = agent_cluster_cross_origin_isolation_mode(),
.time_origin = this->time_origin(),
- .insecure_requests_policy = insecure_requests_policy(),
- .upgrade_insecure_navigations_set = upgrade_insecure_navigations_set(),
.global = move(serialized_global),
};
}
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery
-// AD-HOC: Enforcing the upgrade-insecure-requests directive sets the protected resource's settings' insecure requests
-// policy to "Upgrade", and inserts a tuple of the protected resource's URL's host and port into settings'
-// upgrade insecure navigations set. We instead derive both from the policies enforced in settings' policy
-// container's CSP list, whether they were delivered with a response or by a meta element, and use each
-// policy's self-origin as the protected resource's URL. Monitoring the directive has no effect, so only
-// enforced policies count. The stored values hold what settings inherited.
-template<typename Callback>
-static void for_each_enforced_policy_with_upgrade_insecure_requests(EnvironmentSettingsObject const& settings, Callback callback)
-{
- for (auto const& policy : settings.policy_container()->csp_list.policies()) {
- if (policy->disposition() != ContentSecurityPolicy::Policy::Disposition::Enforce)
- continue;
- if (!policy->contains_directive_with_name(ContentSecurityPolicy::Directives::Names::UpgradeInsecureRequests))
- continue;
- if (callback(*policy) == IterationDecision::Break)
- return;
- }
-}
-
-UpgradeInsecureRequests::InsecureRequestsPolicy EnvironmentSettingsObject::insecure_requests_policy() const
-{
- auto result = m_insecure_requests_policy;
- if (result == UpgradeInsecureRequests::InsecureRequestsPolicy::Upgrade)
- return result;
- for_each_enforced_policy_with_upgrade_insecure_requests(*this, [&](auto const&) {
- result = UpgradeInsecureRequests::InsecureRequestsPolicy::Upgrade;
- return IterationDecision::Break;
- });
- return result;
-}
-
-UpgradeInsecureRequests::UpgradeInsecureNavigationsSet EnvironmentSettingsObject::upgrade_insecure_navigations_set() const
-{
- auto result = m_upgrade_insecure_navigations_set;
- for_each_enforced_policy_with_upgrade_insecure_requests(*this, [&](ContentSecurityPolicy::Policy const& policy) {
- auto const& self_origin = policy.self_origin();
- if (!self_origin.is_opaque())
- result.insert({ self_origin.host(), self_origin.port() });
- return IterationDecision::Continue;
- });
- return result;
-}
-
GC::Ref<StorageAPI::StorageManager> EnvironmentSettingsObject::storage_manager()
{
if (!m_storage_manager)
diff --git a/Libraries/LibWeb/HTML/Scripting/Environments.h b/Libraries/LibWeb/HTML/Scripting/Environments.h
index 489a37edc84..bd9836baada 100644
--- a/Libraries/LibWeb/HTML/Scripting/Environments.h
+++ b/Libraries/LibWeb/HTML/Scripting/Environments.h
@@ -23,7 +23,6 @@
#include <LibWeb/ServiceWorker/Registration.h>
#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>
#include <LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h>
-#include <LibWebCommon/UpgradeInsecureRequests/InsecureRequestsPolicy.h>
namespace Web::HTML {
@@ -136,14 +135,6 @@ public:
// https://fetch.spec.whatwg.org/#concept-fetch-group
auto& fetch_group() { return m_fetch_group; }
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy
- UpgradeInsecureRequests::InsecureRequestsPolicy insecure_requests_policy() const;
- void set_insecure_requests_policy(UpgradeInsecureRequests::InsecureRequestsPolicy policy) { m_insecure_requests_policy = policy; }
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
- UpgradeInsecureRequests::UpgradeInsecureNavigationsSet upgrade_insecure_navigations_set() const;
- void add_to_upgrade_insecure_navigations_set(UpgradeInsecureRequests::HostAndPort tuple) { m_upgrade_insecure_navigations_set.insert(move(tuple)); }
-
SerializedEnvironmentSettingsObject serialize();
GC::Ref<StorageAPI::StorageManager> storage_manager();
@@ -220,15 +211,6 @@ private:
bool m_discarded { false };
Vector<GC::Ref<WorkerAgentParent>> m_owned_worker_agents;
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy
- // It is set to Do Not Upgrade unless otherwise specified.
- // NB: These hold what the settings object inherited. See insecure_requests_policy() for its own policies.
- UpgradeInsecureRequests::InsecureRequestsPolicy m_insecure_requests_policy { UpgradeInsecureRequests::InsecureRequestsPolicy::DoNotUpgrade };
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
- // Its value is the empty set unless otherwise specified.
- UpgradeInsecureRequests::UpgradeInsecureNavigationsSet m_upgrade_insecure_navigations_set;
};
RunScriptDecision can_run_script(EnvironmentSettingsObject const&);
diff --git a/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.cpp b/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.cpp
index a527f112980..27767202555 100644
--- a/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.cpp
@@ -15,7 +15,6 @@
#include <LibWeb/HTML/Scripting/WorkerEnvironmentSettingsObject.h>
#include <LibWeb/HTML/WorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>
namespace Web::HTML {
@@ -47,9 +46,6 @@ GC::Ref<WorkerEnvironmentSettingsObject> WorkerEnvironmentSettingsObject::setup(
auto settings_object = realm->create<WorkerEnvironmentSettingsObject>(move(execution_context), *worker, move(origin), outside_settings.has_cross_site_ancestor, unsafe_worker_creation_time, agent_cluster_id, agent_cluster_cross_origin_isolation_mode);
settings_object->target_browsing_context = nullptr;
- // NB: Upgrade Insecure Requests has the worker inherit the insecure requests policy here.
- UpgradeInsecureRequests::inherit_the_insecure_requests_policy_into_a_worker(settings_object, outside_settings.insecure_requests_policy, outside_settings.upgrade_insecure_navigations_set);
-
// 5. Set settings object's id to a new unique opaque string, creation URL to worker global scope's url, top-level
// creation URL to null, target browsing context to null, and active service worker to null.
// NB: The browser process generates the id, as it holds the worker's environment too. WorkerHost sets (ad-hoc) the
diff --git a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
index c0fdf76bae8..3a0d4adf784 100644
--- a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
@@ -213,6 +213,15 @@ void WorkerGlobalScope::initialize_policy_container(GC::Ref<Fetch::Infrastructur
// 2. Otherwise, set workerGlobalScope's policy container to the result of creating a policy container from a fetch
// response given response and environment.
m_policy_container = create_a_policy_container_from_a_fetch_response(response, environment);
+
+ // https://w3c.github.io/webappsec-upgrade-insecure-requests/#nesting
+ // AD-HOC: Upgrade Insecure Requests has a worker inherit the insecure requests policy of its inherited responsible
+ // browsing context, which HTML no longer has. It inherits that of owner set[0]'s relevant settings object,
+ // which is outside settings, here instead. The clone in step 1 holds it already.
+ auto const& owner_serialized_policy_container = m_owner_set.first().visit([](auto const& owner) -> SerializedPolicyContainer const& {
+ return owner.relevant_settings_object_policy_container;
+ });
+ m_policy_container->inherit_insecure_requests_policy(owner_serialized_policy_container.insecure_requests_policy, owner_serialized_policy_container.upgrade_insecure_navigations_set);
}
// https://html.spec.whatwg.org/multipage/browsers.html#check-a-global-object's-embedder-policy
diff --git a/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.cpp b/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.cpp
index 8ae5b762079..b6be9e1a0eb 100644
--- a/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.cpp
+++ b/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.cpp
@@ -6,78 +6,12 @@
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/HTML/BrowsingContext.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/PolicyContainers.h>
#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>
#include <LibWebCommon/SecureContexts/AbstractOperations.h>
namespace Web::UpgradeInsecureRequests {
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#nesting
-void inherit_the_insecure_requests_policy_into_a_nested_browsing_context(HTML::BrowsingContext& context, InsecureRequestsPolicy embedding_document_policy, UpgradeInsecureNavigationsSet const& embedding_document_set)
-{
- // 1. When a nested browsing context context is created:
- // NB: The caller passes context's embedding document's insecure requests policy and upgrade insecure navigations
- // set, which the process holding that document reports when context is created in another one.
-
- // 1. If context's embedding document's insecure requests policy is Upgrade, then:
- if (embedding_document_policy != InsecureRequestsPolicy::Upgrade)
- return;
-
- // 1. Set context's insecure requests policy to Upgrade.
- context.set_insecure_requests_policy(InsecureRequestsPolicy::Upgrade);
-
- // 2. For each value in context's embedding document's upgrade insecure navigations set, add value to context's
- // upgrade insecure navigations set.
- for (auto const& value : embedding_document_set.tuples())
- context.add_to_upgrade_insecure_navigations_set(value);
-}
-
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#nesting
-void inherit_the_insecure_requests_policy_into_a_new_document(HTML::EnvironmentSettingsObject& document_settings, HTML::BrowsingContext const& context)
-{
- // 2. When creating a new Document object document in a browsing context context:
-
- // 1. If context's insecure requests policy is Upgrade, then:
- if (context.insecure_requests_policy() != InsecureRequestsPolicy::Upgrade)
- return;
-
- // 1. Let settings be document's incumbent settings object.
- // NB: That is document's relevant settings object, which the caller passes. A document that reuses its browsing
- // context's initial about:blank document's window shares its settings object, which inherited the same.
- auto& settings = document_settings;
-
- // 2. Set settings' insecure requests policy to Upgrade.
- settings.set_insecure_requests_policy(InsecureRequestsPolicy::Upgrade);
-
- // 3. For each value in context's upgrade insecure navigations set, add value to settings's upgrade insecure
- // navigations set.
- for (auto const& value : context.upgrade_insecure_navigations_set().tuples())
- settings.add_to_upgrade_insecure_navigations_set(value);
-}
-
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#nesting
-void inherit_the_insecure_requests_policy_into_a_worker(HTML::EnvironmentSettingsObject& settings_object, InsecureRequestsPolicy outside_settings_policy, UpgradeInsecureNavigationsSet const& outside_settings_set)
-{
- // When executing the set up a worker environment settings object algorithm, perform the following steps after the
- // current step #4:
-
- // 1. If inherited responsible browsing context's insecure requests policy is Upgrade, then:
- // AD-HOC: HTML no longer has an inherited responsible browsing context, which was outside settings' responsible
- // browsing context. We inherit outside settings' insecure requests policy and upgrade insecure navigations
- // set instead, which the caller passes. Those include what outside settings inherited from its browsing
- // context, and the policies its own CSP list enforces, so a top-level document's workers inherit too.
- if (outside_settings_policy != InsecureRequestsPolicy::Upgrade)
- return;
-
- // 1. Set settings object's insecure requests policy to Upgrade.
- settings_object.set_insecure_requests_policy(InsecureRequestsPolicy::Upgrade);
-
- // 2. For each value in inherited responsible browsing context's upgrade insecure navigations set, add value to
- // settings object's upgrade insecure navigations set.
- for (auto const& value : outside_settings_set.tuples())
- settings_object.add_to_upgrade_insecure_navigations_set(value);
-}
-
// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
void upgrade_request_to_a_potentially_trustworthy_url_if_appropriate(Fetch::Infrastructure::Request& request)
{
@@ -85,6 +19,10 @@ void upgrade_request_to_a_potentially_trustworthy_url_if_appropriate(Fetch::Infr
// well as insecure initial requests, which needs it to operate on request's current URL.
auto& url = request.current_url();
+ // AD-HOC: Request's policy container holds the insecure requests policy and upgrade insecure navigations set of
+ // request's client as captured for this fetch, which the steps below read in place of client's.
+ auto const& policy_container = *request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>();
+
// 1. If request is a navigation request, append a header named Upgrade-Insecure-Requests with a value of 1 to
// request's header list if any of the following criteria are met:
// 1. request's URL is not a potentially trustworthy URL
@@ -106,7 +44,7 @@ void upgrade_request_to_a_potentially_trustworthy_url_if_appropriate(Fetch::Infr
// 4. If tuple is contained in client's upgrade insecure navigations set, then skip the remaining
// substeps, and continue upgrading request.
auto const& host = url.host();
- if (!request.client() || !host.has_value() || !request.client()->upgrade_insecure_navigations_set().contains({ *host, url.port() })) {
+ if (!host.has_value() || !policy_container.upgrade_insecure_navigations_set().contains({ *host, url.port() })) {
// 5. Return without further modifying request.
return;
}
@@ -115,7 +53,10 @@ void upgrade_request_to_a_potentially_trustworthy_url_if_appropriate(Fetch::Infr
// 3. Let upgrade state be the result of executing § 4.2 Should insecure requests be upgraded for client? upon
// request's client.
- auto upgrade_state = should_insecure_requests_be_upgraded_for_client(request.client());
+ // AD-HOC: § 4.2 reads client's responsible document or browsing context, which HTML no longer has. Request's policy
+ // container holds what client inherited, and its CSP list the policies client enforces. See
+ // https://github.com/w3c/webappsec-upgrade-insecure-requests/issues/27.
+ auto upgrade_state = policy_container.insecure_requests_policy();
// 4. If upgrade state is Do Not Upgrade, return without modifying request.
if (upgrade_state == InsecureRequestsPolicy::DoNotUpgrade)
@@ -131,19 +72,4 @@ void upgrade_request_to_a_potentially_trustworthy_url_if_appropriate(Fetch::Infr
}
}
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#should-upgrade-for-client
-InsecureRequestsPolicy should_insecure_requests_be_upgraded_for_client(GC::Ptr<HTML::EnvironmentSettingsObject> client)
-{
- // AD-HOC: Fetch requests initiated by the browser UI have no client. Their requests are never upgraded.
- if (!client)
- return InsecureRequestsPolicy::DoNotUpgrade;
-
- // 1. If client has a responsible document, return the value of its insecure requests policy.
- // 2. If client has a responsible browsing context, return the value of its insecure requests policy.
- // 3. Return Do Not Upgrade.
- // NB: A client's responsible document's insecure requests policy is the client's own, which includes what it
- // inherited from its responsible browsing context. See EnvironmentSettingsObject::insecure_requests_policy().
- return client->insecure_requests_policy();
-}
-
}
diff --git a/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.h b/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.h
index 167906e4408..f8af8477534 100644
--- a/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.h
+++ b/Libraries/LibWeb/UpgradeInsecureRequests/AbstractOperations.h
@@ -6,19 +6,11 @@
#pragma once
-#include <LibGC/Ptr.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
-#include <LibWebCommon/UpgradeInsecureRequests/InsecureRequestsPolicy.h>
namespace Web::UpgradeInsecureRequests {
-void inherit_the_insecure_requests_policy_into_a_nested_browsing_context(HTML::BrowsingContext&, InsecureRequestsPolicy embedding_document_policy, UpgradeInsecureNavigationsSet const& embedding_document_set);
-void inherit_the_insecure_requests_policy_into_a_new_document(HTML::EnvironmentSettingsObject& document_settings, HTML::BrowsingContext const&);
-void inherit_the_insecure_requests_policy_into_a_worker(HTML::EnvironmentSettingsObject& settings_object, InsecureRequestsPolicy outside_settings_policy, UpgradeInsecureNavigationsSet const& outside_settings_set);
-
WEB_API void upgrade_request_to_a_potentially_trustworthy_url_if_appropriate(Fetch::Infrastructure::Request&);
-InsecureRequestsPolicy should_insecure_requests_be_upgraded_for_client(GC::Ptr<HTML::EnvironmentSettingsObject>);
-
}
diff --git a/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h b/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h
index 0898af6fe94..73053ef4c92 100644
--- a/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h
+++ b/Libraries/LibWebCommon/HTML/ReplicatedNavigableState.h
@@ -54,12 +54,11 @@ struct ReplicatedContainerState {
PermissionsPolicy::PolicyDirective container_policy {};
// https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy, of the container's node
- // document's relevant settings object, which a browsing context created for the navigable in another process
- // inherits.
+ // document's policy container, which a document created in the navigable inherits.
UpgradeInsecureRequests::InsecureRequestsPolicy document_insecure_requests_policy { UpgradeInsecureRequests::InsecureRequestsPolicy::DoNotUpgrade };
// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set, of the container's
- // node document's relevant settings object.
+ // node document's policy container.
UpgradeInsecureRequests::UpgradeInsecureNavigationsSet document_upgrade_insecure_navigations_set {};
};
diff --git a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp
index 367dc9d3596..295b18d8490 100644
--- a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp
+++ b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.cpp
@@ -67,8 +67,6 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::SerializedEnvironmentSettingsO
TRY(encoder.encode(object.agent_cluster_id));
TRY(encoder.encode(object.agent_cluster_cross_origin_isolation_mode));
TRY(encoder.encode(object.time_origin));
- TRY(encoder.encode(object.insecure_requests_policy));
- TRY(encoder.encode(object.upgrade_insecure_navigations_set));
TRY(encoder.encode(object.global));
return {};
@@ -90,8 +88,6 @@ ErrorOr<Web::HTML::SerializedEnvironmentSettingsObject> decode(Decoder& decoder)
.agent_cluster_id = TRY(decoder.decode<Optional<u64>>()),
.agent_cluster_cross_origin_isolation_mode = TRY(decoder.decode<Web::HTML::CrossOriginIsolationMode>()),
.time_origin = TRY(decoder.decode<double>()),
- .insecure_requests_policy = TRY(decoder.decode<Web::UpgradeInsecureRequests::InsecureRequestsPolicy>()),
- .upgrade_insecure_navigations_set = TRY(decoder.decode<Web::UpgradeInsecureRequests::UpgradeInsecureNavigationsSet>()),
.global = TRY(decoder.decode<Web::HTML::SerializedGlobal>()),
};
}
diff --git a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h
index 9a7ea6402ce..fd094e4f094 100644
--- a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h
+++ b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h
@@ -14,7 +14,6 @@
#include <LibWebCommon/HTML/CrossOriginIsolationMode.h>
#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>
#include <LibWebCommon/HTML/SerializedPolicyContainer.h>
-#include <LibWebCommon/UpgradeInsecureRequests/InsecureRequestsPolicy.h>
namespace Web::HTML {
@@ -60,13 +59,6 @@ struct SerializedEnvironmentSettingsObject {
Optional<u64> agent_cluster_id;
CrossOriginIsolationMode agent_cluster_cross_origin_isolation_mode;
double time_origin;
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy
- UpgradeInsecureRequests::InsecureRequestsPolicy insecure_requests_policy { UpgradeInsecureRequests::InsecureRequestsPolicy::DoNotUpgrade };
-
- // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
- UpgradeInsecureRequests::UpgradeInsecureNavigationsSet upgrade_insecure_navigations_set {};
-
SerializedGlobal global;
};
diff --git a/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.cpp b/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.cpp
index 41f58987f4b..8cd8f94ab18 100644
--- a/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.cpp
+++ b/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.cpp
@@ -17,6 +17,8 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::SerializedPolicyContainer cons
TRY(encoder.encode(serialized_policy_container.embedder_policy));
TRY(encoder.encode(serialized_policy_container.referrer_policy));
TRY(encoder.encode(serialized_policy_container.force_load_at_top));
+ TRY(encoder.encode(serialized_policy_container.insecure_requests_policy));
+ TRY(encoder.encode(serialized_policy_container.upgrade_insecure_navigations_set));
return {};
}
@@ -30,6 +32,8 @@ ErrorOr<Web::HTML::SerializedPolicyContainer> decode(Decoder& decoder)
serialized_policy_container.embedder_policy = TRY(decoder.decode<Web::HTML::EmbedderPolicy>());
serialized_policy_container.referrer_policy = TRY(decoder.decode<Web::ReferrerPolicy::ReferrerPolicy>());
serialized_policy_container.force_load_at_top = TRY(decoder.decode<bool>());
+ serialized_policy_container.insecure_requests_policy = TRY(decoder.decode<Web::UpgradeInsecureRequests::InsecureRequestsPolicy>());
+ serialized_policy_container.upgrade_insecure_navigations_set = TRY(decoder.decode<Web::UpgradeInsecureRequests::UpgradeInsecureNavigationsSet>());
return serialized_policy_container;
}
diff --git a/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.h b/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.h
index cb11037c140..abab97891b5 100644
--- a/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.h
+++ b/Libraries/LibWebCommon/HTML/SerializedPolicyContainer.h
@@ -10,6 +10,7 @@
#include <LibWebCommon/Export.h>
#include <LibWebCommon/HTML/EmbedderPolicy.h>
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
+#include <LibWebCommon/UpgradeInsecureRequests/InsecureRequestsPolicy.h>
namespace Web::HTML {
@@ -18,6 +19,8 @@ struct SerializedPolicyContainer {
EmbedderPolicy embedder_policy;
ReferrerPolicy::ReferrerPolicy referrer_policy;
bool force_load_at_top { false };
+ UpgradeInsecureRequests::InsecureRequestsPolicy insecure_requests_policy { UpgradeInsecureRequests::InsecureRequestsPolicy::DoNotUpgrade };
+ UpgradeInsecureRequests::UpgradeInsecureNavigationsSet upgrade_insecure_navigations_set {};
};
}
diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cpp
index 55d9013af56..5bdfe772965 100644
--- a/Libraries/LibWebView/CanonicalNavigable.cpp
+++ b/Libraries/LibWebView/CanonicalNavigable.cpp
@@ -1138,6 +1138,7 @@ void CanonicalNavigable::update_container_state(Web::HTML::ReplicatedContainerSt
m_hosted_state->container = state;
if (has_remote_host())
remote_host().async_update_local_root_container_state(id(), move(state));
+ send_replicated_state();
}
void CanonicalNavigable::update_hosted_state(Web::HTML::HostedNavigableState state)
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-at-fetch-start.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-at-fetch-start.txt
new file mode 100644
index 00000000000..ce13b5cd02d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-at-fetch-start.txt
@@ -0,0 +1,2 @@
+Redirect of a fetch started before the policy: failed
+Redirect of a fetch started after the policy: loaded
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-cross-process.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-cross-process.txt
new file mode 100644
index 00000000000..27ee9ef3ae0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-cross-process.txt
@@ -0,0 +1,4 @@
+Cross-site iframe is in another process: true
+Frame document fetch before the policy: failed
+Frame document fetch after the policy: failed
+Fetch from the frame's next document: loaded
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-new-host.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-new-host.txt
new file mode 100644
index 00000000000..cf0953ac407
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-new-host.txt
@@ -0,0 +1,2 @@
+Cross-site iframe is in another process: true
+Fetch from the frame's next document, in the other site's process: loaded
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-shadow-tree.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-shadow-tree.txt
new file mode 100644
index 00000000000..27ee9ef3ae0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-shadow-tree.txt
@@ -0,0 +1,4 @@
+Cross-site iframe is in another process: true
+Frame document fetch before the policy: failed
+Frame document fetch after the policy: failed
+Fetch from the frame's next document: loaded
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance.txt
new file mode 100644
index 00000000000..cc55cf858b9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance.txt
@@ -0,0 +1,3 @@
+Frame document fetch before the policy: failed
+Frame document fetch after the policy: failed
+Fetch from the frame's next document: loaded
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-history-traversal.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-history-traversal.txt
new file mode 100644
index 00000000000..b6c97ed3284
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-history-traversal.txt
@@ -0,0 +1,3 @@
+Fetch from the about:blank entry: loaded
+Document after Back is rebuilt: true
+Fetch from the rebuilt document: loaded
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-link-at-fetch-start.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-link-at-fetch-start.txt
new file mode 100644
index 00000000000..a9aad6c567f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-link-at-fetch-start.txt
@@ -0,0 +1,2 @@
+Redirect of a stylesheet load started before the policy: failed
+Redirect of a stylesheet load started after the policy: loaded
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-navigations-set-growth.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-navigations-set-growth.txt
new file mode 100644
index 00000000000..4d20d6b38aa
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-navigations-set-growth.txt
@@ -0,0 +1 @@
+Popup of the child's next document loaded over: https:
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-popup-inheritance.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-popup-inheritance.txt
new file mode 100644
index 00000000000..09f2e224844
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/upgrade-insecure-requests-popup-inheritance.txt
@@ -0,0 +1,2 @@
+iframe fetch: loaded
+Fetch from the iframe's about:blank popup: loaded
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-at-fetch-start.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-at-fetch-start.html
new file mode 100644
index 00000000000..612b4c8bf81
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-at-fetch-start.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ const httpsPort = internals.getHttpsEchoServerPort();
+ const resource = `http://127.0.0.1:${httpsPort}/common/blank.html`;
+ const redirect = `https://127.0.0.1:${httpsPort}/common/redirect.py?location=${encodeURIComponent(resource)}`;
+
+ async function tryFetch(url) {
+ try {
+ await fetch(url, { mode: "no-cors" });
+ return "loaded";
+ } catch {
+ return "failed";
+ }
+ }
+
+ // A fetch upgrades its redirects by the policies its client had when the fetch started.
+ asyncTest(async done => {
+ const fetchStartedBeforeThePolicy = tryFetch(redirect);
+
+ const meta = document.createElement("meta");
+ meta.httpEquiv = "Content-Security-Policy";
+ meta.content = "upgrade-insecure-requests";
+ document.head.appendChild(meta);
+
+ println(`Redirect of a fetch started before the policy: ${await fetchStartedBeforeThePolicy}`);
+ println(`Redirect of a fetch started after the policy: ${await tryFetch(redirect)}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-cross-process.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-cross-process.html
new file mode 100644
index 00000000000..55d350fd117
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-cross-process.html
@@ -0,0 +1,72 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ // The frame is cross-site with this document, so another process hosts it, and it enforces no policy of its own:
+ // its documents upgrade it only if they inherited ours, which that process learns from our reports.
+ const httpsPort = internals.getHttpsEchoServerPort();
+ const resource = `http://127.0.0.1:${httpsPort}/common/blank.html`;
+ const secureServer = new HTTPTestServer(`https://127.0.0.1:${httpsPort}`);
+
+ const fetchSource = `
+ async function tryFetch(url) {
+ try {
+ await fetch(url, { mode: "no-cors" });
+ return "loaded";
+ } catch {
+ return "failed";
+ }
+ }`;
+
+ function nextMessage() {
+ return new Promise(resolve => {
+ window.addEventListener("message", event => resolve(event.data), { once: true });
+ });
+ }
+
+ // A document created in a child navigable inherits the policy its container's document has at that point.
+ asyncTest(async done => {
+ const nextDocumentURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-child-document-inheritance/next.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<script>${fetchSource}; tryFetch("${resource}").then(result => parent.postMessage(result, "*"));<\/script>`,
+ });
+ const frameURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-child-document-inheritance/frame.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<script>
+ ${fetchSource}
+ onmessage = async event => {
+ if (event.data === "fetch")
+ parent.postMessage(await tryFetch("${resource}"), "*");
+ else
+ location.href = "${nextDocumentURL}";
+ };
+ parent.postMessage("ready", "*");
+ <\/script>`,
+ });
+
+ const frame = document.createElement("iframe");
+ const ready = nextMessage();
+ frame.src = frameURL;
+ document.body.appendChild(frame);
+ await ready;
+ println(`Cross-site iframe is in another process: ${remoteFrameCount() > 0}`);
+
+ frame.contentWindow.postMessage("fetch", "*");
+ println(`Frame document fetch before the policy: ${await nextMessage()}`);
+
+ const meta = document.createElement("meta");
+ meta.httpEquiv = "Content-Security-Policy";
+ meta.content = "upgrade-insecure-requests";
+ document.head.appendChild(meta);
+ frame.contentWindow.postMessage("fetch", "*");
+ println(`Frame document fetch after the policy: ${await nextMessage()}`);
+
+ // The frame's document navigates itself, without a change to the iframe that would report its state.
+ frame.contentWindow.postMessage("navigate", "*");
+ println(`Fetch from the frame's next document: ${await nextMessage()}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-new-host.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-new-host.html
new file mode 100644
index 00000000000..e990b5c67ed
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-new-host.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ // The cross-site frame puts its site in another process. After we enforce a policy, the srcdoc frame, which is in
+ // ours, navigates to that site, so the other process creates its next document from its copy of the frame's
+ // container state.
+ const httpsPort = internals.getHttpsEchoServerPort();
+ const resource = `http://127.0.0.1:${httpsPort}/common/blank.html`;
+ const secureServer = new HTTPTestServer(`https://127.0.0.1:${httpsPort}`);
+
+ function loaded(frame) {
+ return new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
+ }
+
+ asyncTest(async done => {
+ const otherSiteURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-child-document-inheritance-new-host/other.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: "<!DOCTYPE html>other",
+ });
+ const nextDocumentURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-child-document-inheritance-new-host/next.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<script>
+ fetch("${resource}", { mode: "no-cors" }).then(() => "loaded", () => "failed").then(result => top.postMessage(result, "*"));
+ <\/script>`,
+ });
+
+ const otherSiteFrame = document.createElement("iframe");
+ const otherSiteLoaded = loaded(otherSiteFrame);
+ otherSiteFrame.src = otherSiteURL;
+ document.body.appendChild(otherSiteFrame);
+
+ const frame = document.createElement("iframe");
+ const frameLoaded = loaded(frame);
+ frame.srcdoc = "<!DOCTYPE html>first";
+ document.body.appendChild(frame);
+
+ await otherSiteLoaded;
+ await frameLoaded;
+ println(`Cross-site iframe is in another process: ${remoteFrameCount() > 0}`);
+
+ const meta = document.createElement("meta");
+ meta.httpEquiv = "Content-Security-Policy";
+ meta.content = "upgrade-insecure-requests";
+ document.head.appendChild(meta);
+
+ const nextMessage = new Promise(resolve => addEventListener("message", event => resolve(event.data), { once: true }));
+ frame.contentWindow.location.href = nextDocumentURL;
+ println(`Fetch from the frame's next document, in the other site's process: ${await nextMessage}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-shadow-tree.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-shadow-tree.html
new file mode 100644
index 00000000000..c5bc9d4ee0e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance-shadow-tree.html
@@ -0,0 +1,73 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ // The frame is cross-site with this document, so another process hosts it, and it enforces no policy of its own:
+ // its documents upgrade it only if they inherited ours, which that process learns from our reports.
+ const httpsPort = internals.getHttpsEchoServerPort();
+ const resource = `http://127.0.0.1:${httpsPort}/common/blank.html`;
+ const secureServer = new HTTPTestServer(`https://127.0.0.1:${httpsPort}`);
+
+ const fetchSource = `
+ async function tryFetch(url) {
+ try {
+ await fetch(url, { mode: "no-cors" });
+ return "loaded";
+ } catch {
+ return "failed";
+ }
+ }`;
+
+ function nextMessage() {
+ return new Promise(resolve => {
+ window.addEventListener("message", event => resolve(event.data), { once: true });
+ });
+ }
+
+ // A document created in a child navigable whose container is in a shadow tree inherits the policy its container's
+ // document has at that point.
+ asyncTest(async done => {
+ const nextDocumentURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-child-document-inheritance-shadow-tree/next.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<script>${fetchSource}; tryFetch("${resource}").then(result => parent.postMessage(result, "*"));<\/script>`,
+ });
+ const frameURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-child-document-inheritance-shadow-tree/frame.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<script>
+ ${fetchSource}
+ onmessage = async event => {
+ if (event.data === "fetch")
+ parent.postMessage(await tryFetch("${resource}"), "*");
+ else
+ location.href = "${nextDocumentURL}";
+ };
+ parent.postMessage("ready", "*");
+ <\/script>`,
+ });
+
+ const frame = document.createElement("iframe");
+ const ready = nextMessage();
+ frame.src = frameURL;
+ document.body.appendChild(document.createElement("div")).attachShadow({ mode: "open" }).appendChild(frame);
+ await ready;
+ println(`Cross-site iframe is in another process: ${remoteFrameCount() > 0}`);
+
+ frame.contentWindow.postMessage("fetch", "*");
+ println(`Frame document fetch before the policy: ${await nextMessage()}`);
+
+ const meta = document.createElement("meta");
+ meta.httpEquiv = "Content-Security-Policy";
+ meta.content = "upgrade-insecure-requests";
+ document.head.appendChild(meta);
+ frame.contentWindow.postMessage("fetch", "*");
+ println(`Frame document fetch after the policy: ${await nextMessage()}`);
+
+ // The frame's document navigates itself, without a change to the iframe that would report its state.
+ frame.contentWindow.postMessage("navigate", "*");
+ println(`Fetch from the frame's next document: ${await nextMessage()}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance.html
new file mode 100644
index 00000000000..516ce2901b4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-child-document-inheritance.html
@@ -0,0 +1,46 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ // The frame enforces no policy of its own: its documents upgrade it only if they inherited ours.
+ const resource = `http://127.0.0.1:${internals.getHttpsEchoServerPort()}/common/blank.html`;
+
+ const fetchSource = `
+ async function tryFetch(url) {
+ try {
+ await fetch(url, { mode: "no-cors" });
+ return "loaded";
+ } catch {
+ return "failed";
+ }
+ }`;
+
+ function loadOf(frame) {
+ return new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
+ }
+
+ // A document created in a child navigable inherits the policy its container's document has at that point.
+ asyncTest(async done => {
+ const frame = document.createElement("iframe");
+ frame.srcdoc = `<script>${fetchSource}; onmessage = () => { location.href = "about:blank"; };<\/script>`;
+ let loaded = loadOf(frame);
+ document.body.appendChild(frame);
+ await loaded;
+ println(`Frame document fetch before the policy: ${await frame.contentWindow.tryFetch(resource)}`);
+
+ const meta = document.createElement("meta");
+ meta.httpEquiv = "Content-Security-Policy";
+ meta.content = "upgrade-insecure-requests";
+ document.head.appendChild(meta);
+ println(`Frame document fetch after the policy: ${await frame.contentWindow.tryFetch(resource)}`);
+
+ // The frame's document navigates itself, so the navigation's initiator holds no policy.
+ loaded = loadOf(frame);
+ frame.contentWindow.postMessage("navigate", "*");
+ await loaded;
+ frame.contentWindow.eval(fetchSource);
+ println(`Fetch from the frame's next document: ${await frame.contentWindow.tryFetch(resource)}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-history-traversal.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-history-traversal.html
new file mode 100644
index 00000000000..dcb6d5871d4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-history-traversal.html
@@ -0,0 +1,108 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<!-- The policy comes after include.js, which it would otherwise upgrade. -->
+<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ // The frame inherits our policy and enforces none of its own, so the about:blank document it navigates its popup to
+ // has the policy only as state it inherited, which the document's history entry keeps. Going back to that entry from
+ // a cross-site document rebuilds the about:blank document from the entry: a fetch it had in flight when the popup
+ // navigated away makes it unsalvageable, and the popup is top-level, with nothing else to inherit from.
+ const httpsPort = internals.getHttpsEchoServerPort();
+ const secureServer = new HTTPTestServer(`https://127.0.0.1:${httpsPort}`);
+ const resource = `http://127.0.0.1:${httpsPort}/common/blank.html`;
+ const token = uniqueID();
+
+ function echo(path, body, hostname = "127.0.0.1", extra = {}) {
+ return secureServer
+ .createEcho("GET", `/upgrade-insecure-requests-history-traversal/${path}`, {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body,
+ ...extra,
+ })
+ .then(url => {
+ const result = new URL(url);
+ result.hostname = hostname;
+ return result.href;
+ });
+ }
+
+ asyncTest(async done => {
+ const heldURL = await echo(`held-${token}.html`, "", "127.0.0.1", { wait_for_unblock: token });
+ const startURL = await echo("start.html", `<script>opener.postMessage("started", "*");<\/script>`);
+ const nextURL = await echo("next.html", `<script>opener.postMessage("going back", "*"); history.back();<\/script>`, "localhost");
+ const frameURL = await echo(
+ "frame.html",
+ `<script>
+ const fetchSource = \`
+ async function tryFetch(url) {
+ try {
+ await fetch(url, { mode: "no-cors" });
+ return "loaded";
+ } catch {
+ return "failed";
+ }
+ }\`;
+ const nextMessage = () => new Promise(resolve => addEventListener("message", event => resolve(event.data), { once: true }));
+ function showsAboutBlank(popup) {
+ try {
+ return popup.location.href === "about:blank" && popup.document.readyState === "complete";
+ } catch {
+ return false;
+ }
+ }
+ async function whenShowsAboutBlank(popup) {
+ const deadline = performance.now() + 10000;
+ while (!showsAboutBlank(popup)) {
+ if (performance.now() > deadline)
+ throw new Error("The popup did not show about:blank");
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ }
+
+ (async () => {
+ const started = nextMessage();
+ const popup = window.open(${JSON.stringify(startURL)});
+ await started;
+
+ popup.location.href = "about:blank";
+ await whenShowsAboutBlank(popup);
+ popup.eval(fetchSource);
+ parent.postMessage(\`Fetch from the about:blank entry: \${await popup.tryFetch(${JSON.stringify(resource)})}\`, "*");
+
+ popup.marker = "original";
+ popup.fetch(${JSON.stringify(heldURL)}, { mode: "no-cors" }).catch(() => {});
+ const goingBack = nextMessage();
+ popup.location.href = ${JSON.stringify(nextURL)};
+ await goingBack;
+ await whenShowsAboutBlank(popup);
+
+ parent.postMessage(\`Document after Back is rebuilt: \${popup.marker === undefined}\`, "*");
+ popup.eval(fetchSource);
+ parent.postMessage(\`Fetch from the rebuilt document: \${await popup.tryFetch(${JSON.stringify(resource)})}\`, "*");
+ popup.close();
+ })().catch(error => parent.postMessage(\`Failed: \${error.message}\`, "*"));
+ <\/script>`
+ );
+
+ const messages = [];
+ const finished = new Promise(resolve => {
+ addEventListener("message", event => {
+ messages.push(event.data);
+ if (messages.length === 3 || event.data.startsWith("Failed:"))
+ resolve();
+ });
+ });
+ const frame = document.createElement("iframe");
+ frame.src = frameURL;
+ document.body.appendChild(frame);
+ await finished;
+
+ for (const message of messages)
+ println(message);
+
+ await fetch(`https://127.0.0.1:${httpsPort}/unblock/${token}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-link-at-fetch-start.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-link-at-fetch-start.html
new file mode 100644
index 00000000000..9f72f28a020
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-link-at-fetch-start.html
@@ -0,0 +1,41 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ const httpsPort = internals.getHttpsEchoServerPort();
+ const secureServer = new HTTPTestServer(`https://127.0.0.1:${httpsPort}`);
+
+ function loadStylesheet(url) {
+ return new Promise(resolve => {
+ const link = document.createElement("link");
+ link.rel = "stylesheet";
+ link.onload = () => resolve("loaded");
+ link.onerror = () => resolve("failed");
+ link.href = url;
+ document.head.appendChild(link);
+ });
+ }
+
+ // A link element's fetch upgrades its redirects by the policies its document had when the fetch started.
+ asyncTest(async done => {
+ const stylesheetURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-link-at-fetch-start/style.css", {
+ status: 200,
+ headers: { "Content-Type": "text/css" },
+ body: "",
+ });
+ const resource = stylesheetURL.replace("https:", "http:");
+ const redirect = `https://127.0.0.1:${httpsPort}/common/redirect.py?location=${encodeURIComponent(resource)}`;
+
+ const loadStartedBeforeThePolicy = loadStylesheet(redirect);
+
+ const meta = document.createElement("meta");
+ meta.httpEquiv = "Content-Security-Policy";
+ meta.content = "upgrade-insecure-requests";
+ document.head.appendChild(meta);
+
+ println(`Redirect of a stylesheet load started before the policy: ${await loadStartedBeforeThePolicy}`);
+ println(`Redirect of a stylesheet load started after the policy: ${await loadStylesheet(redirect)}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-navigations-set-growth.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-navigations-set-growth.html
new file mode 100644
index 00000000000..30707b72406
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-navigations-set-growth.html
@@ -0,0 +1,73 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<!-- The policy comes after include.js, which it would otherwise upgrade. -->
+<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
+<script>
+ // This port serves HTTPS, so a navigation to an http: URL with it only succeeds if the request was upgraded to
+ // https:. A top-level navigation is upgraded only if its URL's host and port are in its source's upgrade insecure
+ // navigations set. The frame inherits our policy, then enforces one of its own, which adds its host and port to
+ // its set but leaves its policy as it was. Its child is cross-site with it, so another process hosts the child,
+ // whose next document inherits the frame's set as that process last learned it.
+ const httpsPort = internals.getHttpsEchoServerPort();
+ const secureServer = new HTTPTestServer(`https://127.0.0.1:${httpsPort}`);
+
+ function echo(path, body, hostname = "127.0.0.1") {
+ return secureServer
+ .createEcho("GET", `/upgrade-insecure-requests-navigations-set-growth/${path}`, {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body,
+ })
+ .then(url => {
+ const result = new URL(url);
+ result.hostname = hostname;
+ return result.href;
+ });
+ }
+
+ asyncTest(async done => {
+ const popupURL = await echo("popup.html", `<script>opener.postMessage(location.protocol, "*"); close();<\/script>`);
+ const insecurePopupURL = popupURL.replace("https:", "http:");
+ const nextDocumentURL = await echo(
+ "next.html",
+ `<script>
+ addEventListener("message", event => top.postMessage(event.data, "*"));
+ window.open(${JSON.stringify(insecurePopupURL)});
+ <\/script>`,
+ "localhost"
+ );
+ const childURL = await echo(
+ "child.html",
+ `<script>
+ addEventListener("message", () => (location.href = ${JSON.stringify(nextDocumentURL)}));
+ parent.postMessage("ready", "*");
+ <\/script>`,
+ "localhost"
+ );
+ const frameURL = await echo(
+ "frame.html",
+ `<body><script>
+ addEventListener("message", event => {
+ if (event.data !== "ready")
+ return;
+ const meta = document.createElement("meta");
+ meta.httpEquiv = "Content-Security-Policy";
+ meta.content = "upgrade-insecure-requests";
+ document.head.appendChild(meta);
+ event.source.postMessage("navigate", "*");
+ });
+ const child = document.createElement("iframe");
+ child.src = ${JSON.stringify(childURL)};
+ document.body.appendChild(child);
+ <\/script>`
+ );
+
+ const popupLoaded = new Promise(resolve => addEventListener("message", event => resolve(event.data), { once: true }));
+ const frame = document.createElement("iframe");
+ frame.src = frameURL;
+ document.body.appendChild(frame);
+
+ println(`Popup of the child's next document loaded over: ${await popupLoaded}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-popup-inheritance.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-popup-inheritance.html
new file mode 100644
index 00000000000..8ad2928179a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/upgrade-insecure-requests-popup-inheritance.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<!-- The policy comes after include.js, which it would otherwise upgrade. -->
+<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
+<script>
+ // This port serves HTTPS, so a fetch of an http: URL with it only succeeds if the request was upgraded to https:.
+ // The frame enforces no policy of its own: it upgrades it only if it inherited ours. Its popup's initial
+ // about:blank document has a copy of the frame's policies, so it upgrades it if the frame does.
+ const insecureOrigin = `http://127.0.0.1:${internals.getHttpsEchoServerPort()}`;
+ const resource = `${insecureOrigin}/common/blank.html`;
+ const secureServer = new HTTPTestServer(`https://127.0.0.1:${internals.getHttpsEchoServerPort()}`);
+
+ const fetchSource = `
+ async function tryFetch(url) {
+ try {
+ await fetch(url, { mode: "no-cors" });
+ return "loaded";
+ } catch {
+ return "failed";
+ }
+ }`;
+
+ function nextMessage() {
+ return new Promise(resolve => {
+ window.addEventListener("message", event => resolve(event.data), { once: true });
+ });
+ }
+
+ asyncTest(async done => {
+ const frameURL = await secureServer.createEcho("GET", "/upgrade-insecure-requests-popup-inheritance/frame.html", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<script>
+ const fetchSource = ${JSON.stringify(fetchSource)};
+ eval(fetchSource);
+ (async () => {
+ parent.postMessage(await tryFetch("${resource}"), "*");
+ const popup = window.open();
+ popup.eval(fetchSource);
+ parent.postMessage(await popup.tryFetch("${resource}"), "*");
+ popup.close();
+ })();
+ <\/script>`,
+ });
+
+ const frame = document.createElement("iframe");
+ frame.src = `${insecureOrigin}${new URL(frameURL).pathname}`;
+ document.body.appendChild(frame);
+
+ println(`iframe fetch: ${await nextMessage()}`);
+ println(`Fetch from the iframe's about:blank popup: ${await nextMessage()}`);
+
+ done();
+ });
+</script>