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