Skip to main content

flm_core/stdlib/backends/html/
address.rs

1//! The address policy: which addresses the HTML backend writes into a page,
2//! and which it refuses.
3//!
4//! An **address** here is a URL that the page references: what a link points
5//! at (`href`) or what an image is loaded from (`src`, `srcset`). Both come
6//! from the document or from the host that rendered it, and a browser can do
7//! more with an address than fetch it: when a link is followed whose address
8//! has the **scheme** `javascript` (the scheme is the part before the first
9//! colon, `https` in `https://example.org`), the browser runs the rest of the
10//! address as a program.
11//!
12//! [`check_address`] therefore accepts an address only when it is one of
13//! these:
14//!
15//! - an **address fragment**, `#section-2`: a place in the same page;
16//! - a **relative address**, `figures/plot.png`, `../index.html`, `?page=2`:
17//!   one with no scheme at all, read against the address of the page it is
18//!   in;
19//! - an address whose scheme the render option [`HtmlAllowedUrlSchemes`]
20//!   allows: by default, one of [`DEFAULT_ALLOWED_URL_SCHEMES`];
21//! - for an image only, a `data:` address whose media type begins with
22//!   `image/` ([`DATA_SCHEME`], [`IMAGE_MEDIA_PREFIX`]) — a picture written
23//!   into the page itself.
24//!
25//! Anything else is refused. A refused address loses the address and nothing
26//! else: the emitter writes the link without its `href` and the image without
27//! its `src`, so the link's text and the image's alternative text (the
28//! content) stay in the page, and it reports the refusal as
29//! `flm.html.refused-address`
30//! ([`AddressRefused`](super::emit::AddressRefused)) with the refused scheme.
31//!
32//! # Who decides which schemes are allowed
33//!
34//! The default list is the smallest that lets the standard features write the
35//! links and images they need, and it holds no scheme that a browser runs as a
36//! program. Under it, a page this library produced runs no program that a
37//! document asked for.
38//!
39//! A host that needs more, such as a scheme of its own that a script of its
40//! page handles (`app:open/42`), sets the render option
41//! [`HtmlAllowedUrlSchemes`]: either the list of allowed schemes, which
42//! replaces the default list, or [`HtmlAllowedUrlSchemes::All`], under which
43//! every address is written as given.
44//!
45//! The option is set only by Rust code: on the render request
46//! ([`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options())),
47//! or by a workflow defined in Rust
48//! ([`WorkflowDef::render_options`](crate::core::registry::WorkflowDef#structfield.render_options)).
49//! It is not one of the `html` feature's settings keys
50//! ([`crate::core::settings`]), so no settings written as data (a document's
51//! front matter, a command line, the settings of a package) can set it.
52//! Whether a page may reference an address that a browser runs is the decision
53//! of the program that serves the page, not of a document or of the
54//! configuration written beside it.
55//!
56//! # Where the policy does not apply
57//!
58//! The policy does not apply to a [construct node](super::construct), the node
59//! a lowering rule stages (builds into the lowered tree; see
60//! [`Lowerer`](crate::core::lowering::Lowerer)) to write one HTML tag of its
61//! own with its own attributes: the rule that writes a tag is responsible for
62//! what it writes, and its author must check the addresses it writes as this
63//! module does, with [`check_address`] under the value of
64//! [`HtmlAllowedUrlSchemes`] that the rule declares a read of
65//! ([`LoweringDecl::option`](crate::core::lowering::LoweringDecl::option)).
66//! Nor does it apply to the address of a style or script definition, which
67//! comes from a feature's author or the host ([`super::page`]).
68//!
69//! # How a browser reads the scheme of an address
70//!
71//! A browser does not read the characters of an address exactly as written.
72//! Before it looks for the scheme it removes every tab, line feed and carriage
73//! return from the address, wherever they are, and ignores leading and
74//! trailing spaces and control characters. `java\nscript:alert(1)` and
75//! `  JaVaScRiPt:alert(1)` are therefore both the `javascript` scheme.
76//! [`check_address`] does the same before it reads the scheme, and compares
77//! the scheme ignoring letter case.
78//!
79//! It does **not** decode character references. `javascript:` is not a
80//! hidden scheme here: the sink escapes every `&` it writes into an
81//! attribute value as `&`
82//! ([`escape_attr_into`](super::escape::escape_attr_into)), so the `&` of a
83//! reference never reaches the page as a `&`, and the address the browser
84//! reads is the one this module read. Decoding references before the check
85//! would therefore not make the check stricter; it would only make it disagree
86//! with what the page will hold.
87
88use std::collections::BTreeSet;
89use std::fmt;
90
91/// The schemes an address may have by default, whether it is a link or an
92/// image: `http`, `https`, `mailto`, `ftp`, `tel`.
93///
94/// They are the schemes of the default value of the render option
95/// [`HtmlAllowedUrlSchemes`] ([`HtmlAllowedUrlSchemes::default_schemes`]).
96/// The comparison ignores letter case.
97pub const DEFAULT_ALLOWED_URL_SCHEMES: [&str; 5] = ["http", "https", "mailto", "ftp", "tel"];
98
99/// The scheme of an address that carries its own content instead of pointing
100/// at something, `data`: allowed for an image whose media type begins with
101/// [`IMAGE_MEDIA_PREFIX`], refused for everything else unless the render
102/// option [`HtmlAllowedUrlSchemes`] allows the scheme `data` itself.
103pub const DATA_SCHEME: &str = "data";
104
105/// What the media type of a `data:` address must begin with for an image,
106/// `image/`, comparing without regard to letter case: `data:image/png;base64,…`
107/// is an image, `data:text/html,…` is a page and is refused.
108pub const IMAGE_MEDIA_PREFIX: &str = "image/";
109
110/// A URL scheme, such as `https`: the part of a URL before its first colon,
111/// without the colon, held in lower case.
112///
113/// A scheme is an ASCII letter followed by ASCII letters, digits, `+`, `-` and
114/// `.`; [`UrlScheme::new`] refuses any other name, so a value of this type is
115/// always a scheme that an address can have.
116#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
117pub struct UrlScheme(String);
118
119impl UrlScheme {
120    /// Returns the scheme `name`, held in lower case: `UrlScheme::new("HTTPS")`
121    /// is the scheme `https`.
122    ///
123    /// # Errors
124    ///
125    /// [`InvalidUrlScheme`] when `name` is not a scheme: it is empty, it does
126    /// not begin with an ASCII letter, or it holds a character other than an
127    /// ASCII letter, a digit, `+`, `-` and `.` (the colon that ends a scheme in
128    /// an address included: `app:` is not a scheme, `app` is).
129    pub fn new(name: &str) -> Result<UrlScheme, InvalidUrlScheme> {
130        let mut chars = name.chars();
131        if chars.next().is_some_and(begins_scheme) && chars.all(continues_scheme) {
132            Ok(UrlScheme(name.to_ascii_lowercase()))
133        } else {
134            Err(InvalidUrlScheme { name: String::from(name) })
135        }
136    }
137
138    /// Returns the scheme's name, in lower case and without a colon.
139    pub fn as_str(&self) -> &str {
140        &self.0
141    }
142}
143
144impl fmt::Display for UrlScheme {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.write_str(&self.0)
147    }
148}
149
150/// The error [`UrlScheme::new`] returns for a name that is not a URL scheme,
151/// holding the name as given.
152#[derive(Debug, Clone, PartialEq, Eq, Hash)]
153pub struct InvalidUrlScheme {
154    /// The name as given.
155    pub name: String,
156}
157
158impl fmt::Display for InvalidUrlScheme {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        write!(
161            f,
162            "`{}` is not a URL scheme: a scheme is an ASCII letter followed by ASCII letters, \
163             digits, `+`, `-` and `.`, given without its colon",
164            self.name
165        )
166    }
167}
168
169impl std::error::Error for InvalidUrlScheme {}
170
171/// The render option that decides which URL schemes the page may reference:
172/// the schemes allowed in the URLs that the HTML backend writes into a link's
173/// `href` and an image's `src` and `srcset`.
174///
175/// A URL with no scheme (a relative address, an address fragment) is always
176/// allowed, whatever the value; [the module documentation](self) states the
177/// whole policy. The default value is
178/// [`Listed`](HtmlAllowedUrlSchemes::Listed) with
179/// [`DEFAULT_ALLOWED_URL_SCHEMES`].
180///
181/// The option is bound to the render request
182/// ([`Bind::Render`](crate::model::options::Bind::Render)) and is set only by
183/// Rust code: it is declared by the `html` feature beside its settings, not
184/// among them, so no settings written as data can set it ([who decides which
185/// schemes are allowed](self#who-decides-which-schemes-are-allowed)). It is
186/// an option type of its own rather than a field of
187/// [`HtmlRenderOptions`](super::HtmlRenderOptions) for that reason, and so
188/// that a workflow's value of it is never replaced when settings written as
189/// data set a key of [`HtmlRenderOptions`](super::HtmlRenderOptions).
190///
191/// # Examples
192///
193/// A host that lets the page reference its own scheme `app`, beside the
194/// default ones, and sets the value on its render request:
195///
196/// ```
197/// use flm_core::model::options::OptionValues;
198/// use flm_core::stdlib::backends::html::{
199///     AddressUse, HtmlAllowedUrlSchemes, UrlScheme, check_address,
200/// };
201///
202/// let mut schemes = HtmlAllowedUrlSchemes::default_schemes();
203/// schemes.insert(UrlScheme::new("app").expect("a scheme"));
204/// let allowed = HtmlAllowedUrlSchemes::Listed(schemes);
205/// assert!(check_address("app:open/42", AddressUse::Link, &allowed).is_ok());
206/// assert!(check_address("javascript:alert(1)", AddressUse::Link, &allowed).is_err());
207///
208/// // Given to `PlanRequest::render_options`.
209/// let render_options = OptionValues::new().with(allowed);
210/// # let _ = render_options;
211/// ```
212#[derive(Debug, Clone, PartialEq, Eq, Hash)]
213pub enum HtmlAllowedUrlSchemes {
214    /// Only the URLs whose scheme is one of these, beside the URLs with no
215    /// scheme and, for an image, a `data:` URL carrying a picture. The list
216    /// replaces the default list: a host that adds a scheme to the default
217    /// ones starts from [`default_schemes`](HtmlAllowedUrlSchemes::default_schemes).
218    Listed(BTreeSet<UrlScheme>),
219    /// Every URL, written as given whatever its scheme, `javascript:`
220    /// included: a link whose address is `javascript:…` then runs its program
221    /// in the reader's browser when it is followed. Nothing is refused.
222    All,
223}
224
225impl HtmlAllowedUrlSchemes {
226    /// Returns the default schemes, [`DEFAULT_ALLOWED_URL_SCHEMES`], as the
227    /// set that the default value lists.
228    pub fn default_schemes() -> BTreeSet<UrlScheme> {
229        DEFAULT_ALLOWED_URL_SCHEMES.iter().map(|name| UrlScheme(String::from(*name))).collect()
230    }
231
232    /// Returns the addresses this value allows, in words, as the report of a
233    /// refused address gives them
234    /// ([`AddressRefused`](super::emit::AddressRefused)).
235    pub(super) fn allowed_addresses(&self) -> String {
236        const PICTURE: &str = "for an image, `data:image/…`";
237        let HtmlAllowedUrlSchemes::Listed(schemes) = self else {
238            return String::from("every address");
239        };
240        let names: Vec<String> = schemes.iter().map(|scheme| format!("`{scheme}`")).collect();
241        match names.split_last() {
242            None => format!("those without a scheme and, {PICTURE}"),
243            Some((last, [])) => {
244                format!("those with the scheme {last}, those without a scheme, and, {PICTURE}")
245            }
246            Some((last, others)) => format!(
247                "those with the scheme {} or {last}, those without a scheme, and, {PICTURE}",
248                others.join(", ")
249            ),
250        }
251    }
252}
253
254impl Default for HtmlAllowedUrlSchemes {
255    fn default() -> HtmlAllowedUrlSchemes {
256        HtmlAllowedUrlSchemes::Listed(HtmlAllowedUrlSchemes::default_schemes())
257    }
258}
259
260/// How an address is used: as the target of a link, or as the source of an
261/// image. [`check_address`] takes it.
262///
263/// The two differ in one point only — an image may be a `data:` address
264/// carrying a picture, a link may not (see [the module
265/// documentation](self)).
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
267pub enum AddressUse {
268    /// The `href` of a link.
269    Link,
270    /// The `src` or one candidate of the `srcset` of an image.
271    Image,
272}
273
274/// The error [`check_address`] returns for an address the policy refuses,
275/// holding the refused scheme.
276///
277/// The scheme is the address's own, in lower case and without its colon
278/// (`javascript`); the emitter's report
279/// ([`AddressRefused`](super::emit::AddressRefused)) gives it, so that a reader
280/// of the report can see what the document asked for.
281#[derive(Debug, Clone, PartialEq, Eq, Hash)]
282pub struct RefusedAddress {
283    /// The scheme, in lower case, without the colon.
284    pub scheme: String,
285}
286
287impl fmt::Display for RefusedAddress {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        write!(f, "the address scheme `{}` is not allowed in HTML output", self.scheme)
290    }
291}
292
293/// Returns whether `ch` can begin a scheme: an ASCII letter.
294fn begins_scheme(ch: char) -> bool {
295    ch.is_ascii_alphabetic()
296}
297
298/// Returns whether `ch` can stand in a scheme after its first character: an
299/// ASCII letter, a digit, `+`, `-` or `.`.
300fn continues_scheme(ch: char) -> bool {
301    ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.')
302}
303
304/// Returns the address as a browser reads it before looking for its scheme: without
305/// the tabs, line feeds and carriage returns it holds anywhere, and without
306/// leading and trailing spaces and control characters.
307fn normalized(address: &str) -> String {
308    address
309        .trim_matches(|ch: char| ch == ' ' || (ch as u32) <= 0x1F)
310        .chars()
311        .filter(|ch| !matches!(ch, '\t' | '\n' | '\r'))
312        .collect()
313}
314
315/// Returns the scheme of a normalized address, in lower case and without its colon, or
316/// `None` when the address has none and is therefore relative.
317///
318/// A scheme is an ASCII letter followed by ASCII letters, digits, `+`, `-` and
319/// `.`, and ends at the first colon. Anything else before the first colon
320/// means there is no scheme: the colon belongs to a path (`a/b:c`), to a
321/// fragment (`#see:this`) or to a query, and the address is read against the
322/// page's own.
323fn scheme_of(address: &str) -> Option<String> {
324    let mut scheme = String::new();
325    for ch in address.chars() {
326        if ch == ':' {
327            return if scheme.is_empty() { None } else { Some(scheme) };
328        }
329        let fits = if scheme.is_empty() { begins_scheme(ch) } else { continues_scheme(ch) };
330        if !fits {
331            return None;
332        }
333        scheme.push(ch.to_ascii_lowercase());
334    }
335    None
336}
337
338/// Returns whether `address`, whose scheme is `data`, carries a picture: the
339/// text after the colon begins with [`IMAGE_MEDIA_PREFIX`], in any letter
340/// case.
341fn is_image_data(address: &str) -> bool {
342    match address.split_once(':') {
343        Some((_, rest)) => rest
344            .get(..IMAGE_MEDIA_PREFIX.len())
345            .is_some_and(|head| head.eq_ignore_ascii_case(IMAGE_MEDIA_PREFIX)),
346        None => false,
347    }
348}
349
350/// Checks whether `address` may be written for the use `used_as` under the
351/// value `allowed` of the render option [`HtmlAllowedUrlSchemes`].
352///
353/// It may when it is an address fragment (`#…`), when it is relative, when
354/// `allowed` allows its scheme, or when it is an image's `data:` address
355/// carrying a picture; under [`HtmlAllowedUrlSchemes::All`], every address
356/// may be written. The HTML emitter calls it for every link and image address
357/// and writes the element without a refused address, keeping its content.
358/// [The module documentation](self) states the policy and how an address is
359/// read.
360///
361/// # Errors
362///
363/// [`RefusedAddress`], holding the scheme, when the address has a scheme that
364/// `allowed` does not allow for that use.
365///
366/// # Examples
367///
368/// ```
369/// use flm_core::stdlib::backends::html::address::{
370///     AddressUse, HtmlAllowedUrlSchemes, check_address,
371/// };
372///
373/// let allowed = HtmlAllowedUrlSchemes::default();
374/// assert!(check_address("#section-2", AddressUse::Link, &allowed).is_ok());
375/// assert!(check_address("../figures/plot.png", AddressUse::Image, &allowed).is_ok());
376/// assert!(check_address("https://example.org/", AddressUse::Link, &allowed).is_ok());
377///
378/// // A scheme that hides behind letter case and a leading control character.
379/// let refused = check_address(" \u{1}JaVaScRiPt:alert(1)", AddressUse::Link, &allowed)
380///     .expect_err("a scheme this backend does not write");
381/// assert_eq!(refused.scheme, "javascript");
382///
383/// // A picture written into the page is an image, not a link.
384/// let png = "data:image/png;base64,iVBORw0KGgo=";
385/// assert!(check_address(png, AddressUse::Image, &allowed).is_ok());
386/// assert!(check_address(png, AddressUse::Link, &allowed).is_err());
387/// ```
388pub fn check_address(
389    address: &str,
390    used_as: AddressUse,
391    allowed: &HtmlAllowedUrlSchemes,
392) -> Result<(), RefusedAddress> {
393    let HtmlAllowedUrlSchemes::Listed(schemes) = allowed else {
394        return Ok(());
395    };
396    let address = normalized(address);
397    let Some(scheme) = scheme_of(&address) else {
398        // No scheme: a fragment, or an address read against the page's own.
399        return Ok(());
400    };
401    if schemes.iter().any(|listed| listed.as_str() == scheme) {
402        return Ok(());
403    }
404    if used_as == AddressUse::Image && scheme == DATA_SCHEME && is_image_data(&address) {
405        return Ok(());
406    }
407    Err(RefusedAddress { scheme })
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413
414    /// The check under the default value of the option.
415    fn check(address: &str, used_as: AddressUse) -> Result<(), RefusedAddress> {
416        check_address(address, used_as, &HtmlAllowedUrlSchemes::default())
417    }
418
419    #[test]
420    fn an_address_with_no_scheme_is_written_as_it_stands() {
421        for address in [
422            "#section-2",
423            "",
424            "figures/plot.png",
425            "../index.html",
426            "/absolute/path",
427            "//example.org/page",
428            "?page=2",
429            "a/b:c",          // the colon belongs to the path
430            "#see:this",      // and here to the fragment
431            "9lives:x",       // a scheme cannot begin with a digit
432            "my scheme:x",    // nor hold a space
433        ] {
434            assert!(check(address, AddressUse::Link).is_ok(), "{address:?}");
435            assert!(check(address, AddressUse::Image).is_ok(), "{address:?}");
436        }
437    }
438
439    #[test]
440    fn the_listed_schemes_are_written_whatever_their_letter_case() {
441        for scheme in DEFAULT_ALLOWED_URL_SCHEMES {
442            let address = format!("{scheme}:x");
443            assert!(check(&address, AddressUse::Link).is_ok(), "{address}");
444            assert!(check(&address.to_uppercase(), AddressUse::Image).is_ok(), "{address}");
445        }
446        // A scheme's own characters do not end it.
447        assert!(check("view-source+x:y", AddressUse::Link).is_err());
448    }
449
450    #[test]
451    fn a_scheme_hidden_by_case_whitespace_or_control_characters_is_still_refused() {
452        for address in [
453            "javascript:alert(1)",
454            "JaVaScRiPt:alert(1)",
455            "  javascript:alert(1)",
456            "\u{1}\u{2}javascript:alert(1)",
457            "\tjava\nscript:alert(1)",
458            "java\r\nscript:alert(1)",
459            "  \n javascript:alert(1)  \n",
460        ] {
461            let refused =
462                check(address, AddressUse::Link).expect_err("a refused scheme");
463            assert_eq!(refused.scheme, "javascript", "{address:?}");
464        }
465    }
466
467    #[test]
468    fn a_data_address_is_a_picture_for_an_image_and_nothing_for_a_link() {
469        let png = "data:image/png;base64,iVBORw0KGgo=";
470        assert!(check(png, AddressUse::Image).is_ok());
471        assert!(check("DATA:IMAGE/PNG;base64,iVBORw0KGgo=", AddressUse::Image).is_ok());
472        assert_eq!(
473            check(png, AddressUse::Link).expect_err("not for a link").scheme,
474            "data"
475        );
476        for address in ["data:text/html,<script>x</script>", "data:,plain", "data:image"] {
477            assert_eq!(
478                check(address, AddressUse::Image).expect_err("not a picture").scheme,
479                "data",
480                "{address:?}"
481            );
482        }
483    }
484
485    #[test]
486    fn every_other_scheme_is_refused_and_names_itself() {
487        for (address, scheme) in [
488            ("vbscript:x", "vbscript"),
489            ("file:///etc/passwd", "file"),
490            ("about:blank", "about"),
491            ("blob:https://example.org/x", "blob"),
492        ] {
493            let refused =
494                check(address, AddressUse::Link).expect_err("a refused scheme");
495            assert_eq!(refused.scheme, scheme, "{address:?}");
496        }
497    }
498
499    #[test]
500    fn a_scheme_written_with_character_references_is_not_decoded() {
501        // The sink escapes the `&` of a reference, so what stands here is an
502        // address beginning with `&`, which is no scheme at all, and the page
503        // holds `&amp;#106;avascript:x`: a relative address, fetched, never run.
504        assert!(check("&#106;avascript:alert(1)", AddressUse::Link).is_ok());
505    }
506
507    #[test]
508    fn a_hosts_list_replaces_the_default_and_all_writes_every_address() {
509        let only_app =
510            HtmlAllowedUrlSchemes::Listed(BTreeSet::from([UrlScheme::new("APP").unwrap()]));
511        assert!(check_address("app:open/42", AddressUse::Link, &only_app).is_ok());
512        let refused = check_address("https://example.org/", AddressUse::Link, &only_app)
513            .expect_err("a scheme the list leaves out");
514        assert_eq!(refused.scheme, "https");
515        // A picture written into the page is not a scheme of the list.
516        assert!(check_address("data:image/png;base64,x", AddressUse::Image, &only_app).is_ok());
517        for address in ["javascript:alert(1)", "data:text/html,x", "app:x"] {
518            assert!(check_address(address, AddressUse::Link, &HtmlAllowedUrlSchemes::All).is_ok());
519        }
520        // A name that is not a scheme cannot be listed.
521        for name in ["app:", "", "9p", "my scheme"] {
522            assert!(UrlScheme::new(name).is_err(), "{name:?}");
523        }
524    }
525}