Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
nav_guard.rs

1//! The navigation guard: a window stays on the app's own pages (its local page, or the hosted web app it shows); a web link
2//! elsewhere opens in the person's browser; anything else is refused.
3
4use std::fmt;
5use url::Url;
6
7/// Why an address cannot be a hosted app's origin. None of them repeats the address: it may hold a credential.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum OriginError {
10    NotAUrl,
11    Credentials,
12    MissingHost,
13    NotHttps,
14}
15
16impl OriginError {
17    /// The stable code the page reads (never reworded).
18    pub fn code(self) -> &'static str {
19        match self {
20            OriginError::NotAUrl => "origin_not_a_url",
21            OriginError::Credentials => "origin_credentials",
22            OriginError::MissingHost => "origin_missing_host",
23            OriginError::NotHttps => "origin_not_https",
24        }
25    }
26}
27
28impl fmt::Display for OriginError {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        f.write_str(match self {
31            OriginError::NotAUrl => "not a valid URL",
32            OriginError::Credentials => "no credentials in the URL",
33            OriginError::MissingHost => "missing host",
34            OriginError::NotHttps => "the app must be served over https",
35        })
36    }
37}
38
39impl std::error::Error for OriginError {}
40
41/// A hosted app must be HTTPS (plain http only for a loopback address), carry no credentials in its URL, and is reduced
42/// to its origin.
43pub fn normalize_origin(input: &str) -> Result<String, OriginError> {
44    let url = Url::parse(input.trim()).map_err(|_| OriginError::NotAUrl)?;
45    if !url.username().is_empty() || url.password().is_some() {
46        return Err(OriginError::Credentials);
47    }
48    let host = url.host_str().ok_or(OriginError::MissingHost)?;
49    let loopback = matches!(host, "localhost" | "127.0.0.1" | "[::1]");
50    match url.scheme() {
51        "https" => {}
52        "http" if loopback => {}
53        _ => return Err(OriginError::NotHttps),
54    }
55    Ok(url.origin().ascii_serialization())
56}
57
58/// True when `target` is on the same origin as `allowed`. A look-alike host (`app.example.com.evil.example`) is not.
59pub fn same_origin(allowed: &str, target: &Url) -> bool {
60    Url::parse(allowed)
61        .map(|a| a.origin() == target.origin())
62        .unwrap_or(false)
63}
64
65/// What the window does with a navigation.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum Navigation {
68    /// One of the app's own places: the window goes there.
69    Stay,
70    /// A web page elsewhere: the window stays, the person's browser opens it.
71    Browser,
72    /// Anything else (`file:`, `javascript:`, `data:`, another app's scheme): nothing happens.
73    Refuse,
74}
75
76/// The same place: scheme, host and port. Unlike [`same_origin`], it also matches the app's own local page
77/// (`tauri://localhost`), whose origin the URL standard calls opaque.
78pub fn same_place(allowed: &str, target: &Url) -> bool {
79    let Ok(a) = Url::parse(allowed) else {
80        return false;
81    };
82    a.scheme() == target.scheme()
83        && a.host_str().is_some()
84        && a.host_str() == target.host_str()
85        && a.port_or_known_default() == target.port_or_known_default()
86        && target.username().is_empty()
87        && target.password().is_none()
88}
89
90/// Decides a navigation of a window whose own places are `allowed` (the local page, the hosted app's origin).
91pub fn decide(allowed: &[String], target: &Url) -> Navigation {
92    if allowed.iter().any(|a| same_place(a, target)) {
93        return Navigation::Stay;
94    }
95    match target.scheme() {
96        // The page's own blank frame and the object URLs it made (a PDF shown from memory).
97        "about" if target.as_str() == "about:blank" => Navigation::Stay,
98        "blob" => match Url::parse(target.path()) {
99            Ok(inner) if allowed.iter().any(|a| same_place(a, &inner)) => Navigation::Stay,
100            _ => Navigation::Refuse,
101        },
102        "https" | "http" | "mailto"
103            if target.username().is_empty() && target.password().is_none() =>
104        {
105            Navigation::Browser
106        }
107        _ => Navigation::Refuse,
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    fn places() -> Vec<String> {
116        vec![
117            "tauri://localhost".into(),
118            "https://www.verikora.com".into(),
119        ]
120    }
121
122    fn at(url: &str) -> Url {
123        Url::parse(url).unwrap()
124    }
125
126    #[test]
127    fn the_window_stays_on_its_own_places() {
128        for own in [
129            "tauri://localhost/index.html",
130            "https://www.verikora.com/app/rapports",
131            "about:blank",
132            "blob:tauri://localhost/5f1c-77",
133        ] {
134            assert_eq!(decide(&places(), &at(own)), Navigation::Stay, "{own}");
135        }
136    }
137
138    #[test]
139    fn a_web_page_elsewhere_opens_in_the_browser_and_the_rest_is_refused() {
140        for web in [
141            "https://www.krizaka.com/privacy",
142            "http://example.com/",
143            "mailto:support@krizaka.com",
144        ] {
145            assert_eq!(decide(&places(), &at(web)), Navigation::Browser, "{web}");
146        }
147        for refused in [
148            "file:///etc/passwd",
149            "javascript:alert(1)",
150            "data:text/html,<script>1</script>",
151            "sovkora://app",
152            "tauri://evil",
153            "blob:https://evil.example/1",
154            "https://user:pw@evil.example/",
155        ] {
156            assert_eq!(
157                decide(&places(), &at(refused)),
158                Navigation::Refuse,
159                "{refused}"
160            );
161        }
162        assert_eq!(
163            decide(&places(), &at("https://www.verikora.com.evil.example/")),
164            Navigation::Browser
165        );
166        assert_eq!(
167            decide(&places(), &at("https://www.verikora.com:8443/")),
168            Navigation::Browser
169        );
170    }
171
172    #[test]
173    fn an_origin_is_https_or_loopback_and_reduced_to_its_origin() {
174        assert_eq!(
175            normalize_origin("https://www.verikora.com/some/path?x=1").unwrap(),
176            "https://www.verikora.com"
177        );
178        assert_eq!(
179            normalize_origin("http://localhost:3000/").unwrap(),
180            "http://localhost:3000"
181        );
182    }
183
184    #[test]
185    fn refuses_plain_http_credentials_and_other_schemes() {
186        for bad in [
187            "http://www.verikora.com",
188            "https://user:pw@www.verikora.com",
189            "file:///etc/passwd",
190            "javascript:alert(1)",
191            "nonsense",
192        ] {
193            assert!(normalize_origin(bad).is_err(), "{bad}");
194        }
195    }
196
197    #[test]
198    fn compares_origins_and_refuses_look_alikes() {
199        let allowed = "https://www.verikora.com";
200        assert!(same_origin(
201            allowed,
202            &Url::parse("https://www.verikora.com/login").unwrap()
203        ));
204        assert!(!same_origin(
205            allowed,
206            &Url::parse("https://evil.example/").unwrap()
207        ));
208        assert!(!same_origin(
209            allowed,
210            &Url::parse("https://www.verikora.com.evil.example/").unwrap()
211        ));
212        assert!(!same_origin(
213            "not a url",
214            &Url::parse("https://www.verikora.com/").unwrap()
215        ));
216    }
217}