Skip to main content

fetchlet_http/service/
origin.rs

1use http::Uri;
2use http::uri::{Authority, PathAndQuery, Scheme};
3
4use super::Error;
5
6/// The configured public scheme and authority of incoming requests.
7///
8/// Servers see a path and a Host header that clients choose; the application
9/// sees this origin with the incoming path and query instead.
10#[derive(Clone, Debug)]
11pub struct PublicOrigin {
12    scheme: Scheme,
13    authority: Authority,
14}
15
16impl PublicOrigin {
17    pub fn parse(value: &str) -> Result<Self, Error> {
18        let uri: Uri = value.parse().map_err(|_| Error::InvalidOrigin)?;
19        let (Some(scheme), Some(authority)) = (uri.scheme(), uri.authority()) else {
20            return Err(Error::InvalidOrigin);
21        };
22        if !matches!(scheme.as_str(), "http" | "https")
23            || authority.as_str().contains('@')
24            || uri.path() != "/"
25            || uri.query().is_some()
26            || value.contains('#')
27        {
28            return Err(Error::InvalidOrigin);
29        }
30        Ok(Self {
31            scheme: scheme.clone(),
32            authority: authority.clone(),
33        })
34    }
35
36    /// Replace the scheme and authority, keeping the path and query.
37    pub fn apply(&self, uri: Uri) -> Result<Uri, Error> {
38        let mut parts = uri.into_parts();
39        parts.scheme = Some(self.scheme.clone());
40        parts.authority = Some(self.authority.clone());
41        if parts.path_and_query.is_none() {
42            parts.path_and_query = Some(PathAndQuery::from_static("/"));
43        }
44        Uri::from_parts(parts).map_err(Error::InvalidRequestUri)
45    }
46
47    /// Apply the origin to a request target such as `/path?query`.
48    pub fn resolve(&self, path_and_query: &str) -> Result<Uri, Error> {
49        let path_and_query: PathAndQuery = path_and_query
50            .parse()
51            .map_err(|_| Error::InvalidRequest("invalid request target".into()))?;
52        let mut parts = http::uri::Parts::default();
53        parts.path_and_query = Some(path_and_query);
54        self.apply(Uri::from_parts(parts).map_err(Error::InvalidRequestUri)?)
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn accepts_an_http_or_https_scheme_and_authority() {
64        for value in [
65            "https://app.test",
66            "https://app.test/",
67            "http://127.0.0.1:8080",
68            "http://[::1]:3000/",
69        ] {
70            assert!(PublicOrigin::parse(value).is_ok(), "{value}");
71        }
72    }
73
74    #[test]
75    fn refuses_anything_beyond_an_origin() {
76        for value in [
77            "app.test",
78            "/path",
79            "ftp://app.test",
80            "https://user@app.test",
81            "https://app.test/base",
82            "https://app.test/?query",
83            "https://app.test/#fragment",
84            "https://",
85            "",
86        ] {
87            assert!(
88                matches!(PublicOrigin::parse(value), Err(Error::InvalidOrigin)),
89                "{value}"
90            );
91        }
92    }
93
94    #[test]
95    fn applies_the_origin_and_keeps_the_path_and_query() {
96        let origin = PublicOrigin::parse("https://app.test:8443").unwrap();
97        let uri: Uri = "http://client-chosen.example/a/b?c=d".parse().unwrap();
98        assert_eq!(
99            origin.apply(uri).unwrap().to_string(),
100            "https://app.test:8443/a/b?c=d"
101        );
102        let authority_only: Uri = "client-chosen.example".parse().unwrap();
103        assert_eq!(
104            origin.apply(authority_only).unwrap().to_string(),
105            "https://app.test:8443/"
106        );
107    }
108
109    #[test]
110    fn resolves_request_targets() {
111        let origin = PublicOrigin::parse("http://localhost:3000/").unwrap();
112        assert_eq!(
113            origin.resolve("/search?q=1").unwrap().to_string(),
114            "http://localhost:3000/search?q=1"
115        );
116        assert!(matches!(
117            origin.resolve("/with space"),
118            Err(Error::InvalidRequest(_))
119        ));
120    }
121}