Skip to content
1        10        20        30        40        50        60        70        80        901use std::net::IpAddr;23use anyhow::{Context, bail};4use reqwest::Url;56#[cfg(not(feature = "testing"))]7pub const DEFAULT_TWIG_URL: &str = "https://twig.silenlocatelli.ch/";89#[derive(Clone, Debug, Eq, Hash, PartialEq)]10pub struct TwigUrl(Url);1112impl TwigUrl {13    pub fn parse(input: &str) -> anyhow::Result<Self> {14        let mut url = Url::parse(input.trim()).context("Twig URL must be an absolute URL")?;15        if !matches!(url.scheme(), "http" | "https") {16            bail!("Twig URL must use HTTPS (HTTP is allowed only for loopback development URLs)");17        }18        if !url.username().is_empty() || url.password().is_some() {19            bail!("Twig URL must not contain a username or password");20        }21        if url.query().is_some() || url.fragment().is_some() {22            bail!("Twig URL must not contain a query string or fragment");23        }24        if url.scheme() == "http" && !url.host_str().is_some_and(is_loopback_host) {25            bail!("Twig URL must use HTTPS unless it points to a loopback address");26        }2728        let mut base_path = url.path().to_string();29        if !base_path.ends_with('/') {30            base_path.push('/');31            url.set_path(&base_path);32        }3334        Ok(Self(url))35    }3637    pub fn as_url(&self) -> &Url {38        &self.039    }4041    pub fn matches_git_request(&self, protocol: &str, host: &str, path: Option<&str>) -> bool {42        if !protocol.eq_ignore_ascii_case(self.0.scheme()) {43            return false;44        }4546        let Ok(request_url) = Url::parse(&format!("{protocol}://{host}/")) else {47            return false;48        };49        if !request_url50            .host_str()51            .zip(self.0.host_str())52            .is_some_and(|(request_host, base_host)| request_host.eq_ignore_ascii_case(base_host))53            || request_url.port_or_known_default() != self.0.port_or_known_default()54        {55            return false;56        }5758        let base_path = self.0.path().trim_matches('/');59        if base_path.is_empty() {60            return true;61        }62        let Some(path) = path else {63            return false;64        };65        let request_path = path.trim_matches('/');66        request_path == base_path67            || request_path68                .strip_prefix(base_path)69                .is_some_and(|suffix| suffix.starts_with('/'))70    }71}7273fn is_loopback_host(host: &str) -> bool {74    let host = host75        .strip_prefix('[')76        .and_then(|host| host.strip_suffix(']'))77        .unwrap_or(host);78    host.eq_ignore_ascii_case("localhost")79        || host80            .parse::<IpAddr>()81            .is_ok_and(|address| address.is_loopback())82}8384#[cfg(test)]85mod tests {86    use super::*;8788    #[test]89    fn accepts_the_default_https_twig_url_and_normalizes_its_root() {90        let url = TwigUrl::parse("https://twig.silenlocatelli.ch").unwrap();9192        assert_eq!(url.as_url().as_str(), "https://twig.silenlocatelli.ch/");93    }9495    #[test]96    fn allows_http_only_for_loopback_development_urls() {97        assert!(TwigUrl::parse("http://127.0.0.1:8080/").is_ok());98        assert!(TwigUrl::parse("http://[::1]:8080/").is_ok());99        assert!(TwigUrl::parse("http://twig.example.dev/").is_err());100    }101102    #[test]103    fn rejects_userinfo_queries_and_fragments() {104        for value in [105            "https://user:pass@twig.example.dev/",106            "https://twig.example.dev/?token=secret",107            "https://twig.example.dev/#fragment",108        ] {109            assert!(TwigUrl::parse(value).is_err(), "accepted {value}");110        }111    }112113    #[test]114    fn matches_only_the_authorized_scheme_host_port_and_path_prefix() {115        let url = TwigUrl::parse("https://git.example.dev/twig/").unwrap();116117        assert!(url.matches_git_request(118            "https",119            "git.example.dev",120            Some("twig/platform/repo.git")121        ));122        assert!(!url.matches_git_request(123            "https",124            "git.example.dev",125            Some("other/platform/repo.git")126        ));127        assert!(!url.matches_git_request(128            "http",129            "git.example.dev",130            Some("twig/platform/repo.git")131        ));132        assert!(!url.matches_git_request(133            "https",134            "other.example.dev",135            Some("twig/platform/repo.git")136        ));137    }138}