all_smi/common/
http_hosts.rs1use thiserror::Error;
16use url::Url;
17
18#[derive(Debug, Clone, PartialEq, Eq, Error)]
20#[error("invalid remote host `{value}`: {reason}")]
21pub struct HttpHostError {
22 value: String,
23 reason: String,
24}
25
26impl HttpHostError {
27 fn new(value: &str, reason: impl Into<String>) -> Self {
28 Self {
29 value: if value.is_empty() {
30 "<empty>".to_string()
31 } else {
32 value.to_string()
33 },
34 reason: reason.into(),
35 }
36 }
37}
38
39pub fn normalize_http_hosts(hosts: &[String]) -> Result<Vec<String>, HttpHostError> {
46 let mut normalized = Vec::new();
47
48 for raw in hosts {
49 for element in raw.split(',') {
50 let host = element.trim();
51 if host.is_empty() {
52 return Err(HttpHostError::new(
53 raw.trim(),
54 "host list contains an empty entry",
55 ));
56 }
57 parse_http_host_url(host)?;
58 normalized.push(host.to_string());
59 }
60 }
61
62 Ok(normalized)
63}
64
65pub(crate) fn parse_http_host_url(host: &str) -> Result<Url, HttpHostError> {
67 if let Some((prefix, _)) = host.split_once(':')
68 && matches!(prefix.to_ascii_lowercase().as_str(), "http" | "https")
69 && !host.contains("://")
70 {
71 return Err(HttpHostError::new(
72 host,
73 "malformed URL: HTTP and HTTPS schemes must be followed by `://`",
74 ));
75 }
76
77 let candidate = if let Some((scheme, remainder)) = host.split_once("://") {
78 if !matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https") {
79 return Err(HttpHostError::new(
80 host,
81 format!("unsupported scheme `{scheme}`; expected http or https"),
82 ));
83 }
84 if remainder.is_empty() {
85 return Err(HttpHostError::new(host, "missing host"));
86 }
87 host.to_string()
88 } else {
89 format!("http://{host}")
90 };
91
92 let url = Url::parse(&candidate)
93 .map_err(|error| HttpHostError::new(host, format!("malformed URL: {error}")))?;
94
95 if !matches!(url.scheme(), "http" | "https") {
96 return Err(HttpHostError::new(
97 host,
98 format!(
99 "unsupported scheme `{}`; expected http or https",
100 url.scheme()
101 ),
102 ));
103 }
104 if url.host_str().is_none_or(str::is_empty) {
105 return Err(HttpHostError::new(host, "missing host"));
106 }
107 if url.port() == Some(0) {
108 return Err(HttpHostError::new(host, "port must be between 1 and 65535"));
109 }
110
111 Ok(url)
112}
113
114pub(crate) fn http_host_identifier(host: &str) -> String {
122 parse_http_host_url(host)
123 .map(|url| url[url::Position::BeforeHost..url::Position::AfterPort].to_string())
124 .unwrap_or_else(|_| host.to_string())
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 fn strings(values: &[&str]) -> Vec<String> {
135 values.iter().map(|value| (*value).to_string()).collect()
136 }
137
138 #[test]
139 fn accepts_whitespace_comma_and_mixed_lists_in_order() {
140 assert_eq!(
141 normalize_http_hosts(&strings(&["host-a:9090", "host-b:9090"])).unwrap(),
142 strings(&["host-a:9090", "host-b:9090"])
143 );
144 assert_eq!(
145 normalize_http_hosts(&strings(&["host-a:9090,host-b:9090"])).unwrap(),
146 strings(&["host-a:9090", "host-b:9090"])
147 );
148 assert_eq!(
149 normalize_http_hosts(&strings(&[
150 " host-a:9090, https://host-b:9443 ",
151 "http://[2001:db8::1]:9090"
152 ]))
153 .unwrap(),
154 strings(&[
155 "host-a:9090",
156 "https://host-b:9443",
157 "http://[2001:db8::1]:9090"
158 ])
159 );
160 }
161
162 #[test]
163 fn rejects_empty_elements() {
164 for input in [
165 "",
166 ",host-a:9090",
167 "host-a:9090,,host-b:9090",
168 "host-a:9090,",
169 ] {
170 let error = normalize_http_hosts(&strings(&[input])).unwrap_err();
171 assert!(error.to_string().contains("empty entry"), "{error}");
172 }
173 }
174
175 #[test]
176 fn rejects_invalid_port_and_names_the_value() {
177 let error = normalize_http_hosts(&strings(&["host-a:9090,host-b:not-a-port"]))
178 .unwrap_err()
179 .to_string();
180 assert!(error.contains("host-b:not-a-port"), "{error}");
181 assert!(error.contains("invalid port"), "{error}");
182 }
183
184 #[test]
185 fn rejects_unsupported_scheme_missing_host_and_malformed_url() {
186 let unsupported = normalize_http_hosts(&strings(&["ftp://host-a:9090"]))
187 .unwrap_err()
188 .to_string();
189 assert!(unsupported.contains("ftp://host-a:9090"), "{unsupported}");
190 assert!(unsupported.contains("unsupported scheme"), "{unsupported}");
191
192 let missing = normalize_http_hosts(&strings(&["http://"]))
193 .unwrap_err()
194 .to_string();
195 assert!(missing.contains("http://"), "{missing}");
196 assert!(missing.contains("missing host"), "{missing}");
197
198 let malformed = normalize_http_hosts(&strings(&["http://[2001:db8::1"]))
199 .unwrap_err()
200 .to_string();
201 assert!(malformed.contains("http://[2001:db8::1"), "{malformed}");
202 assert!(malformed.contains("malformed URL"), "{malformed}");
203
204 let missing_slashes = normalize_http_hosts(&strings(&["https:/host-a:9090"]))
205 .unwrap_err()
206 .to_string();
207 assert!(
208 missing_slashes.contains("https:/host-a:9090"),
209 "{missing_slashes}"
210 );
211 assert!(
212 missing_slashes.contains("must be followed by `://`"),
213 "{missing_slashes}"
214 );
215 }
216
217 #[test]
218 fn preserves_https_and_accepts_unreachable_or_bracketed_ipv6_hosts() {
219 let hosts = normalize_http_hosts(&strings(&[
220 "https://does-not-exist.invalid:9443",
221 "[2001:db8::2]:9090",
222 ]))
223 .unwrap();
224 assert_eq!(
225 hosts,
226 strings(&["https://does-not-exist.invalid:9443", "[2001:db8::2]:9090"])
227 );
228 assert_eq!(parse_http_host_url(&hosts[0]).unwrap().scheme(), "https");
229 }
230
231 #[test]
232 fn endpoint_identifier_is_stable_across_schemes_and_paths() {
233 assert_eq!(http_host_identifier("http://node-a:9090"), "node-a:9090");
234 assert_eq!(
235 http_host_identifier("https://node-a:9090/ignored/path"),
236 "node-a:9090"
237 );
238 assert_eq!(http_host_identifier("node-a:9090"), "node-a:9090");
239 assert_eq!(
240 http_host_identifier("http://[2001:db8::1]:9090"),
241 "[2001:db8::1]:9090"
242 );
243 }
244}