Skip to main content

fetchium_core/http/
tls.rs

1//! TLS enforcement: require HTTPS, allow HTTP only for localhost (PRD §41).
2
3use crate::error::FetchiumError;
4use url::Url;
5
6/// Reject plain HTTP for remote hosts; allow localhost for development.
7///
8/// PRD §41: "TLS enforcement — always HTTPS for remote hosts."
9///
10/// # Examples
11/// ```rust
12/// use fetchium_core::http::tls::enforce_tls;
13/// assert!(enforce_tls("https://example.com").is_ok());
14/// assert!(enforce_tls("http://localhost:11434").is_ok());
15/// assert!(enforce_tls("http://example.com").is_err());
16/// ```
17pub fn enforce_tls(url: &str) -> Result<(), FetchiumError> {
18    let parsed = Url::parse(url).map_err(|e| FetchiumError::InvalidUrl(format!("{url}: {e}")))?;
19    match parsed.scheme() {
20        "https" => Ok(()),
21        "http" if is_localhost(&parsed) => Ok(()),
22        "http" => Err(FetchiumError::InsecureConnection {
23            url: url.to_string(),
24            suggestion: format!(
25                "Use https://{} instead",
26                parsed.host_str().unwrap_or("unknown")
27            ),
28        }),
29        scheme => Err(FetchiumError::InvalidUrl(format!(
30            "Unsupported URL scheme: '{scheme}'"
31        ))),
32    }
33}
34
35fn is_localhost(url: &Url) -> bool {
36    matches!(
37        url.host_str(),
38        Some("localhost") | Some("127.0.0.1") | Some("::1")
39    )
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn https_is_allowed() {
48        assert!(enforce_tls("https://example.com").is_ok());
49        assert!(enforce_tls("https://docs.rust-lang.org/book/").is_ok());
50    }
51
52    #[test]
53    fn http_localhost_is_allowed() {
54        assert!(enforce_tls("http://localhost:11434").is_ok());
55        assert!(enforce_tls("http://127.0.0.1:8080").is_ok());
56        assert!(enforce_tls("http://127.0.0.1:3000/api").is_ok());
57    }
58
59    #[test]
60    fn http_remote_is_rejected() {
61        let err = enforce_tls("http://example.com").unwrap_err();
62        match err {
63            FetchiumError::InsecureConnection { url, .. } => {
64                assert!(url.contains("example.com"));
65            }
66            other => panic!("Expected InsecureConnection, got {other:?}"),
67        }
68    }
69
70    #[test]
71    fn invalid_url_rejected() {
72        assert!(enforce_tls("not a url").is_err());
73        assert!(enforce_tls("").is_err());
74    }
75
76    #[test]
77    fn unsupported_scheme_rejected() {
78        assert!(enforce_tls("ftp://example.com").is_err());
79    }
80}