Skip to main content

appstruct_runtime/
origin.rs

1// Browser origin validation used by generated Auth configuration.
2
3use url::Url;
4
5/// Validates an exact HTTP(S) origin used for CORS, CSRF, and frontend links.
6///
7/// # Errors
8///
9/// Returns an error when the value is empty, not `http`/`https`, or includes
10/// credentials, a path, query, or fragment.
11pub fn validate_browser_origin(name: &str, value: &str) -> Result<String, String> {
12    let value = value.trim();
13    if value.is_empty() {
14        return Err(format!("{name} must not be empty"));
15    }
16    if value
17        .bytes()
18        .any(|byte| byte == b'\\' || !byte.is_ascii_graphic())
19    {
20        return Err(format!("{name} must be an ASCII HTTP origin"));
21    }
22    let parsed = Url::parse(value).map_err(|_| format!("{name} must be a valid http(s) origin"))?;
23    if !matches!(parsed.scheme(), "http" | "https") {
24        return Err(format!("{name} must be an http(s) origin"));
25    }
26    let rest = value
27        .split_once("://")
28        .map(|(_, rest)| rest)
29        .ok_or_else(|| format!("{name} must be an http(s) origin"))?;
30    if parsed.host().is_none()
31        || !parsed.username().is_empty()
32        || parsed.password().is_some()
33        || rest.is_empty()
34        || rest.contains(['/', '?', '#', '@'])
35    {
36        return Err(format!(
37            "{name} must be an origin without credentials, path, query, or fragment"
38        ));
39    }
40    Ok(parsed.origin().ascii_serialization())
41}
42
43#[cfg(test)]
44mod tests {
45    use super::validate_browser_origin;
46
47    #[test]
48    fn accepts_http_and_https_origins() {
49        assert_eq!(
50            validate_browser_origin("ORIGIN", "http://127.0.0.1:5173").unwrap(),
51            "http://127.0.0.1:5173"
52        );
53        assert_eq!(
54            validate_browser_origin("ORIGIN", "https://app.example.com").unwrap(),
55            "https://app.example.com"
56        );
57        assert_eq!(
58            validate_browser_origin("ORIGIN", "  http://[::1]:5173  ").unwrap(),
59            "http://[::1]:5173"
60        );
61        assert_eq!(
62            validate_browser_origin("ORIGIN", "HTTPS://Example.COM:443").unwrap(),
63            "https://example.com"
64        );
65    }
66
67    #[test]
68    fn rejects_empty_non_http_and_non_origin_urls() {
69        for value in [
70            "",
71            "ftp://example.com",
72            "http://example.com/",
73            "https://example.com/path",
74            "http://user@host",
75            "https://example.com?q=1",
76            "http://example.com#frag",
77            "https://:443",
78            "https://example.com:bad",
79            "https://[::1",
80            "https://example.com:443:bad",
81        ] {
82            assert!(validate_browser_origin("ORIGIN", value).is_err(), "{value}");
83        }
84    }
85}