1use std::fmt;
5use std::net::Ipv6Addr;
6use std::str::FromStr;
7
8use crate::error::CliError;
9use crate::url::LoopbackUrl;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum Scheme {
15 Http,
18 Https,
21}
22
23impl Scheme {
24 pub fn as_str(self) -> &'static str {
26 match self {
27 Self::Http => "http",
28 Self::Https => "https",
29 }
30 }
31
32 fn default_port(self) -> u16 {
34 match self {
35 Self::Http => 80,
36 Self::Https => 443,
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Hash)]
69pub struct CanonicalOrigin {
70 scheme: Scheme,
71 host: String,
72 port: Option<u16>,
73}
74
75impl CanonicalOrigin {
76 pub fn scheme(&self) -> Scheme {
78 self.scheme
79 }
80
81 pub fn host(&self) -> &str {
84 &self.host
85 }
86
87 pub fn port(&self) -> u16 {
89 self.port.unwrap_or_else(|| self.scheme.default_port())
90 }
91
92 pub fn authority(&self) -> String {
95 match self.port {
96 Some(port) => format!("{}:{port}", self.host),
97 None => self.host.clone(),
98 }
99 }
100
101 pub fn as_str(&self) -> String {
103 format!("{}://{}", self.scheme.as_str(), self.authority())
104 }
105
106 pub fn url(&self, path: &str) -> String {
109 format!("{}{path}", self.as_str())
110 }
111}
112
113impl fmt::Display for CanonicalOrigin {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.write_str(&self.as_str())
116 }
117}
118
119impl FromStr for CanonicalOrigin {
120 type Err = ParseOriginError;
121
122 fn from_str(text: &str) -> Result<Self, Self::Err> {
123 let (scheme, rest) = if let Some(rest) = text.strip_prefix("https://") {
124 (Scheme::Https, rest)
125 } else if let Some(rest) = text.strip_prefix("http://") {
126 (Scheme::Http, rest)
127 } else {
128 return Err(ParseOriginError::Scheme);
129 };
130 let authority = rest.strip_suffix('/').unwrap_or(rest);
131 if authority.contains(['/', '?', '#']) {
132 return Err(ParseOriginError::NotAnOrigin);
133 }
134 if authority.contains('@') {
135 return Err(ParseOriginError::UserInfo);
136 }
137 let (host, port_text) = if let Some(inner) = authority.strip_prefix('[') {
138 let (literal, after) = inner.split_once(']').ok_or(ParseOriginError::Host)?;
139 let canonical = literal
140 .parse::<Ipv6Addr>()
141 .is_ok_and(|addr| addr.to_string() == literal);
142 if !canonical {
143 return Err(ParseOriginError::Host);
144 }
145 let port = match after {
146 "" => None,
147 other => Some(other.strip_prefix(':').ok_or(ParseOriginError::Port)?),
148 };
149 (format!("[{literal}]"), port)
150 } else {
151 let (host, port) = match authority.split_once(':') {
152 Some((host, port)) => (host, Some(port)),
153 None => (authority, None),
154 };
155 if !is_dns_host(host) {
156 return Err(ParseOriginError::Host);
157 }
158 (host.to_owned(), port)
159 };
160 let port = match port_text {
161 None => None,
162 Some(digits) => {
163 let valid = !digits.is_empty()
164 && digits.len() <= 5
165 && digits.bytes().all(|b| b.is_ascii_digit())
166 && !digits.starts_with('0');
167 let port = digits
168 .parse::<u16>()
169 .ok()
170 .filter(|_| valid)
171 .ok_or(ParseOriginError::Port)?;
172 if port == scheme.default_port() {
173 return Err(ParseOriginError::DefaultPort);
174 }
175 Some(port)
176 }
177 };
178 Ok(Self { scheme, host, port })
179 }
180}
181
182fn is_dns_host(host: &str) -> bool {
186 !host.is_empty()
187 && host.len() <= 253
188 && host.split('.').all(|label| {
189 !label.is_empty()
190 && label.len() <= 63
191 && !label.starts_with('-')
192 && !label.ends_with('-')
193 && label
194 .bytes()
195 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
196 })
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
201#[non_exhaustive]
202pub enum ParseOriginError {
203 #[error("origin must start with https:// or http://")]
205 Scheme,
206 #[error("origin must have no path, query or fragment")]
208 NotAnOrigin,
209 #[error("origin must not contain user information")]
211 UserInfo,
212 #[error("origin host must be a lowercase name or address (ipv6 in brackets, rfc 5952 form)")]
215 Host,
216 #[error("origin port must be a number from 1 to 65535")]
218 Port,
219 #[error("origin must omit the scheme's default port")]
221 DefaultPort,
222}
223
224#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct GateTarget {
258 origin: CanonicalOrigin,
259 connect: LoopbackUrl,
260}
261
262impl GateTarget {
263 pub fn new(origin: CanonicalOrigin, connect: Option<ConnectAddress>) -> Result<Self, CliError> {
272 let connect = match connect {
273 Some(address) => address.0,
274 None => match origin.scheme() {
275 Scheme::Https => {
276 return Err(CliError::Usage(format!(
277 "{origin} is an https:// origin and this client has no TLS transport yet: \
278 the remote transport arrives with the public origin. Reach the gate on \
279 this machine with --connect <host:port>"
280 )))
281 }
282 Scheme::Http => format!("http://{}:{}", origin.host(), origin.port())
283 .parse::<LoopbackUrl>()
284 .map_err(|_| {
285 CliError::Usage(format!(
286 "{origin} is not a loopback address; pass --connect <host:port> with \
287 a loopback address to reach the gate"
288 ))
289 })?,
290 },
291 };
292 Ok(Self { origin, connect })
293 }
294
295 pub fn origin(&self) -> &CanonicalOrigin {
297 &self.origin
298 }
299
300 pub fn connect(&self) -> &LoopbackUrl {
302 &self.connect
303 }
304}
305
306#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct ConnectAddress(LoopbackUrl);
324
325impl ConnectAddress {
326 pub fn authority(&self) -> String {
328 self.0.authority()
329 }
330}
331
332impl fmt::Display for ConnectAddress {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 f.write_str(&self.0.authority())
335 }
336}
337
338impl FromStr for ConnectAddress {
339 type Err = ParseConnectError;
340
341 fn from_str(text: &str) -> Result<Self, Self::Err> {
342 if text.contains('/') {
343 return Err(ParseConnectError);
344 }
345 let url: LoopbackUrl = format!("http://{text}")
346 .parse()
347 .map_err(|_| ParseConnectError)?;
348 if url.authority() != text {
350 return Err(ParseConnectError);
351 }
352 Ok(Self(url))
353 }
354}
355
356#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
358#[error(
359 "connect address must be <host>:<port> with a host in 127.0.0.0/8 (such as 127.0.0.1), [::1] or localhost"
360)]
361#[non_exhaustive]
362pub struct ParseConnectError;
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 #[test]
369 fn origins_keep_one_spelling() {
370 for (text, canonical, authority) in [
371 ("https://a.example", "https://a.example", "a.example"),
372 ("https://a.example/", "https://a.example", "a.example"),
373 (
374 "https://a.example:8443",
375 "https://a.example:8443",
376 "a.example:8443",
377 ),
378 (
379 "http://127.0.0.1:7461",
380 "http://127.0.0.1:7461",
381 "127.0.0.1:7461",
382 ),
383 ("https://[::1]:9", "https://[::1]:9", "[::1]:9"),
384 ] {
385 let origin: CanonicalOrigin = text.parse().expect(text);
386 assert_eq!(origin.as_str(), canonical, "{text}");
387 assert_eq!(origin.authority(), authority, "{text}");
388 }
389 for bad in [
390 "ftp://a.example",
391 "https://A.example",
392 "https://a.example:443",
393 "http://a.example:80",
394 "https://a.example:0",
395 "https://a.example:08443",
396 "https://a.example/x",
397 "https://a.example?x",
398 "https://u@a.example",
399 "https://[0:0::1]",
400 "https://a..example",
401 "https://",
402 ] {
403 assert!(bad.parse::<CanonicalOrigin>().is_err(), "{bad}");
404 }
405 }
406
407 #[test]
408 fn https_without_connect_is_refused_and_http_needs_loopback() {
409 let https: CanonicalOrigin = "https://a.example".parse().expect("origin");
410 let err = GateTarget::new(https, None).expect_err("refused");
411 assert!(
412 err.to_string()
413 .contains("remote transport arrives with the public origin"),
414 "{err}"
415 );
416 let far: CanonicalOrigin = "http://a.example:7461".parse().expect("origin");
417 assert!(GateTarget::new(far, None).is_err());
418 let near: CanonicalOrigin = "http://localhost:7461".parse().expect("origin");
419 let target = GateTarget::new(near, None).expect("loopback");
420 assert_eq!(target.connect().connect_host(), "127.0.0.1");
421 }
422}