1use std::fmt;
4use std::net::IpAddr;
5
6use reqwest::Url;
7
8const DEFAULT_BASE_URL: &str = "https://api.typesafe.ai";
10
11#[derive(Clone, PartialEq, Eq)]
26pub struct BaseUrl {
27 url: Url,
28 sends_key_in_clear: bool,
29}
30
31impl BaseUrl {
32 pub fn parse(input: &str) -> Result<Self, InvalidBaseUrl> {
38 Self::parse_with(input, false)
39 }
40
41 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 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 #[must_use]
87 pub fn as_str(&self) -> &str {
88 self.url.as_str()
89 }
90
91 #[must_use]
94 pub const fn sends_key_in_clear(&self) -> bool {
95 self.sends_key_in_clear
96 }
97
98 pub(crate) fn is_https(&self) -> bool {
100 self.url.scheme() == "https"
101 }
102
103 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
143#[non_exhaustive]
144pub enum InvalidBaseUrl {
145 #[error("the base URL is not a valid absolute URL such as https://api.typesafe.ai")]
147 Malformed,
148 #[error("the base URL must start with https://")]
150 UnsupportedScheme,
151 #[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 #[error("the base URL must not contain a user name or password")]
159 HasCredentials,
160 #[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 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}