Skip to main content

hemplate_runtime/
context.rs

1//! Attribute contexts and the typed values that may enter them.
2//!
3//! HTML escaping makes a value safe as *text*. Some attributes are read a second
4//! time as another language: `on*` as JavaScript, `style` as CSS, `srcdoc` as a
5//! document, `href` as a URL. There escaping does not help (a browser decodes
6//! `'` before running the script), so the derive macro classifies every
7//! interpolated attribute and requires a value of the matching trait:
8//!
9//! | Context | Attributes | Trait |
10//! |---|---|---|
11//! | URL | `href`, `src`, `action`, `formaction`, `poster`, `cite`, `ping`, ... | [`UrlValue`] |
12//! | srcset | `srcset`, `imagesrcset` | [`SrcsetValue`] |
13//! | script | `on*` | [`ScriptValue`] |
14//! | style | `style` | [`StyleValue`] |
15//! | document | `srcdoc` | [`DocumentValue`] |
16//! | navigation | `<base href>`, `<meta http-equiv>` | [`NavigationValue`] |
17//! | resource | `<script src>`, `<object data>`, `<embed src>`, stylesheet/preload `<link href>` | [`ResourceValue`] |
18//! | animation | `to`, `from`, `by`, `values` of SVG animation elements | [`AnimationValue`] |
19//!
20//! A plain `String` satisfies none of them, so interpolating one is a compile
21//! error that names the context and the alternatives. A URL attribute whose
22//! fixed text already settles the destination (`href="/users/{+ id +}"`) takes
23//! plain values. Everything else takes a checked type ([`Url`], [`Srcset`]), a
24//! type of the application's own that implements the trait, or an explicit
25//! [`Trusted`] value whose constructor marks the place where someone vouches
26//! for it.
27
28use alloc::string::{String, ToString};
29use core::fmt;
30use core::marker::PhantomData;
31
32/// Marker for a context that [`Trusted`] values can be created for.
33pub trait Context {
34    /// A short name for diagnostics.
35    const NAME: &'static str;
36}
37
38macro_rules! contexts {
39    ($($(#[$doc:meta])* $marker:ident => $name:literal),* $(,)?) => {$(
40        $(#[$doc])*
41        #[derive(Clone, Copy, Debug)]
42        pub enum $marker {}
43        impl Context for $marker {
44            const NAME: &'static str = $name;
45        }
46    )*};
47}
48
49contexts! {
50    /// URL context marker.
51    UrlContext => "url",
52    /// `srcset` context marker.
53    SrcsetContext => "srcset",
54    /// Script (`on*`) context marker.
55    ScriptContext => "script",
56    /// `style` context marker.
57    StyleContext => "style",
58    /// `srcdoc` context marker.
59    DocumentContext => "document",
60    /// `<base href>` and `<meta http-equiv>` context marker.
61    NavigationContext => "navigation",
62    /// Script, style and plug-in loading URL context marker.
63    ResourceContext => "resource",
64    /// SVG animation value context marker.
65    AnimationContext => "animation",
66}
67
68/// A value that may be the whole value of a URL attribute.
69///
70/// Implement it for types whose `Display` output is always a complete URL that is
71/// relative or uses `http`, `https`, `mailto` or `tel`, such as a route type.
72#[diagnostic::on_unimplemented(
73    message = "`{Self}` is not a checked URL, so it cannot be the whole value of a URL attribute",
74    label = "a string could hold a `javascript:` URL",
75    note = "parse it with `hemplate::Url::parse(..)` and handle the error, or start the attribute with fixed text such as `/`, `?`, `#` or `https://`",
76    note = "for a scheme such as `data:` or `sms:`, vouch for it explicitly with `hemplate::TrustedUrl::new_unchecked(..)`"
77)]
78pub trait UrlValue: fmt::Display {}
79
80/// A value that may be the whole value of a `srcset` attribute.
81#[diagnostic::on_unimplemented(
82    message = "`{Self}` cannot be interpolated into a `srcset` attribute",
83    label = "every candidate in a srcset must be a checked URL",
84    note = "build a `hemplate::Srcset` from checked `hemplate::Url` values",
85    note = "or vouch for a list explicitly with `hemplate::TrustedSrcset::new_unchecked(..)`"
86)]
87pub trait SrcsetValue: fmt::Display {}
88
89/// JavaScript that may be placed in an `on*` attribute.
90#[diagnostic::on_unimplemented(
91    message = "`{Self}` cannot be interpolated into an event-handler attribute (`on*`)",
92    label = "this value would be run as JavaScript",
93    note = "HTML escaping does not make a value safe as code: the browser decodes the attribute before running it",
94    note = "pass data in a `data-*` attribute and read it from a script, or use a Hemx handle",
95    note = "code you wrote yourself can be vouched for with `hemplate::TrustedScript::new_unchecked(..)`"
96)]
97pub trait ScriptValue: fmt::Display {}
98
99/// CSS that may be placed in a `style` attribute.
100#[diagnostic::on_unimplemented(
101    message = "`{Self}` cannot be interpolated into a `style` attribute",
102    label = "this value would be read as CSS",
103    note = "a `;` ends the property, so a value can add others such as `background: url(..)` that fetch a URL",
104    note = "choose among fixed styles with `+class=\"..\"`, or implement `hemplate::StyleValue` for a type that can only build valid values",
105    note = "or vouch for CSS explicitly with `hemplate::TrustedStyle::new_unchecked(..)`"
106)]
107pub trait StyleValue: fmt::Display {}
108
109/// A document that may be placed in `srcdoc`.
110#[diagnostic::on_unimplemented(
111    message = "`{Self}` cannot be interpolated into a `srcdoc` attribute",
112    label = "this value would be parsed as a whole HTML document",
113    note = "serve the document from its own URL and use `src`, or vouch for it with `hemplate::TrustedDocument::new_unchecked(..)`"
114)]
115pub trait DocumentValue: fmt::Display {}
116
117/// A value that may be placed in `<base href>` or `<meta http-equiv>`.
118#[diagnostic::on_unimplemented(
119    message = "`{Self}` cannot be interpolated into `<base href>` or `<meta http-equiv>`",
120    label = "this value changes how the whole page navigates or behaves",
121    note = "use fixed text, or vouch for the value with `hemplate::TrustedNavigation::new_unchecked(..)`"
122)]
123pub trait NavigationValue: fmt::Display {}
124
125/// A URL that may load script, styles or plug-ins.
126#[diagnostic::on_unimplemented(
127    message = "`{Self}` cannot be interpolated into a URL that loads script, styles or plug-ins",
128    label = "even an `https:` URL would run code or styles from wherever it points",
129    note = "use a fixed URL, or a type implementing `hemplate::ResourceValue` that can only name files you serve",
130    note = "or vouch for the URL with `hemplate::TrustedResource::new_unchecked(..)`"
131)]
132pub trait ResourceValue: fmt::Display {}
133
134/// A value that may be placed in `to`, `from`, `by` or `values` of an SVG animation.
135#[diagnostic::on_unimplemented(
136    message = "`{Self}` cannot be interpolated into an SVG animation attribute",
137    label = "an animation can set `href` to a `javascript:` URL",
138    note = "use fixed values, or vouch for them with `hemplate::TrustedAnimation::new_unchecked(..)`"
139)]
140pub trait AnimationValue: fmt::Display {}
141
142macro_rules! forward_refs {
143    ($($trait:ident),* $(,)?) => {$(
144        #[diagnostic::do_not_recommend]
145        impl<T: $trait + ?Sized> $trait for &T {}
146    )*};
147}
148
149forward_refs!(
150    UrlValue,
151    SrcsetValue,
152    ScriptValue,
153    StyleValue,
154    DocumentValue,
155    NavigationValue,
156    ResourceValue,
157    AnimationValue,
158);
159
160/// A value someone vouches for in context `C`, without any check.
161///
162/// The unchecked constructor is the visible, searchable place where responsibility
163/// is taken. Prefer [`Url`] and [`Srcset`] where they fit.
164#[derive(Clone, PartialEq, Eq, Hash)]
165pub struct Trusted<C: Context> {
166    value: String,
167    context: PhantomData<fn() -> C>,
168}
169
170impl<C: Context> Trusted<C> {
171    /// Vouch that `value` is safe in this context.
172    ///
173    /// Nothing is checked. A value that is not safe here reintroduces exactly the
174    /// injection this type exists to prevent.
175    pub fn new_unchecked(value: impl Into<String>) -> Self {
176        Self {
177            value: value.into(),
178            context: PhantomData,
179        }
180    }
181
182    /// The vouched value.
183    pub fn as_str(&self) -> &str {
184        &self.value
185    }
186}
187
188impl<C: Context> fmt::Display for Trusted<C> {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        f.write_str(&self.value)
191    }
192}
193
194impl<C: Context> fmt::Debug for Trusted<C> {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        write!(f, "Trusted<{}>({:?})", C::NAME, self.value)
197    }
198}
199
200/// A URL vouched for without a check, for example a `data:` or `sms:` URL.
201pub type TrustedUrl = Trusted<UrlContext>;
202/// A `srcset` vouched for without a check.
203pub type TrustedSrcset = Trusted<SrcsetContext>;
204/// JavaScript vouched for without a check.
205pub type TrustedScript = Trusted<ScriptContext>;
206/// CSS vouched for without a check.
207pub type TrustedStyle = Trusted<StyleContext>;
208/// A document vouched for without a check.
209pub type TrustedDocument = Trusted<DocumentContext>;
210/// A navigation value vouched for without a check.
211pub type TrustedNavigation = Trusted<NavigationContext>;
212/// A script, style or plug-in URL vouched for without a check.
213pub type TrustedResource = Trusted<ResourceContext>;
214/// An SVG animation value vouched for without a check.
215pub type TrustedAnimation = Trusted<AnimationContext>;
216
217#[diagnostic::do_not_recommend]
218impl UrlValue for Trusted<UrlContext> {}
219#[diagnostic::do_not_recommend]
220impl SrcsetValue for Trusted<SrcsetContext> {}
221#[diagnostic::do_not_recommend]
222impl ScriptValue for Trusted<ScriptContext> {}
223#[diagnostic::do_not_recommend]
224impl StyleValue for Trusted<StyleContext> {}
225#[diagnostic::do_not_recommend]
226impl DocumentValue for Trusted<DocumentContext> {}
227#[diagnostic::do_not_recommend]
228impl NavigationValue for Trusted<NavigationContext> {}
229#[diagnostic::do_not_recommend]
230impl ResourceValue for Trusted<ResourceContext> {}
231#[diagnostic::do_not_recommend]
232impl AnimationValue for Trusted<AnimationContext> {}
233
234/// Why a value is not accepted as a [`Url`] or [`Srcset`] part.
235#[derive(Clone, Debug, PartialEq, Eq)]
236pub enum UrlError {
237    /// The URL has a scheme other than `http`, `https`, `mailto` or `tel`.
238    DisallowedScheme(String),
239    /// The URL contains a control character.
240    ControlCharacter,
241    /// The URL cannot stand as a `srcset` candidate (it contains whitespace or a comma).
242    NotSrcsetSafe,
243    /// A `srcset` density descriptor is not a positive finite number.
244    InvalidDensity,
245}
246
247impl fmt::Display for UrlError {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        match self {
250            Self::DisallowedScheme(scheme) => write!(
251                f,
252                "URL scheme `{scheme}` is not allowed (http, https, mailto and tel are)"
253            ),
254            Self::ControlCharacter => f.write_str("URL contains a control character"),
255            Self::NotSrcsetSafe => f.write_str("URL contains whitespace or a comma"),
256            Self::InvalidDensity => f.write_str("srcset density must be a positive finite number"),
257        }
258    }
259}
260
261impl core::error::Error for UrlError {}
262
263/// Schemes a [`Url`] may have.
264const ALLOWED_SCHEMES: [&str; 4] = ["http", "https", "mailto", "tel"];
265
266/// A URL that is relative or has an allowed scheme: `http`, `https`, `mailto`
267/// or `tel`.
268///
269/// [`Url::parse`] sees the value as a browser does: tabs and newlines anywhere
270/// are dropped, leading and trailing control characters and spaces are trimmed,
271/// and the scheme is compared without regard to case. A value that merely looks
272/// harmless to a naive check, such as `JaVa\tScRiPt:...`, is rejected.
273///
274/// A `Url` satisfies [`UrlValue`] only: it cannot be placed in script, style,
275/// document, navigation or resource contexts, where even a valid `https` URL is
276/// dangerous.
277#[derive(Clone, PartialEq, Eq, Hash)]
278pub struct Url(String);
279
280impl Url {
281    /// Check `input` and keep it in the form a browser would read it.
282    pub fn parse(input: &str) -> Result<Self, UrlError> {
283        let stripped: String = input
284            .chars()
285            .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
286            .collect();
287        let trimmed = stripped.trim_matches(|c: char| c <= ' ');
288        if trimmed.chars().any(|c| c.is_ascii_control()) {
289            return Err(UrlError::ControlCharacter);
290        }
291        if let Some(scheme) = scheme_of(trimmed) {
292            let scheme = scheme.to_ascii_lowercase();
293            if !ALLOWED_SCHEMES.contains(&scheme.as_str()) {
294                return Err(UrlError::DisallowedScheme(scheme));
295            }
296        }
297        Ok(Self(trimmed.to_string()))
298    }
299
300    /// The checked URL.
301    pub fn as_str(&self) -> &str {
302        &self.0
303    }
304}
305
306/// The scheme of a cleaned URL as the URL standard finds it: an ASCII letter,
307/// then letters, digits, `+`, `-` or `.`, then `:`. Anything else is relative.
308fn scheme_of(url: &str) -> Option<&str> {
309    let mut chars = url.char_indices();
310    match chars.next() {
311        Some((_, first)) if first.is_ascii_alphabetic() => {}
312        _ => return None,
313    }
314    for (index, c) in chars {
315        match c {
316            ':' => return Some(&url[..index]),
317            c if c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.') => {}
318            _ => return None,
319        }
320    }
321    None
322}
323
324impl fmt::Display for Url {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        f.write_str(&self.0)
327    }
328}
329
330impl fmt::Debug for Url {
331    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332        write!(f, "Url({:?})", self.0)
333    }
334}
335
336impl core::str::FromStr for Url {
337    type Err = UrlError;
338
339    fn from_str(input: &str) -> Result<Self, UrlError> {
340        Self::parse(input)
341    }
342}
343
344impl TryFrom<&str> for Url {
345    type Error = UrlError;
346
347    fn try_from(input: &str) -> Result<Self, UrlError> {
348        Self::parse(input)
349    }
350}
351
352#[diagnostic::do_not_recommend]
353impl UrlValue for Url {}
354
355/// How large a `srcset` candidate renders.
356#[derive(Clone, Copy, Debug, PartialEq)]
357pub enum Descriptor {
358    /// A width in pixels: `480w`.
359    Width(u32),
360    /// A pixel density: `2x`.
361    Density(f32),
362}
363
364/// A `srcset` whose candidates are all checked [`Url`]s.
365#[derive(Clone, Default, PartialEq, Eq, Hash)]
366pub struct Srcset(String);
367
368impl Srcset {
369    /// An empty list.
370    pub fn new() -> Self {
371        Self::default()
372    }
373
374    /// Add a candidate. A URL with whitespace or a comma would end its candidate
375    /// early, so it is refused rather than escaped.
376    pub fn candidate(
377        mut self,
378        url: &Url,
379        descriptor: Option<Descriptor>,
380    ) -> Result<Self, UrlError> {
381        if url.as_str().chars().any(|c| c.is_whitespace() || c == ',') {
382            return Err(UrlError::NotSrcsetSafe);
383        }
384        if let Some(Descriptor::Density(density)) = descriptor
385            && (!density.is_finite() || density <= 0.0)
386        {
387            return Err(UrlError::InvalidDensity);
388        }
389        if !self.0.is_empty() {
390            self.0.push_str(", ");
391        }
392        self.0.push_str(url.as_str());
393        match descriptor {
394            Some(Descriptor::Width(width)) => {
395                self.0.push(' ');
396                self.0.push_str(&width.to_string());
397                self.0.push('w');
398            }
399            Some(Descriptor::Density(density)) => {
400                self.0.push(' ');
401                self.0.push_str(&density.to_string());
402                self.0.push('x');
403            }
404            None => {}
405        }
406        Ok(self)
407    }
408
409    /// The rendered list.
410    pub fn as_str(&self) -> &str {
411        &self.0
412    }
413}
414
415impl fmt::Display for Srcset {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        f.write_str(&self.0)
418    }
419}
420
421impl fmt::Debug for Srcset {
422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423        write!(f, "Srcset({:?})", self.0)
424    }
425}
426
427#[diagnostic::do_not_recommend]
428impl SrcsetValue for Srcset {}