Skip to main content

blitz_traits/
platform.rs

1//! Abstractions of the host platform APIs a guest expects to find: fetching,
2//! and per-origin storage.
3//!
4//! These sit beside [`crate::net`] rather than inside it, and the distinction
5//! is worth stating because it is not obvious from the names.
6//!
7//! [`NetProvider`](crate::net::NetProvider) loads *resources the document
8//! needs*: a stylesheet, an image, a script. Its completion callback is
9//! [`NetHandler::bytes`](crate::net::NetHandler), which takes a resolved URL
10//! and some bytes, and that is the whole answer. There is no status code and
11//! there are no response headers, because a caller loading an image has nothing
12//! to do with either: the bytes decode or they do not.
13//!
14//! A `fetch()` caller is the opposite. A 404 is not a failure to be logged and
15//! dropped, it is the answer, and so are the headers. So this is a second trait
16//! rather than a wider `NetProvider`: an embedder that only ever loads page
17//! resources keeps implementing the small one, and the two can share a client.
18//! `blitz-net` implements both over the same `reqwest` client, the same
19//! connection pool, the same cookie jar and the same disk cache.
20//!
21//! Nothing here performs IO or names an HTTP client. The implementations live
22//! with the embedder.
23
24pub use bytes::Bytes;
25/// Re-exported so a binding can name `HeaderName` and `HeaderValue` when
26/// building a request, without taking its own dependency on `http` and pinning
27/// it to whatever version this crate happens to resolve. Same reasoning as the
28/// `keyboard_types` re-export in the crate root.
29pub use http;
30pub use http::{HeaderMap, Method, StatusCode};
31use std::sync::atomic::{AtomicU64, Ordering};
32pub use url::Url;
33
34/// A type that performs `fetch`-style requests on behalf of a guest.
35///
36/// Asynchronous by construction: [`fetch`](FetchProvider::fetch) hands the
37/// request over and returns immediately, and the answer arrives through the
38/// handler on whatever thread the implementation chooses. Callers must not
39/// assume the handler runs later, or on another thread: an implementation
40/// serving a `data:` URL may answer before `fetch` returns.
41pub trait FetchProvider: Send + Sync + 'static {
42    fn fetch(&self, request: FetchRequest, handler: Box<dyn FetchHandler>);
43}
44
45/// Receives the result of one [`FetchProvider::fetch`].
46///
47/// Takes `self: Box<Self>` so that a handler can be consumed by completing,
48/// which makes "completed twice" unrepresentable rather than merely wrong.
49/// Same shape as [`NetHandler`](crate::net::NetHandler).
50pub trait FetchHandler: Send + Sync + 'static {
51    /// Called exactly once.
52    ///
53    /// **A response with a non-success status is `Ok`, not `Err`.** A 404 has a
54    /// status, headers and usually a body, all of which the caller asked for.
55    /// [`FetchError`] is for the cases where there is no response at all.
56    fn complete(self: Box<Self>, result: Result<FetchResponse, FetchError>);
57}
58
59/// A request, loosely <https://fetch.spec.whatwg.org/#requests>.
60///
61/// Narrower than [`Request`](crate::net::Request) on purpose: no form bodies,
62/// because a guest that wants a multipart body can encode one, and no abort
63/// signal, because nothing in the current scope cancels. Both are additive
64/// later; see the README.
65#[non_exhaustive]
66#[derive(Debug, Clone)]
67pub struct FetchRequest {
68    pub url: Url,
69    pub method: Method,
70    pub headers: HeaderMap,
71    /// `None` is distinct from `Some(empty)`: the first sends no body at all,
72    /// the second sends a zero-length one with a `Content-Length: 0`.
73    pub body: Option<Bytes>,
74}
75
76impl FetchRequest {
77    /// A GET with no headers and no body.
78    pub fn get(url: Url) -> Self {
79        Self {
80            url,
81            method: Method::GET,
82            headers: HeaderMap::new(),
83            body: None,
84        }
85    }
86
87    /// The same request with a method.
88    pub fn method(mut self, method: Method) -> Self {
89        self.method = method;
90        self
91    }
92
93    /// The same request with a body.
94    pub fn body(mut self, body: Bytes) -> Self {
95        self.body = Some(body);
96        self
97    }
98}
99
100/// A response, loosely <https://fetch.spec.whatwg.org/#responses>.
101#[non_exhaustive]
102#[derive(Debug, Clone)]
103pub struct FetchResponse {
104    /// The URL the response actually came from, after any redirects.
105    ///
106    /// Not the requested URL. A guest resolving relative links out of a
107    /// response body needs the one it landed on.
108    pub url: Url,
109    pub status: StatusCode,
110    pub headers: HeaderMap,
111    pub body: Bytes,
112}
113
114impl FetchResponse {
115    /// A response with the given status and no headers or body.
116    ///
117    /// A constructor rather than a struct literal because the type is
118    /// `#[non_exhaustive]`, and it is `#[non_exhaustive]` because every
119    /// provider lives outside this crate: a field added here later would
120    /// otherwise break all of them at once. Build with this and the setters,
121    /// and a new field arrives with a default instead of a compile error.
122    pub fn new(url: Url, status: StatusCode) -> Self {
123        Self {
124            url,
125            status,
126            headers: HeaderMap::new(),
127            body: Bytes::new(),
128        }
129    }
130
131    pub fn headers(mut self, headers: HeaderMap) -> Self {
132        self.headers = headers;
133        self
134    }
135
136    pub fn body(mut self, body: Bytes) -> Self {
137        self.body = body;
138        self
139    }
140}
141
142/// Why there is no response.
143///
144/// Note what is *not* here: an HTTP status. A server that answered is a
145/// [`FetchResponse`] whatever it answered with. These are the cases where
146/// nothing answered.
147#[non_exhaustive]
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum FetchError {
150    /// The request could not be completed: DNS, TLS, connection, timeout, a
151    /// malformed response, or a local read that failed.
152    ///
153    /// The string is for a human reading a log. TLS algorithm refusals use
154    /// `TlsPolicy` so callers can retain the reason without parsing this text.
155    Network(String),
156    /// The peer could not complete TLS under the permitted algorithm policy.
157    TlsPolicy(crate::tls_policy::TlsPolicyError),
158    /// The URL's scheme is not one this provider serves.
159    UnsupportedScheme(String),
160    /// The request was rejected before it was sent: an unparseable header, a
161    /// method the provider will not issue.
162    InvalidRequest(String),
163    /// Refused by policy rather than by the network. A provider that enforces
164    /// an allowlist, or refuses to let an opaque origin reach the network,
165    /// answers with this.
166    Blocked(String),
167    /// There is no provider installed. See [`DummyFetchProvider`].
168    NoProvider,
169}
170
171impl std::fmt::Display for FetchError {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        match self {
174            Self::Network(detail) => write!(f, "network error: {detail}"),
175            Self::TlsPolicy(reason) => write!(f, "TLS policy: {reason}"),
176            Self::UnsupportedScheme(scheme) => write!(f, "unsupported URL scheme: {scheme}"),
177            Self::InvalidRequest(detail) => write!(f, "invalid request: {detail}"),
178            Self::Blocked(reason) => write!(f, "blocked: {reason}"),
179            Self::NoProvider => write!(f, "no fetch provider is installed"),
180        }
181    }
182}
183
184impl std::error::Error for FetchError {}
185
186/// A [`FetchProvider`] that answers every request with [`FetchError::NoProvider`].
187///
188/// **It answers rather than doing nothing, which is where it differs from
189/// [`DummyNetProvider`](crate::net::DummyNetProvider), and the difference is
190/// deliberate.** A dropped resource load leaves an image unpainted, which is
191/// visible and survivable. A dropped `fetch` leaves the guest waiting on an
192/// answer that will never come, and a guest awaiting a promise that never
193/// settles is indistinguishable from a hang. So the no-op provider here fails
194/// fast instead of going quiet.
195#[derive(Default)]
196pub struct DummyFetchProvider;
197
198impl FetchProvider for DummyFetchProvider {
199    fn fetch(&self, _request: FetchRequest, handler: Box<dyn FetchHandler>) {
200        handler.complete(Err(FetchError::NoProvider));
201    }
202}
203
204/// The security principal a piece of stored state belongs to.
205///
206/// **Storage is keyed by this and never by a URL.** Two pages on one origin
207/// share storage; two pages on different origins must not see each other's,
208/// and that is a security property rather than a nicety.
209///
210/// Derived through [`Url::origin`], which is Servo's implementation of the
211/// WHATWG origin concept, so the awkward cases are already decided: `blob:`
212/// unwraps to its inner origin, and `file:` and `data:` are *opaque*.
213///
214/// # Opaque origins
215///
216/// [`Url::origin`] mints a **fresh** opaque origin on every call for a `file:`
217/// URL, so a document must derive its key once, at construction, and hold it.
218/// Deriving twice would give one document two identities and lose its own
219/// writes.
220///
221/// That is exactly the intended behaviour and not a wrinkle to route around.
222/// Collapsing every `file:` page into one shared bucket would mean any local
223/// HTML file could read any other's saved state, which is the same class of
224/// mistake as `blitz-net`'s `file:` handler reading any path it is handed.
225/// One such hole is enough.
226///
227/// [`is_persistable`](OriginKey::is_persistable) is the flag a disk-backed
228/// provider must check: an opaque origin is unique to one instance of one
229/// document, so writing it to disk stores a row that can never be read again.
230#[derive(Debug, Clone, PartialEq, Eq, Hash)]
231pub struct OriginKey {
232    key: String,
233    persistable: bool,
234}
235
236/// Distinguishes one opaque origin from the next within a process.
237static NEXT_OPAQUE: AtomicU64 = AtomicU64::new(0);
238
239impl OriginKey {
240    /// The origin of a document loaded from `url`.
241    ///
242    /// Call once per document and keep the result. See the type's docs for why
243    /// calling twice is a bug for `file:` and `data:` URLs.
244    pub fn for_document(url: &Url) -> Self {
245        let origin = url.origin();
246        if origin.is_tuple() {
247            Self {
248                key: origin.ascii_serialization(),
249                persistable: true,
250            }
251        } else {
252            Self::opaque()
253        }
254    }
255
256    /// A fresh opaque origin, shared with nothing.
257    ///
258    /// The serialisation of every opaque origin is the string `null`, so it
259    /// cannot be used to tell two of them apart. This appends a
260    /// process-unique counter so that a provider keying an in-memory map on
261    /// [`as_str`](OriginKey::as_str) isolates them from each other, which
262    /// `null` alone would not.
263    pub fn opaque() -> Self {
264        let nth = NEXT_OPAQUE.fetch_add(1, Ordering::Relaxed);
265        Self {
266            key: format!("null:{nth}"),
267            persistable: false,
268        }
269    }
270
271    /// A stable string for this origin, suitable as a map or table key.
272    ///
273    /// Unique per origin, including across opaque ones. Not a URL, and not to
274    /// be parsed back into one.
275    pub fn as_str(&self) -> &str {
276        &self.key
277    }
278
279    /// Whether state under this origin may be written to disk.
280    ///
281    /// False for opaque origins. A provider that persists must check this and
282    /// keep the rest in memory; see the type's docs.
283    pub fn is_persistable(&self) -> bool {
284        self.persistable
285    }
286}
287
288/// Per-origin key/value storage, the model behind `localStorage`.
289///
290/// Synchronous, because the API it backs is. Values are strings, because the
291/// API it backs stores strings: a caller with structure serialises it, exactly
292/// as it would against a browser, and no implementation here looks inside a
293/// value.
294///
295/// **Every method takes an [`OriginKey`], and an implementation must scope by
296/// it.** This is the whole security contract of the trait and it is not
297/// optional. An implementation that ignores the argument compiles, works in a
298/// single-origin test, and leaks every site's data to every other.
299pub trait StorageProvider: Send + Sync + 'static {
300    fn get(&self, origin: &OriginKey, key: &str) -> Option<String>;
301    fn set(&self, origin: &OriginKey, key: &str, value: &str) -> Result<(), StorageError>;
302    fn remove(&self, origin: &OriginKey, key: &str);
303    /// Removes everything under `origin`, and nothing under any other.
304    fn clear(&self, origin: &OriginKey);
305}
306
307/// Why a write did not happen.
308///
309/// Reads, removes and clears do not fail: an absent key is `None` and removing
310/// what is not there is a no-op, which is what the storage API specifies.
311#[non_exhaustive]
312#[derive(Debug, Clone, PartialEq, Eq)]
313pub enum StorageError {
314    /// The origin is at its limit. `localStorage` surfaces this as a
315    /// `QuotaExceededError`, which is the one storage failure guests handle.
316    QuotaExceeded,
317    /// The backing store refused the write.
318    Backend(String),
319}
320
321impl std::fmt::Display for StorageError {
322    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323        match self {
324            Self::QuotaExceeded => write!(f, "storage quota exceeded for this origin"),
325            Self::Backend(detail) => write!(f, "storage backend error: {detail}"),
326        }
327    }
328}
329
330impl std::error::Error for StorageError {}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    fn url(text: &str) -> Url {
337        Url::parse(text).unwrap()
338    }
339
340    #[test]
341    fn same_origin_urls_share_a_key() {
342        let a = OriginKey::for_document(&url("https://example.com/one?x=1#frag"));
343        let b = OriginKey::for_document(&url("https://example.com/two"));
344        assert_eq!(a, b);
345        assert!(a.is_persistable());
346    }
347
348    #[test]
349    fn scheme_port_and_host_all_separate_origins() {
350        let https = OriginKey::for_document(&url("https://example.com/"));
351        let http = OriginKey::for_document(&url("http://example.com/"));
352        let port = OriginKey::for_document(&url("https://example.com:8443/"));
353        let host = OriginKey::for_document(&url("https://other.example.com/"));
354        assert_ne!(https, http);
355        assert_ne!(https, port);
356        assert_ne!(https, host);
357    }
358
359    /// The property that stops one local page reading another's state. Two
360    /// *identical* file URLs must still be different origins.
361    #[test]
362    fn every_file_url_gets_its_own_opaque_origin() {
363        let one = OriginKey::for_document(&url("file:///home/user/page.html"));
364        let same_again = OriginKey::for_document(&url("file:///home/user/page.html"));
365        let other = OriginKey::for_document(&url("file:///home/user/other.html"));
366
367        assert_ne!(one, same_again);
368        assert_ne!(one, other);
369        assert!(!one.is_persistable());
370        assert!(!same_again.is_persistable());
371    }
372
373    #[test]
374    fn data_urls_are_opaque_too() {
375        let key = OriginKey::for_document(&url("data:text/html,<p>hi"));
376        assert!(!key.is_persistable());
377    }
378
379    /// `ascii_serialization` answers `null` for every opaque origin, so a
380    /// provider keying on it alone would merge them all into one bucket. This
381    /// is the assertion that the counter is doing its job.
382    #[test]
383    fn opaque_keys_are_distinguishable_from_each_other() {
384        let one = OriginKey::opaque();
385        let two = OriginKey::opaque();
386        assert_ne!(one.as_str(), two.as_str());
387        assert_ne!(one.as_str(), "null");
388    }
389
390    /// A `blob:` URL carries its origin inside it, and that origin is the one
391    /// that owns any state reached through it.
392    #[test]
393    fn a_blob_url_takes_the_origin_it_was_minted_from() {
394        let blob = OriginKey::for_document(&url("blob:https://example.com/uuid-goes-here"));
395        let page = OriginKey::for_document(&url("https://example.com/index.html"));
396        assert_eq!(blob, page);
397    }
398
399    #[test]
400    fn the_dummy_provider_answers_rather_than_going_quiet() {
401        use std::sync::{Arc, Mutex};
402
403        struct Record(Arc<Mutex<Option<Result<FetchResponse, FetchError>>>>);
404        impl FetchHandler for Record {
405            fn complete(self: Box<Self>, result: Result<FetchResponse, FetchError>) {
406                *self.0.lock().unwrap() = Some(result);
407            }
408        }
409
410        let seen = Arc::new(Mutex::new(None));
411        DummyFetchProvider.fetch(
412            FetchRequest::get(url("https://example.com/")),
413            Box::new(Record(seen.clone())),
414        );
415
416        let answer = seen.lock().unwrap().take();
417        assert_eq!(
418            answer.expect("the dummy must answer").unwrap_err(),
419            FetchError::NoProvider
420        );
421    }
422}