eggfetch_http_connect/target.rs
1//! CONNECT authority ownership.
2//!
3//! Centralizes `host:port` formatting so every consumer does not
4//! reimplement IPv6 bracketing.
5
6use crate::error::ConnectError;
7
8/// CONNECT destination in authority form.
9///
10/// Holds a validated host and port. [`ConnectTarget::authority`] renders
11/// the exact `host:port` string used for both the `CONNECT` request-target
12/// and the `Host` header so they cannot diverge.
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
14pub struct ConnectTarget {
15 host: String,
16 port: u16,
17}
18
19impl ConnectTarget {
20 /// Create a CONNECT target.
21 ///
22 /// # Errors
23 ///
24 /// Returns [`ConnectError::InvalidTarget`] when the host is empty,
25 /// contains request-line control bytes (`CR`, `LF`, other C0 controls,
26 /// `DEL`, or space), request-target delimiters (`/`, `?`, `#`, `@`),
27 /// or has malformed IPv6 brackets. Bracketed
28 /// (`[::1]`) and unbracketed (`::1`) IPv6 literals are both accepted
29 /// and normalize to the same bracketed authority. No path, query, or
30 /// body semantics exist in this type.
31 pub fn new(host: impl Into<String>, port: u16) -> Result<Self, ConnectError> {
32 let host = host.into();
33 if port == 0 {
34 return Err(ConnectError::InvalidTarget);
35 }
36 validate_host(&host)?;
37 Ok(Self { host, port })
38 }
39
40 /// Return the raw host as supplied (brackets preserved when given).
41 #[must_use]
42 pub fn host(&self) -> &str {
43 &self.host
44 }
45
46 /// Return the port.
47 #[must_use]
48 pub fn port(&self) -> u16 {
49 self.port
50 }
51
52 /// Render the authority-form `host:port` target.
53 ///
54 /// Domains render as `example.com:443`, IPv4 as `127.0.0.1:443`,
55 /// and IPv6 bracketed as `[::1]:443`. Pre-bracketed and unbracketed
56 /// IPv6 normalize to the same bracketed form.
57 #[must_use]
58 pub fn authority(&self) -> String {
59 authority_form(&self.host, self.port)
60 }
61}
62
63/// Render authority without re-validating (already validated at construction).
64fn authority_form(host: &str, port: u16) -> String {
65 if let Some(inner) = strip_brackets(host) {
66 format!("[{inner}]:{port}")
67 } else if host.contains(':') {
68 format!("[{host}]:{port}")
69 } else {
70 format!("{host}:{port}")
71 }
72}
73
74/// Return the inner literal when `host` is fully bracketed.
75fn strip_brackets(host: &str) -> Option<&str> {
76 if host.starts_with('[') && host.ends_with(']') && host.len() >= 2 {
77 Some(&host[1..host.len() - 1])
78 } else {
79 None
80 }
81}
82
83/// Validate a CONNECT host without echoing it in errors.
84fn validate_host(host: &str) -> Result<(), ConnectError> {
85 if host.is_empty() {
86 return Err(ConnectError::InvalidTarget);
87 }
88 // Bracket shape: brackets may only wrap the whole host.
89 if host.contains('[') || host.contains(']') {
90 let Some(inner) = strip_brackets(host) else {
91 return Err(ConnectError::InvalidTarget);
92 };
93 if inner.is_empty() || inner.contains('[') || inner.contains(']') {
94 return Err(ConnectError::InvalidTarget);
95 }
96 validate_host_inner(inner)?;
97 return Ok(());
98 }
99 validate_host_inner(host)
100}
101
102/// Validate the unbracketed host body.
103fn validate_host_inner(host: &str) -> Result<(), ConnectError> {
104 if host.is_empty() {
105 return Err(ConnectError::InvalidTarget);
106 }
107 for c in host.chars() {
108 // Reject request-line control bytes: C0, DEL, and space. This
109 // blocks CR/LF injection and other control smuggling while
110 // leaving ordinary domain/IPv4/IPv6 text untouched.
111 if c == '\r' || c == '\n' || c.is_control() || c == ' ' || c == '\u{7f}' {
112 return Err(ConnectError::InvalidTarget);
113 }
114 // Reject request-target delimiters that would let a `host`
115 // value smuggle a path/query/fragment (`evil.com/path:443`),
116 // userinfo (`user@host`), or extra authority sections into the
117 // CONNECT request line. `:` is allowed here only for the
118 // IPv6-literal path, which is validated separately above.
119 if matches!(c, '/' | '?' | '#' | '@') {
120 return Err(ConnectError::InvalidTarget);
121 }
122 }
123 // A `:` in an unbracketed host is only valid as an IPv6 literal;
124 // otherwise `foo:bar` would render as `[foo:bar]:443` and smuggle an
125 // extra authority section. Require valid IPv6 shape here (allowing an
126 // optional `%zone` suffix).
127 if host.contains(':') {
128 let candidate = host.split_once('%').map_or(host, |(base, _)| base);
129 if candidate.parse::<std::net::Ipv6Addr>().is_err() {
130 return Err(ConnectError::InvalidTarget);
131 }
132 }
133 Ok(())
134}