Skip to main content

jev_client/
base_url.rs

1//! The API root, validated so that a key is never sent somewhere it should not go.
2
3use std::fmt;
4use std::net::IpAddr;
5
6use reqwest::Url;
7
8/// The default API root.
9const DEFAULT_BASE_URL: &str = "https://api.typesafe.ai";
10
11/// The root URL of the TypeSafe API, such as `https://api.typesafe.ai`.
12///
13/// A base URL must use `https://`. Plain `http://` is accepted for a loopback address, which is
14/// what a local mock server uses, and otherwise only through
15/// [`BaseUrl::parse_allowing_insecure_http`], an explicit opt-in. A URL carrying credentials, a
16/// query string or a fragment is always rejected.
17///
18/// ```
19/// use jev_client::BaseUrl;
20///
21/// assert_eq!(BaseUrl::default().as_str(), "https://api.typesafe.ai/");
22/// assert!(BaseUrl::parse("http://127.0.0.1:8080").is_ok());
23/// assert!(BaseUrl::parse("http://example.com").is_err());
24/// ```
25#[derive(Clone, PartialEq, Eq)]
26pub struct BaseUrl {
27    url: Url,
28    sends_key_in_clear: bool,
29}
30
31impl BaseUrl {
32    /// Parses a base URL, requiring `https://` for anything that is not a loopback address.
33    ///
34    /// # Errors
35    ///
36    /// See [`InvalidBaseUrl`]. The error never echoes the input, which could hold credentials.
37    pub fn parse(input: &str) -> Result<Self, InvalidBaseUrl> {
38        Self::parse_with(input, false)
39    }
40
41    /// Parses a base URL, also accepting plain `http://` to a host that is not loopback.
42    ///
43    /// The API key then crosses the network unencrypted. This exists for unusual test setups;
44    /// a caller that uses it should warn, as [`BaseUrl::sends_key_in_clear`] allows.
45    ///
46    /// # Errors
47    ///
48    /// See [`InvalidBaseUrl`].
49    pub fn parse_allowing_insecure_http(input: &str) -> Result<Self, InvalidBaseUrl> {
50        Self::parse_with(input, true)
51    }
52
53    fn parse_with(input: &str, allow_insecure_http: bool) -> Result<Self, InvalidBaseUrl> {
54        let mut url = Url::parse(input.trim()).map_err(|_| InvalidBaseUrl::Malformed)?;
55
56        if !url.username().is_empty() || url.password().is_some() {
57            return Err(InvalidBaseUrl::HasCredentials);
58        }
59        if url.query().is_some() || url.fragment().is_some() {
60            return Err(InvalidBaseUrl::HasQueryOrFragment);
61        }
62        let loopback = match url.host() {
63            None => return Err(InvalidBaseUrl::Malformed),
64            Some(host) => is_loopback(&host),
65        };
66        let sends_key_in_clear = match url.scheme() {
67            "https" => false,
68            "http" if loopback => false,
69            "http" if allow_insecure_http => true,
70            "http" => return Err(InvalidBaseUrl::InsecureHttp),
71            _ => return Err(InvalidBaseUrl::UnsupportedScheme),
72        };
73
74        // A trailing slash makes `join` append to the path instead of replacing its last segment.
75        if !url.path().ends_with('/') {
76            let path = format!("{}/", url.path());
77            url.set_path(&path);
78        }
79        Ok(Self {
80            url,
81            sends_key_in_clear,
82        })
83    }
84
85    /// The URL as text, always ending in `/`.
86    #[must_use]
87    pub fn as_str(&self) -> &str {
88        self.url.as_str()
89    }
90
91    /// Returns `true` when requests travel over plain `http://` to a host that is not loopback,
92    /// which only [`BaseUrl::parse_allowing_insecure_http`] permits.
93    #[must_use]
94    pub const fn sends_key_in_clear(&self) -> bool {
95        self.sends_key_in_clear
96    }
97
98    /// Returns `true` when the URL uses `https://`.
99    pub(crate) fn is_https(&self) -> bool {
100        self.url.scheme() == "https"
101    }
102
103    /// The URL of an endpoint, given its path relative to the root (no leading slash).
104    pub(crate) fn endpoint(&self, relative_path: &str) -> Result<Url, InvalidBaseUrl> {
105        self.url
106            .join(relative_path)
107            .map_err(|_| InvalidBaseUrl::Malformed)
108    }
109}
110
111impl Default for BaseUrl {
112    fn default() -> Self {
113        // The constant is a valid HTTPS URL; a unit test pins that down.
114        Self::parse(DEFAULT_BASE_URL).unwrap_or_else(|_| unreachable!("default base URL is valid"))
115    }
116}
117
118impl fmt::Debug for BaseUrl {
119    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(formatter, "BaseUrl({})", self.url)
121    }
122}
123
124impl fmt::Display for BaseUrl {
125    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126        formatter.write_str(self.url.as_str())
127    }
128}
129
130fn is_loopback(host: &url::Host<&str>) -> bool {
131    match host {
132        url::Host::Domain(name) => name.eq_ignore_ascii_case("localhost"),
133        url::Host::Ipv4(address) => IpAddr::V4(*address).is_loopback(),
134        url::Host::Ipv6(address) => IpAddr::V6(*address).is_loopback(),
135    }
136}
137
138/// Why a string was rejected as a base URL.
139///
140/// The messages describe the problem without echoing the input, because a rejected URL may be one
141/// that embeds a password.
142#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
143#[non_exhaustive]
144pub enum InvalidBaseUrl {
145    /// Not an absolute URL with a host.
146    #[error("the base URL is not a valid absolute URL such as https://api.typesafe.ai")]
147    Malformed,
148    /// A scheme other than `https` or `http`.
149    #[error("the base URL must start with https://")]
150    UnsupportedScheme,
151    /// Plain `http://` to a host that is not loopback, without the explicit opt-in.
152    #[error(
153        "the base URL must use https://; plain http:// is accepted only for a loopback address, \
154         or when insecure HTTP is explicitly allowed"
155    )]
156    InsecureHttp,
157    /// A user name or password in the URL.
158    #[error("the base URL must not contain a user name or password")]
159    HasCredentials,
160    /// A `?query` or `#fragment` in the URL.
161    #[error("the base URL must not contain a query string or a fragment")]
162    HasQueryOrFragment,
163}
164
165#[cfg(test)]
166mod tests {
167    use super::{BaseUrl, InvalidBaseUrl};
168
169    #[test]
170    fn the_default_is_the_public_api_over_https() {
171        let base = BaseUrl::default();
172
173        assert_eq!(base.as_str(), "https://api.typesafe.ai/");
174        assert!(base.is_https());
175        assert!(!base.sends_key_in_clear());
176    }
177
178    #[test]
179    fn plain_http_is_rejected_unless_the_host_is_loopback() {
180        assert_eq!(
181            BaseUrl::parse("http://example.com"),
182            Err(InvalidBaseUrl::InsecureHttp)
183        );
184        assert_eq!(
185            BaseUrl::parse("http://192.168.1.10:8080"),
186            Err(InvalidBaseUrl::InsecureHttp)
187        );
188        assert_eq!(
189            BaseUrl::parse("http://localhost.example.com"),
190            Err(InvalidBaseUrl::InsecureHttp)
191        );
192
193        for loopback in [
194            "http://127.0.0.1:4010",
195            "http://127.8.8.8",
196            "http://[::1]:4010",
197            "http://LOCALHOST:1",
198        ] {
199            let base = BaseUrl::parse(loopback).unwrap();
200            assert!(!base.sends_key_in_clear(), "{loopback}");
201        }
202    }
203
204    #[test]
205    fn insecure_http_needs_the_explicit_opt_in_and_is_flagged() {
206        let base = BaseUrl::parse_allowing_insecure_http("http://example.com").unwrap();
207
208        assert!(base.sends_key_in_clear());
209        assert!(
210            !BaseUrl::parse_allowing_insecure_http("https://example.com")
211                .unwrap()
212                .sends_key_in_clear()
213        );
214    }
215
216    #[test]
217    fn rejects_credentials_queries_and_other_schemes_without_echoing_them() {
218        let cases = [
219            (
220                "https://user:hunter2@example.com",
221                InvalidBaseUrl::HasCredentials,
222            ),
223            ("https://token@example.com", InvalidBaseUrl::HasCredentials),
224            (
225                "https://example.com/?key=hunter2",
226                InvalidBaseUrl::HasQueryOrFragment,
227            ),
228            (
229                "https://example.com/#hunter2",
230                InvalidBaseUrl::HasQueryOrFragment,
231            ),
232            ("ftp://example.com", InvalidBaseUrl::UnsupportedScheme),
233            ("file:///etc/passwd", InvalidBaseUrl::Malformed),
234            ("api.typesafe.ai", InvalidBaseUrl::Malformed),
235            ("", InvalidBaseUrl::Malformed),
236        ];
237
238        for (input, expected) in cases {
239            let error = BaseUrl::parse(input).unwrap_err();
240
241            assert_eq!(error, expected, "{input}");
242            assert!(!error.to_string().contains("hunter2"), "{error}");
243        }
244        // The opt-in relaxes the scheme rule only.
245        assert_eq!(
246            BaseUrl::parse_allowing_insecure_http("http://user:hunter2@example.com"),
247            Err(InvalidBaseUrl::HasCredentials)
248        );
249    }
250
251    #[test]
252    fn endpoints_are_appended_to_the_root_and_to_a_path_prefix() {
253        let root = BaseUrl::parse("https://api.typesafe.ai").unwrap();
254        let prefixed = BaseUrl::parse("https://gateway.example.com/typesafe").unwrap();
255
256        assert_eq!(
257            root.endpoint("v1/systemone").unwrap().as_str(),
258            "https://api.typesafe.ai/v1/systemone"
259        );
260        assert_eq!(
261            prefixed.endpoint("v1/models").unwrap().as_str(),
262            "https://gateway.example.com/typesafe/v1/models"
263        );
264        assert_eq!(
265            prefixed.to_string(),
266            "https://gateway.example.com/typesafe/"
267        );
268    }
269}