Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(location): apply protocol setter scheme rules

ldm0ced40f990640
diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/install.rs
index f26e5416c..b2e36341c 100644
--- a/moli-renderer-v8/src/context_bootstrap/location_runtime/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/install.rs
@@ -415,10 +415,34 @@ fn location_writable_attribute_setter_callback<'s>(
});
}
LocationAttribute::Protocol => {
- let scheme = value.strip_suffix(':').unwrap_or(&value).to_owned();
- navigate_modified_location_url(scope, holder, |current| {
- current.set_scheme(&scheme).is_ok()
- });
+ let Some(scheme) = location_protocol_scheme(&value) else {
+ crate::context_bootstrap::throw_dom_exception_value(
+ scope,
+ "The provided value is not a valid URL scheme.",
+ "SyntaxError",
+ );
+ return;
+ };
+ let Some(current_href) = location_href_slot(scope, holder) else {
+ return;
+ };
+ let Ok(mut target) = url::Url::parse(&current_href) else {
+ return;
+ };
+ // A syntactically valid scheme can still be incompatible with the
+ // current URL (for example, changing an HTTP URL to `data`). URL's
+ // scheme-state override treats that as a non-failing no-op.
+ if target.set_scheme(&scheme).is_err() || !matches!(target.scheme(), "http" | "https") {
+ return;
+ }
+ // Unlike the other component setters, protocol assignment must
+ // navigate even when parsing leaves the serialized URL unchanged.
+ navigate_location_object(
+ scope,
+ holder,
+ LocationNavigationKind::Assign,
+ Some(target.to_string()),
+ );
}
LocationAttribute::Host => {
navigate_modified_location_url(scope, holder, |current| {
@@ -449,6 +473,28 @@ fn location_writable_attribute_setter_callback<'s>(
rv.set_undefined();
}
+fn location_protocol_scheme(value: &str) -> Option<String> {
+ // Basic URL parsing removes ASCII tab and newline code points before the
+ // scheme-state override runs. The first colon terminates that state, so
+ // values such as `https::::` and `http:gunk` both provide only the scheme
+ // before their first colon.
+ let normalized = value
+ .chars()
+ .filter(|character| !matches!(character, '\t' | '\n' | '\r'))
+ .collect::<String>();
+ let candidate = normalized.split(':').next().unwrap_or_default();
+ let mut characters = candidate.chars();
+ let first = characters.next()?;
+ if !first.is_ascii_alphabetic()
+ || !characters.all(|character| {
+ character.is_ascii_alphanumeric() || matches!(character, '+' | '-' | '.')
+ })
+ {
+ return None;
+ }
+ Some(candidate.to_ascii_lowercase())
+}
+
fn location_hash_string(url: &url::Url) -> String {
match url.fragment() {
Some(fragment) if !fragment.is_empty() => format!("#{fragment}"),
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/events_errors.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/events_errors.rs
index 4163a1540..f15f115eb 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/events_errors.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/events_errors.rs
@@ -813,3 +813,100 @@ fn location_navigation_throws_syntax_error_for_unparseable_urls() {
"invalid Location navigation must not queue navigation"
);
}
+
+#[test]
+fn location_protocol_setter_rejects_invalid_schemes_without_navigation() {
+ let mut vm = new_storage_test_vm("https://example.com/path?x=1#frag");
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const originalHref = location.href;
+ const invalid = [
+ "", "\u0000", "\u0001", "\u000c", " ", "!", "\u007f",
+ "\u0080", "\u00ff", ":", "\u2020", "x!", "1http"
+ ];
+ const errors = invalid.map(value => {
+ try {
+ location.protocol = value;
+ return "returned";
+ } catch (error) {
+ return `${error.name}:${error.code}:${error instanceof DOMException}`;
+ }
+ });
+ return JSON.stringify({
+ allSyntaxErrors: errors.every(value => value === "SyntaxError:12:true"),
+ hrefUnchanged: location.href === originalHref
+ });
+})()
+"#,
+ )
+ .expect("invalid Location protocol probe should evaluate");
+
+ assert_eq!(result, r#"{"allSyntaxErrors":true,"hrefUnchanged":true}"#);
+ assert!(
+ vm.take_pending_location_navigation_with_seed().is_none(),
+ "invalid Location protocols must not queue navigation"
+ );
+}
+
+#[test]
+fn location_protocol_setter_uses_scheme_state_override_navigation_rules() {
+ let original = "http://example.com/path?x=1#frag";
+ let mut ignored_vm = new_storage_test_vm(original);
+ let ignored = ignored_vm
+ .eval(
+ r#"
+(() => {
+ const results = [];
+ for (const scheme of ["x", "data", "file", "ftp", "http+x"]) {
+ try {
+ location.protocol = scheme;
+ results.push(location.href);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ return JSON.stringify(results);
+})()
+"#,
+ )
+ .expect("non-HTTP Location protocol probe should evaluate");
+ assert_eq!(
+ ignored,
+ r#"["http://example.com/path?x=1#frag","http://example.com/path?x=1#frag","http://example.com/path?x=1#frag","http://example.com/path?x=1#frag","http://example.com/path?x=1#frag"]"#
+ );
+ assert!(
+ ignored_vm
+ .take_pending_location_navigation_with_seed()
+ .is_none(),
+ "non-HTTP(S) protocol results must not queue navigation"
+ );
+
+ let mut same_vm = new_storage_test_vm(original);
+ same_vm
+ .eval(r#"location.protocol = "ht\ntp:gunk"; "queued""#)
+ .expect("same Location protocol probe should evaluate");
+ assert_eq!(
+ same_vm
+ .take_pending_location_navigation_with_seed()
+ .expect("same protocol assignment should still navigate")
+ .url
+ .as_str(),
+ original
+ );
+
+ let mut changed_vm = new_storage_test_vm(original);
+ changed_vm
+ .eval(r#"location.protocol = "https::::"; "queued""#)
+ .expect("changed Location protocol probe should evaluate");
+ assert_eq!(
+ changed_vm
+ .take_pending_location_navigation_with_seed()
+ .expect("HTTP(S) protocol assignment should navigate")
+ .url
+ .as_str(),
+ "https://example.com/path?x=1#frag"
+ );
+}
diff --git a/moli-wpt-compat/fixtures/wpt/manifest.toml b/moli-wpt-compat/fixtures/wpt/manifest.toml
index 23356d6b3..edaea2a33 100644
--- a/moli-wpt-compat/fixtures/wpt/manifest.toml
+++ b/moli-wpt-compat/fixtures/wpt/manifest.toml
@@ -1358,7 +1358,7 @@ wait_until = "load"
timeout_ms = 5000
suite = "smoke"
tags = ["location"]
-notes = "Manual compat port for the stable HTTP subset of location.protocol assignment: assigning the current protocol with or without a trailing colon, assigning the same protocol with different casing, and assigning an invalid scheme leave URL and session history unchanged. Cross-scheme http/https navigation remains follow-up until the WPT fixture server exposes an HTTPS origin."
+notes = "Manual compat coverage for location.protocol failure boundaries: syntactically invalid schemes throw SyntaxError, while valid scheme-state overrides that do not produce an HTTP(S) URL leave the current URL and session history unchanged. Same-scheme and HTTP-to-HTTPS navigation are covered by renderer tests and upstream WPT."
[[test]]
id = "location-assign-fragment-history-basic"
diff --git a/moli-wpt-compat/fixtures/wpt/ported/location/location-protocol-noop-basic.html b/moli-wpt-compat/fixtures/wpt/ported/location/location-protocol-noop-basic.html
index d4aebdca9..7685cff27 100644
--- a/moli-wpt-compat/fixtures/wpt/ported/location/location-protocol-noop-basic.html
+++ b/moli-wpt-compat/fixtures/wpt/ported/location/location-protocol-noop-basic.html
@@ -9,24 +9,20 @@ test(function () {
const initialProtocol = location.protocol;
const initialLength = history.length;
- location.protocol = initialProtocol;
- assert_equals(location.href, initialHref, "assigning the current protocol should be a no-op");
- assert_equals(location.protocol, initialProtocol, "current protocol assignment should preserve protocol");
- assert_equals(history.length, initialLength, "current protocol assignment should not grow history");
+ for (const invalid of ["", "1invalid:", "!bad", "http bad"]) {
+ assert_throws_dom(
+ "SyntaxError",
+ () => { location.protocol = invalid; },
+ `invalid scheme ${JSON.stringify(invalid)} should throw`
+ );
+ }
- location.protocol = initialProtocol.toUpperCase();
- assert_equals(location.href, initialHref, "scheme setter should treat protocol case-insensitively");
- assert_equals(location.protocol, initialProtocol, "case-insensitive protocol assignment should preserve protocol");
- assert_equals(history.length, initialLength, "case-insensitive no-op should not grow history");
+ for (const ignored of ["data", "file", "ftp", "custom"]) {
+ location.protocol = ignored;
+ assert_equals(location.href, initialHref, `${ignored} must not navigate an HTTP document`);
+ assert_equals(location.protocol, initialProtocol, `${ignored} must preserve the HTTP protocol`);
+ }
- location.protocol = initialProtocol.slice(0, -1);
- assert_equals(location.href, initialHref, "protocol assignment without a trailing colon should normalize as the same scheme");
- assert_equals(location.protocol, initialProtocol, "colonless current protocol assignment should preserve protocol");
- assert_equals(history.length, initialLength, "colonless no-op should not grow history");
-
- location.protocol = "1invalid:";
- assert_equals(location.href, initialHref, "invalid protocol assignment should leave the URL unchanged");
- assert_equals(location.protocol, initialProtocol, "invalid protocol assignment should preserve protocol");
- assert_equals(history.length, initialLength, "invalid protocol assignment should not grow history");
-}, "location.protocol no-op and invalid assignments do not navigate");
+ assert_equals(history.length, initialLength, "rejected and ignored assignments should not grow history");
+}, "location.protocol rejects invalid schemes and ignores non-HTTP(S) results");
</script>