Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(service-worker): reject invalid registration query URLs

ldm040d476dbaf51
diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs
index 69e116d4e..fe3284487 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/service_worker.rs
@@ -1127,20 +1127,45 @@ pub(in crate::context_bootstrap) fn navigator_service_worker_get_registration_ca
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
- let value: v8::Local<'_, v8::Value> = if let Some(host_ptr) =
- context_host_ptr_from_global_bridge(scope)
- {
- let host = unsafe { &mut *host_ptr };
- let owner = service_worker_container_owner_scope(scope, args.this());
- let state = host
- .service_worker_window_request_context(owner)
- .and_then(|request_context| {
- service_worker_client_url(request_context.document_url(), &parsed.client_url)
- .and_then(|client_url| {
- host.service_worker_registration_for_client(&request_context, &client_url)
- })
- });
- if let Some(state) = state {
+ let promise = resolver.get_promise(scope);
+ let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
+ let _ = resolver.resolve(scope, v8::undefined(scope).into());
+ rv.set(promise.into());
+ return;
+ };
+ let host = unsafe { &mut *host_ptr };
+ let owner = service_worker_container_owner_scope(scope, args.this());
+ let Some(request_context) = host.service_worker_window_request_context(owner) else {
+ let _ = resolver.resolve(scope, v8::undefined(scope).into());
+ rv.set(promise.into());
+ return;
+ };
+ let client_url =
+ match service_worker_client_url(request_context.document_url(), &parsed.client_url) {
+ Ok(client_url) => client_url,
+ Err(ServiceWorkerClientUrlError::Invalid) => {
+ reject_service_worker_promise_with_type_error(
+ scope,
+ resolver,
+ "Failed to parse the client URL.",
+ );
+ rv.set(promise.into());
+ return;
+ }
+ Err(ServiceWorkerClientUrlError::CrossOrigin) => {
+ reject_service_worker_promise_with_dom_exception(
+ scope,
+ resolver,
+ "The client URL must have the same origin as the document.",
+ "SecurityError",
+ );
+ rv.set(promise.into());
+ return;
+ }
+ };
+ let value: v8::Local<'_, v8::Value> = host
+ .service_worker_registration_for_client(&request_context, &client_url)
+ .map(|state| {
build_service_worker_registration_object_for_container(
scope,
args.this(),
@@ -1149,14 +1174,10 @@ pub(in crate::context_bootstrap) fn navigator_service_worker_get_registration_ca
ServiceWorkerRegistrationPhase::Snapshot(&state),
)
.into()
- } else {
- v8::undefined(scope).into()
- }
- } else {
- v8::undefined(scope).into()
- };
+ })
+ .unwrap_or_else(|| v8::undefined(scope).into());
let _ = resolver.resolve(scope, value);
- rv.set(resolver.get_promise(scope).into());
+ rv.set(promise.into());
}
pub(in crate::context_bootstrap) fn navigator_service_worker_get_registrations_callback<'s>(
@@ -2178,10 +2199,24 @@ fn service_worker_scope_url(
Some(scope_url)
}
-fn service_worker_client_url(document_url: &url::Url, client: &str) -> Option<url::Url> {
- let mut client_url = document_url.join(client).ok()?;
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum ServiceWorkerClientUrlError {
+ Invalid,
+ CrossOrigin,
+}
+
+fn service_worker_client_url(
+ document_url: &url::Url,
+ client: &str,
+) -> Result<url::Url, ServiceWorkerClientUrlError> {
+ let mut client_url = document_url
+ .join(client)
+ .map_err(|_| ServiceWorkerClientUrlError::Invalid)?;
+ if !moli_url::same_origin(document_url, &client_url) {
+ return Err(ServiceWorkerClientUrlError::CrossOrigin);
+ }
client_url.set_fragment(None);
- Some(client_url)
+ Ok(client_url)
}
fn default_service_worker_scope_url(script_url: &url::Url) -> url::Url {
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
index 85dacaae6..32ff5652b 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
@@ -29000,3 +29000,90 @@ fn blob_url_revocation_respects_browser_partitions_and_allows_same_origin_realms
assert!(crate::blob::object_url_body_and_type(&url).is_none());
}
}
+
+#[tokio::test]
+async fn navigator_service_worker_url_arguments_follow_webidl_and_origin_rules() {
+ let (base_url, server) =
+ spawn_service_worker_script_server(vec!["/worker.js", "/resources/worker.js"]).await;
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
+ let (mut vm, browser_context_runtime) =
+ new_service_worker_page_test_vm_with_loader_and_browser_context_runtime(
+ &format!("{base_url}/page.html"),
+ &loader,
+ );
+
+ vm.eval(
+ r#"
+ (() => {
+ const sw = navigator.serviceWorker;
+ const rejectionName = promise => promise.then(
+ () => "resolved",
+ error => error && error.name
+ );
+ globalThis.__serviceWorkerUrlArgumentProbe = { state: "pending" };
+ (async () => {
+ const registration = await sw.register("/worker.js", { scope: "null" });
+ const nullClientMatches = await sw.getRegistration(null) === registration;
+ const crossOrigin = await rejectionName(
+ sw.getRegistration("http://example.com/")
+ );
+ const invalidClientUrl = await rejectionName(
+ sw.getRegistration("https://[")
+ );
+ const nullScope = await rejectionName(
+ sw.register("/resources/worker.js", { scope: null })
+ );
+ const nullType = await rejectionName(
+ sw.register("/worker.js", { type: null })
+ );
+ const nullUpdateViaCache = await rejectionName(
+ sw.register("/worker.js", { updateViaCache: null })
+ );
+ const primitiveOptions = await rejectionName(
+ sw.register("/worker.js", 1)
+ );
+ const symbolClient = await rejectionName(
+ sw.getRegistration(Symbol("client"))
+ );
+ const unregistered = await registration.unregister();
+ globalThis.__serviceWorkerUrlArgumentProbe = {
+ state: "done",
+ nullClientMatches,
+ crossOrigin,
+ invalidClientUrl,
+ nullScope,
+ nullType,
+ nullUpdateViaCache,
+ primitiveOptions,
+ symbolClient,
+ unregistered
+ };
+ })().catch(error => {
+ globalThis.__serviceWorkerUrlArgumentProbe = {
+ state: "error",
+ error: String(error)
+ };
+ });
+ })()
+ "#,
+ )
+ .expect("service worker URL argument probe should evaluate");
+
+ drain_service_worker_test_until_eval_equals(
+ &mut vm,
+ &browser_context_runtime,
+ &loader,
+ "String(globalThis.__serviceWorkerUrlArgumentProbe.state !== 'pending')",
+ "true",
+ )
+ .await;
+
+ assert_eq!(
+ vm.eval("JSON.stringify(globalThis.__serviceWorkerUrlArgumentProbe)")
+ .expect("service worker URL argument result should evaluate"),
+ r#"{"state":"done","nullClientMatches":true,"crossOrigin":"SecurityError","invalidClientUrl":"TypeError","nullScope":"SecurityError","nullType":"TypeError","nullUpdateViaCache":"TypeError","primitiveOptions":"TypeError","symbolClient":"TypeError","unregistered":true}"#
+ );
+ server
+ .await
+ .expect("service worker URL argument script server should finish");
+}