Truly independent web browser
LibURL: Compute the origin of a URL in Rust
Shannon Boothc25143677779
diff --git a/Cargo.lock b/Cargo.lockindex b29d6ea2be4..cfc74a6f068 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -818,6 +818,7 @@ dependencies = ["ak","cbindgen","encoding_rs",+ "getrandom","ladybird_allocator","libregex_rust","libunicode_rust",diff --git a/Libraries/LibURL/Rust/Cargo.toml b/Libraries/LibURL/Rust/Cargo.tomlindex ef4d5eb5a56..d9ba3c13a16 100644--- a/Libraries/LibURL/Rust/Cargo.toml+++ b/Libraries/LibURL/Rust/Cargo.toml@@ -9,6 +9,7 @@ crate-type = ["rlib", "staticlib"][dependencies]ak = { path = "../../../AK/Rust" }encoding_rs = "0.8.42"+getrandom = "0.4"ladybird_allocator = { path = "../../RustAllocator", optional = true }libregex_rust = { path = "../../LibRegex/Rust" }libunicode_rust = { path = "../../LibUnicode/Rust", features = ["idna"] }diff --git a/Libraries/LibURL/Rust/src/ffi.rs b/Libraries/LibURL/Rust/src/ffi.rsindex d527b88c261..6f41782d45b 100644--- a/Libraries/LibURL/Rust/src/ffi.rs+++ b/Libraries/LibURL/Rust/src/ffi.rs@@ -4,5 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/+pub mod origin;pub mod pattern;pub mod url;diff --git a/Libraries/LibURL/Rust/src/ffi/origin.rs b/Libraries/LibURL/Rust/src/ffi/origin.rsnew file mode 100644index 00000000000..4aaddb2767d--- /dev/null+++ b/Libraries/LibURL/Rust/src/ffi/origin.rs@@ -0,0 +1,82 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::ffi::c_void;++use crate::ffi::url::{FfiUrlHost, RustUrl, RustUrlByteSlice};+use crate::origin::{Nonce, OpaqueOriginKind, Origin};+use crate::rust_panic::abort_on_panic;+use crate::url::HostKind;++/// An origin borrowed across the FFI boundary. A tuple origin without a domain has a domain of kind Null.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiOrigin {+ pub is_opaque: bool,+ pub opaque_kind: OpaqueOriginKind,+ pub nonce: Nonce,+ pub scheme: RustUrlByteSlice,+ pub host: FfiUrlHost,+ pub has_port: bool,+ pub port: u16,+ pub domain: FfiUrlHost,+}++impl FfiOrigin {+ fn from_origin(origin: &Origin) -> Self {+ let null_host = FfiUrlHost::new(HostKind::Null, "");+ match origin {+ Origin::Opaque { nonce, kind } => Self {+ is_opaque: true,+ opaque_kind: *kind,+ nonce: *nonce,+ scheme: RustUrlByteSlice::from_str(""),+ host: null_host,+ has_port: false,+ port: 0,+ domain: null_host,+ },+ Origin::Tuple {+ scheme,+ host,+ port,+ domain,+ } => Self {+ is_opaque: false,+ opaque_kind: OpaqueOriginKind::Standard,+ nonce: Nonce::default(),+ scheme: RustUrlByteSlice::from_str(scheme),+ host: FfiUrlHost::new(host.kind, &host.serialization),+ has_port: port.is_some(),+ port: port.unwrap_or(0),+ domain: domain+ .as_ref()+ .map_or(null_host, |domain| FfiUrlHost::new(domain.kind, &domain.serialization)),+ },+ }+ }++ /// Lends the origin to `f` across the FFI boundary.+ pub fn with_origin<R>(origin: &Origin, f: impl FnOnce(&FfiOrigin) -> R) -> R {+ f(&Self::from_origin(origin))+ }+}++pub type FfiOriginResultFn = unsafe extern "C" fn(*mut c_void, *const FfiOrigin);++/// # Safety+/// `url` must be valid for the duration of this call. `on_complete` is called exactly once, with the origin of the+/// URL, which it borrows for the duration of that call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_url_origin(url: *const RustUrl, ctx: *mut c_void, on_complete: FfiOriginResultFn) {+ abort_on_panic(|| {+ let origin = unsafe { (*url).borrow() }.origin();+ FfiOrigin::with_origin(&origin, |ffi_origin| {+ // SAFETY: on_complete is a valid function pointer; ctx is caller-provided.+ unsafe { on_complete(ctx, ffi_origin) };+ });+ })+}diff --git a/Libraries/LibURL/Rust/src/ffi/url.rs b/Libraries/LibURL/Rust/src/ffi/url.rsindex 1a3f6dc06d9..31a429955f4 100644--- a/Libraries/LibURL/Rust/src/ffi/url.rs+++ b/Libraries/LibURL/Rust/src/ffi/url.rs@@ -28,7 +28,7 @@ pub struct RustUrlInput {impl RustUrlInput {/// # Safety/// The selected pointer must borrow length storage units. Byte input must be valid UTF-8.- unsafe fn borrow<'a>(self) -> UrlInput<'a> {+ pub(crate) unsafe fn borrow<'a>(self) -> UrlInput<'a> {if self.length == 0 {return UrlInput::Utf8("");}@@ -48,7 +48,7 @@ pub struct RustUrlByteSlice {}impl RustUrlByteSlice {- fn from_str(string: &str) -> Self {+ pub(crate) fn from_str(string: &str) -> Self {Self {data: string.as_ptr(),length: string.len(),@@ -103,7 +103,7 @@ pub struct FfiUrlHost {}impl FfiUrlHost {- fn new(kind: HostKind, serialized_host: &str) -> Self {+ pub(crate) fn new(kind: HostKind, serialized_host: &str) -> Self {let mut host = Self {kind,ipv4: [0; 4],diff --git a/Libraries/LibURL/Rust/src/lib.rs b/Libraries/LibURL/Rust/src/lib.rsindex 0c7b84349b7..0c9fb612c86 100644--- a/Libraries/LibURL/Rust/src/lib.rs+++ b/Libraries/LibURL/Rust/src/lib.rs@@ -14,6 +14,7 @@ mod rust_demangle;mod rust_panic;mod ffi;+pub mod origin;pub mod pattern;mod textcodec;pub mod url;@@ -24,6 +25,13 @@ pub use url::Url;pub use url::basic_parse;pub use url::basic_parse_with_state_override;+// LibURL's C++ is not linked into Rust unit tests.+#[cfg(test)]+#[unsafe(no_mangle)]+extern "C" fn url_rust_file_scheme_urls_have_tuple_origins() -> bool {+ false+}+// LibUnicode's C++ IDNA implementation is not linked into Rust unit tests.#[cfg(test)]#[unsafe(no_mangle)]diff --git a/Libraries/LibURL/Rust/src/origin.rs b/Libraries/LibURL/Rust/src/origin.rsnew file mode 100644index 00000000000..ebc5f5e96a3--- /dev/null+++ b/Libraries/LibURL/Rust/src/origin.rs@@ -0,0 +1,137 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use crate::url::{BasicParseOptions, HostKind, Url, basic_parse};++unsafe extern "C" {+ // NB: LibWeb's library links its own copy of this crate, so process-wide state lives in LibURL's C++.+ fn url_rust_file_scheme_urls_have_tuple_origins() -> bool;+}++#[derive(Clone, Debug, Eq, PartialEq, Hash)]+pub struct Host {+ pub kind: HostKind,+ pub serialization: String,+}++#[repr(u8)]+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub enum OpaqueOriginKind {+ #[default]+ Standard,+ File,+ SandboxedFile,+}++pub type Nonce = [u8; 16];++// https://html.spec.whatwg.org/multipage/browsers.html#concept-origin+#[derive(Clone, Debug)]+pub enum Origin {+ // https://html.spec.whatwg.org/multipage/browsers.html#concept-origin-opaque+ Opaque {+ nonce: Nonce,+ kind: OpaqueOriginKind,+ },+ // https://html.spec.whatwg.org/multipage/browsers.html#concept-origin-tuple+ Tuple {+ scheme: String,+ host: Host,+ port: Option<u16>,+ domain: Option<Host>,+ },+}++impl Origin {+ pub fn new_opaque(kind: OpaqueOriginKind) -> Self {+ let mut nonce = Nonce::default();+ getrandom::fill(&mut nonce).expect("the platform CSPRNG fills buffers");+ Self::Opaque { nonce, kind }+ }++ fn new_tuple(scheme: &str, host: Host, port: Option<u16>) -> Self {+ Self::Tuple {+ scheme: scheme.to_owned(),+ host,+ port,+ domain: None,+ }+ }+}++impl<Serialization: AsRef<str>> Url<Serialization> {+ fn host(&self) -> Host {+ Host {+ kind: self.host_kind(),+ serialization: self.serialized_host().unwrap_or("").to_owned(),+ }+ }++ // https://url.spec.whatwg.org/#concept-url-origin+ // NB: A URL of this crate has no blob URL entry, so the caller runs step 1 of "blob".+ pub fn origin(&self) -> Origin {+ // The origin of a URL url is the origin returned by running these steps, switching on url’s scheme:+ match self.scheme() {+ // -> "blob"+ "blob" => {+ // 2. Let pathURL be the result of parsing the result of URL path serializing url.+ let Some(path_url) = basic_parse(self.serialize_path(), BasicParseOptions::new()) else {+ // 3. If pathURL is failure, then return a new opaque origin.+ return Origin::new_opaque(OpaqueOriginKind::Standard);+ };++ // 4. If pathURL’s scheme is "http", "https", or "file", then return pathURL’s origin.+ if matches!(path_url.scheme(), "http" | "https" | "file") {+ return path_url.origin();+ }++ // 5. Return a new opaque origin.+ Origin::new_opaque(OpaqueOriginKind::Standard)+ }+ // -> "ftp"+ // -> "http"+ // -> "https"+ // -> "ws"+ // -> "wss"+ // Return the tuple origin (url’s scheme, url’s host, url’s port, null).+ "ftp" | "http" | "https" | "ws" | "wss" => Origin::new_tuple(self.scheme(), self.host(), self.port()),+ // AD-HOC: resource:// URLs are internal browser resources; give them a shared tuple origin+ // so that same-origin checks pass between any two resource:// documents or worker scripts.+ "resource" => Origin::new_tuple("resource", empty_host(), None),+ // -> "file"+ "file" => {+ // Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin.++ // Our implementation-defined behavior is to return an opaque origin for file:// URLs,+ // tagged explicitly as a "file" opaque origin rather than a fully anonymous one.+ //+ // This keeps file:// URLs opaque by default while still allowing downstream code to+ // identify and special-case them where needed - for example, to match cases where+ // other browsers treat a file:// origin as if it were a tuple origin.+ //+ // A process-wide flag can opt into tuple origins for file:// URLs instead. This is+ // intended for development/testing scenarios where web features requiring a non-opaque+ // origin (such as localStorage) need to work with file:// pages.+ // SAFETY: LibURL defines the function, which only reads a flag.+ if unsafe { url_rust_file_scheme_urls_have_tuple_origins() } {+ return Origin::new_tuple("file", empty_host(), None);+ }++ Origin::new_opaque(OpaqueOriginKind::File)+ }+ // -> Otherwise+ // Return a new opaque origin.+ _ => Origin::new_opaque(OpaqueOriginKind::Standard),+ }+ }+}++fn empty_host() -> Host {+ Host {+ kind: HostKind::Domain,+ serialization: String::new(),+ }+}diff --git a/Libraries/LibURL/RustIntegration.cpp b/Libraries/LibURL/RustIntegration.cppindex 2f12ae4cfd8..b9f19167aae 100644--- a/Libraries/LibURL/RustIntegration.cpp+++ b/Libraries/LibURL/RustIntegration.cpp@@ -167,6 +167,21 @@ Optional<Host> host_from_ffi(FFI::FfiUrlHost const& ffi)VERIFY_NOT_REACHED();}+Origin origin_from_ffi(FFI::FfiOrigin const& ffi)+{+ if (ffi.is_opaque) {+ Origin::OpaqueData::Nonce nonce;+ static_assert(sizeof(nonce) == sizeof(ffi.nonce));+ __builtin_memcpy(nonce.data(), ffi.nonce, sizeof(ffi.nonce));+ return Origin { Origin::OpaqueData { nonce, static_cast<Origin::OpaqueData::Type>(ffi.opaque_kind) } };+ }++ Optional<u16> port;+ if (ffi.has_port)+ port = ffi.port;+ return Origin { string_from_ffi(ffi.scheme), host_from_ffi(ffi.host).release_value(), port, host_from_ffi(ffi.domain) };+}+URLPattern::Impl::~Impl(){if (rust_url_pattern)diff --git a/Libraries/LibURL/RustIntegration.h b/Libraries/LibURL/RustIntegration.hindex 48c689922d7..dccad173205 100644--- a/Libraries/LibURL/RustIntegration.h+++ b/Libraries/LibURL/RustIntegration.h@@ -21,6 +21,7 @@ namespace URL::RustIntegration {Optional<Host> parse_host(StringView input, bool is_opaque = false);Optional<Host> parse_host(Utf16View input, bool is_opaque = false);Optional<Host> host_from_ffi(FFI::FfiUrlHost const&);+Origin origin_from_ffi(FFI::FfiOrigin const&);FFI::RustUrlInput rust_url_input(Utf16View);class URLPattern {diff --git a/Libraries/LibURL/URL.cpp b/Libraries/LibURL/URL.cppindex 3aefea0fb32..b09a2409a42 100644--- a/Libraries/LibURL/URL.cpp+++ b/Libraries/LibURL/URL.cpp@@ -417,69 +417,29 @@ bool file_scheme_urls_have_tuple_origins()return s_file_scheme_urls_have_tuple_origins;}+extern "C" bool url_rust_file_scheme_urls_have_tuple_origins();++extern "C" bool url_rust_file_scheme_urls_have_tuple_origins()+{+ return s_file_scheme_urls_have_tuple_origins;+}+// https://url.spec.whatwg.org/#concept-url-originOrigin URL::origin() const{// The origin of a URL url is the origin returned by running these steps, switching on url’s scheme:// -> "blob"- if (scheme() == "blob"sv) {- // 1. If url’s blob URL entry is non-null, then return url’s blob URL entry’s environment’s origin.- if (blob_url_entry().has_value())- return blob_url_entry()->environment.origin;-- // 2. Let pathURL be the result of parsing the result of URL path serializing url.- auto path_url = Parser::basic_parse(serialize_path());-- // 3. If pathURL is failure, then return a new opaque origin.- if (!path_url.has_value())- return Origin::create_opaque();-- // 4. If pathURL’s scheme is "http", "https", or "file", then return pathURL’s origin.- if (path_url->scheme().is_one_of("http"sv, "https"sv, "file"sv))- return path_url->origin();+ // 1. If url’s blob URL entry is non-null, then return url’s blob URL entry’s environment’s origin.+ if (scheme() == "blob"sv && blob_url_entry().has_value())+ return blob_url_entry()->environment.origin;- // 5. Return a new opaque origin.- return Origin::create_opaque();- }-- // -> "ftp"- // -> "http"- // -> "https"- // -> "ws"- // -> "wss"- if (scheme().is_one_of("ftp"sv, "http"sv, "https"sv, "ws"sv, "wss"sv)) {- // Return the tuple origin (url’s scheme, url’s host, url’s port, null).- return Origin(String::from_ascii_without_validation(scheme().bytes()), host().value(), port());- }-- // AD-HOC: resource:// URLs are internal browser resources; give them a shared tuple origin- // so that same-origin checks pass between any two resource:// documents or worker scripts.- if (scheme() == "resource"sv)- return Origin("resource"_string, String {}, {});-- // -> "file"- if (scheme() == "file"sv) {- // Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin.-- // Our implementation-defined behavior is to return an opaque origin for file:// URLs,- // tagged explicitly as a "file" opaque origin rather than a fully anonymous one.- //- // This keeps file:// URLs opaque by default while still allowing downstream code to- // identify and special-case them where needed - for example, to match cases where- // other browsers treat a file:// origin as if it were a tuple origin.- //- // A process-wide flag can opt into tuple origins for file:// URLs instead. This is- // intended for development/testing scenarios where web features requiring a non-opaque- // origin (such as localStorage) need to work with file:// pages.- if (file_scheme_urls_have_tuple_origins())- return Origin { "file"_string, String {}, {} };-- return Origin::create_opaque(Origin::OpaqueData::Type::File);- }-- // -> Otherwise- // Return a new opaque origin.- return Origin::create_opaque();+ // NB: liburl_rust runs the remaining steps.+ auto rust_url = to_rust();+ Optional<Origin> origin;+ FFI::rust_url_origin(&rust_url, &origin, [](void* ctx, FFI::FfiOrigin const* ffi_origin) {+ *static_cast<Optional<Origin>*>(ctx) = RustIntegration::origin_from_ffi(*ffi_origin);+ });+ return origin.release_value();}bool URL::equals(URL const& other, ExcludeFragment exclude_fragments) const