Skip to main content

all_smi/common/
http_hosts.rs

1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use thiserror::Error;
16use url::Url;
17
18/// A syntactically invalid HTTP remote endpoint.
19#[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
39/// Split a host list on commas, trim each element, and validate every endpoint.
40///
41/// Whitespace-separated CLI values already arrive as separate vector elements,
42/// so applying comma splitting to each element supports whitespace, comma, and
43/// mixed invocations while preserving the operator's ordering and explicit
44/// scheme spelling.
45pub 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
65/// Parse one endpoint without performing DNS lookup or any network I/O.
66pub(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
114/// Return the scheme-less endpoint identifier used by remote-view tabs,
115/// connection status, and parsed device rows.
116///
117/// Callers pass values that have already gone through
118/// [`normalize_http_hosts`]. Keeping the conversion here, beside the URL
119/// parser, prevents the transport and UI layers from inventing subtly
120/// different identifiers for explicit `http://` / `https://` endpoints.
121pub(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        // NetworkClient also creates a failure status for malformed inputs.
125        // Preserve the original value in that defensive path so the error is
126        // still attributable even though normal startup validation rejects it.
127        .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}