Skip to main content

subspace_core/http/
service_url.rs

1/// The supplied service URL was not a plain HTTPS origin and path.
2#[derive(Debug, thiserror::Error)]
3#[error("must be a plain https URL (no credentials, query or fragment)")]
4pub struct InvalidUrl;
5
6/// Checks a service base URL: `https`, no credentials, query or fragment.
7/// Returns the origin and path without a trailing slash.
8pub fn plain_https_url(value: &str) -> Result<String, InvalidUrl> {
9    let url = url::Url::parse(value).map_err(|_| InvalidUrl)?;
10    let plain = url.scheme() == "https"
11        && url.username().is_empty()
12        && url.password().is_none()
13        && url.query().is_none()
14        && url.fragment().is_none();
15    if !plain {
16        return Err(InvalidUrl);
17    }
18    Ok(format!(
19        "{}{}",
20        url.origin().ascii_serialization(),
21        url.path().trim_end_matches('/')
22    ))
23}
24
25#[cfg(test)]
26mod tests {
27    use super::plain_https_url;
28
29    #[test]
30    fn plain_https_urls() {
31        assert_eq!(
32            plain_https_url("https://Service.Example.com:443/api//")
33                .as_deref()
34                .map_err(ToString::to_string),
35            Ok("https://service.example.com/api")
36        );
37        assert_eq!(
38            plain_https_url("https://service.example.com")
39                .map_err(|error| error.to_string())
40                .as_deref(),
41            Ok("https://service.example.com")
42        );
43        assert_eq!(
44            plain_https_url("https://service.example.com:8443/")
45                .map_err(|error| error.to_string())
46                .as_deref(),
47            Ok("https://service.example.com:8443")
48        );
49        for bad in [
50            "",
51            "service.example.com",
52            "http://service.example.com",
53            "https://user@service.example.com",
54            "https://user:pw@service.example.com",
55            "https://service.example.com/?a=1",
56            "https://service.example.com/#top",
57        ] {
58            assert!(plain_https_url(bad).is_err(), "{bad}");
59        }
60    }
61}