Skip to main content

tilo_dialogs/
web_policy.rs

1//! Decisions the browser host makes before it touches the page. They need no
2//! JavaScript, so they build and are tested natively.
3
4/// Whether `uri` may be handed to `window.open`: web pages and composing
5/// links only. `javascript:`, `data:`, `blob:` and `file:` would run script
6/// in, or expose content to, the console's origin.
7pub fn openable_uri(uri: &str) -> Result<(), String> {
8    const OPENABLE: [&str; 4] = ["http", "https", "mailto", "tel"];
9    let scheme = uri
10        .split_once(':')
11        .map(|(scheme, _)| scheme)
12        .filter(|scheme| {
13            let mut chars = scheme.chars();
14            chars.next().is_some_and(|c| c.is_ascii_alphabetic())
15                && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
16        })
17        .ok_or_else(|| format!("not an absolute URI: {uri:?}"))?
18        .to_ascii_lowercase();
19    if uri.chars().any(char::is_control) {
20        return Err("URI contains control characters".to_owned());
21    }
22    if OPENABLE.contains(&scheme.as_str()) {
23        Ok(())
24    } else {
25        Err(format!("a browser host does not open {scheme}: URIs"))
26    }
27}
28
29/// The `accept` attribute of an `<input type=file>` for a chooser offering
30/// `globs` and `mimetypes`. Empty (anything) when no filter was given or one
31/// cannot be expressed: a narrower chooser than the reader would hide files
32/// the app could open.
33pub fn accept_attribute<'a>(
34    globs: impl IntoIterator<Item = &'a str>,
35    mimetypes: impl IntoIterator<Item = &'a str>,
36) -> String {
37    let mut accepted = Vec::new();
38    for glob in globs {
39        let Some(extension) = glob.strip_prefix("*.") else {
40            return String::new();
41        };
42        if extension.is_empty() || extension.contains(['*', '?', '[', ',', '/']) {
43            return String::new();
44        }
45        accepted.push(format!(".{extension}"));
46    }
47    for mime in mimetypes {
48        if mime.contains(',') || !mime.contains('/') {
49            return String::new();
50        }
51        accepted.push(mime.to_owned());
52    }
53    accepted.dedup();
54    accepted.join(",")
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    tilo_test_env::scenario! {
62        fn a_web_page_opens_only_safe_schemes_and_lists_what_its_picker_accepts;
63
64        phase only_web_and_composing_schemes_open;
65        {
66            for uri in [
67                "https://tilo.so/docs",
68                "HTTP://example.com",
69                "mailto:ada@example.com",
70                "tel:+15551234",
71            ] {
72                assert_eq!(openable_uri(uri), Ok(()), "{uri}");
73            }
74            for uri in [
75                "javascript:alert(1)",
76                " JavaScript:alert(1)",
77                "data:text/html,<script>",
78                "blob:https://console/1",
79                "file:///etc/passwd",
80                "settings:display",
81                "relative/path",
82                "https://example.com/\u{0}x",
83            ] {
84                assert!(openable_uri(uri).is_err(), "{uri}");
85            }
86        }
87
88        phase accept_lists_extensions_and_types_or_admits_everything;
89        {
90            assert_eq!(
91                accept_attribute(["*.png", "*.tar.gz"], ["image/png"]),
92                ".png,.tar.gz,image/png"
93            );
94            assert_eq!(accept_attribute([], []), "");
95            assert_eq!(accept_attribute(["*.md", "*"], []), "", "All files");
96            assert_eq!(accept_attribute(["Makefile"], []), "");
97            assert_eq!(accept_attribute(["*.[ch]"], []), "");
98            assert_eq!(accept_attribute([], ["text/*"]), "text/*");
99        }
100    }
101}