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