Skip to main content

eggfetch_http_connect/
request.rs

1//! CONNECT request serialization and Basic auth helper.
2//!
3//! Serialization is byte-oriented and side-effect free: it has no timeout,
4//! socket, TLS, or retry behavior. Callers write the returned bytes under
5//! their own write-deadline policy.
6
7use std::fmt;
8
9use crate::error::ConnectError;
10use crate::target::ConnectTarget;
11
12/// A CONNECT request to serialize.
13///
14/// `proxy_authorization` holds a pre-encoded header value such as
15/// `Basic <base64>` (see [`basic_auth_value`]). `extra_headers` holds
16/// proxy-only headers as `(name, raw value)` pairs; values are preserved
17/// byte-for-byte where HTTP permits (including `obs-text` 0x80..=0xFF).
18/// `max_head_bytes` bounds the serialized head before any write.
19pub struct ConnectRequest<'a> {
20    /// CONNECT destination; also sources the generated `Host` value.
21    pub target: &'a ConnectTarget,
22    /// Optional pre-encoded `Proxy-Authorization` value (without the name).
23    pub proxy_authorization: Option<&'a str>,
24    /// Proxy-only headers as `(name, raw value)` pairs.
25    pub extra_headers: &'a [(String, Vec<u8>)],
26    /// Maximum serialized head size in bytes.
27    pub max_head_bytes: usize,
28}
29
30impl fmt::Debug for ConnectRequest<'_> {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        // Never render credential material: the explicit auth value and
33        // any `proxy-authorization` entry smuggled via `extra_headers`
34        // are presence-only.
35        let redacted_extra: Vec<(&str, String)> = self
36            .extra_headers
37            .iter()
38            .map(|(name, value)| {
39                if name.eq_ignore_ascii_case("proxy-authorization") {
40                    (name.as_str(), String::from("<redacted>"))
41                } else {
42                    (name.as_str(), String::from_utf8_lossy(value).into_owned())
43                }
44            })
45            .collect();
46        f.debug_struct("ConnectRequest")
47            .field("target", &self.target)
48            .field(
49                "proxy_authorization",
50                &self.proxy_authorization.map(|_| "<redacted>"),
51            )
52            .field("extra_headers", &redacted_extra)
53            .field("max_head_bytes", &self.max_head_bytes)
54            .finish()
55    }
56}
57
58/// Build a `Basic <base64(user:pass)>` proxy-auth value.
59///
60/// # Errors
61///
62/// Returns [`ConnectError::InvalidCredentials`] when the username contains
63/// `:`, or when either input contains `CR`, `LF`, `NUL`, or other control
64/// bytes. Inputs are never echoed in errors.
65pub fn basic_auth_value(username: &str, password: &str) -> Result<String, ConnectError> {
66    if username.contains(':') {
67        return Err(ConnectError::InvalidCredentials);
68    }
69    for value in [username, password] {
70        for c in value.chars() {
71            if c == '\r' || c == '\n' || c == '\0' || c.is_control() || c == '\u{7f}' {
72                return Err(ConnectError::InvalidCredentials);
73            }
74        }
75    }
76    {
77        use base64::Engine as _;
78        let credential = format!("{username}:{password}");
79        let encoded = base64::engine::general_purpose::STANDARD.encode(credential.as_bytes());
80        Ok(format!("Basic {encoded}"))
81    }
82}
83
84/// Serialize a CONNECT request head.
85///
86/// Wire shape:
87///
88/// ```text
89/// CONNECT host:port HTTP/1.1\r\n
90/// Host: host:port\r\n
91/// [Proxy-Authorization: ...\r\n]
92/// [proxy-only headers...]
93/// \r\n
94/// ```
95///
96/// # Errors
97///
98/// Returns [`ConnectError`] when a header name/value is unsafe, when a
99/// reserved header (`Host`) would override the generated authority, when
100/// two `Proxy-Authorization` values would be emitted, or when the
101/// serialized head exceeds `max_head_bytes`. No credentials or header
102/// bytes are echoed in errors.
103pub fn encode_connect_request(request: &ConnectRequest<'_>) -> Result<Vec<u8>, ConnectError> {
104    let authority = request.target.authority();
105
106    if let Some(auth) = request.proxy_authorization {
107        validate_header_value_bytes(auth.as_bytes())?;
108    }
109
110    // Count proxy-authorization occurrences deterministically: an explicit
111    // value plus any extra entry is a duplicate; two extra entries are a
112    // duplicate even without an explicit value.
113    let mut extra_auth_count = 0_usize;
114    for (name, value) in request.extra_headers {
115        validate_header_name(name)?;
116        validate_header_value_bytes(value)?;
117        if name.eq_ignore_ascii_case("proxy-authorization") {
118            extra_auth_count += 1;
119        }
120        if name.eq_ignore_ascii_case("host") {
121            return Err(ConnectError::ReservedHeader);
122        }
123    }
124    if request.proxy_authorization.is_some() && extra_auth_count > 0 {
125        return Err(ConnectError::DuplicateAuthorization);
126    }
127    if extra_auth_count > 1 {
128        return Err(ConnectError::DuplicateAuthorization);
129    }
130
131    let max = request.max_head_bytes;
132    let mut out = Vec::new();
133
134    let request_line = format!("CONNECT {authority} HTTP/1.1\r\n");
135    let host_line = format!("Host: {authority}\r\n");
136    // Bound incrementally so a hostile extra-header set cannot force an
137    // unbounded allocation before the limit check.
138    let mut len = 0_usize;
139    for chunk_len in [
140        request_line.len(),
141        host_line.len(),
142        request
143            .proxy_authorization
144            .map_or(0, |v| "Proxy-Authorization: ".len() + v.len() + 2),
145    ] {
146        len = len
147            .checked_add(chunk_len)
148            .ok_or(ConnectError::RequestHeadTooLarge {
149                len: usize::MAX,
150                max,
151            })?;
152        if len > max {
153            return Err(ConnectError::RequestHeadTooLarge { len, max });
154        }
155    }
156    for (name, value) in request.extra_headers {
157        let header_len = name.len().checked_add(2 + value.len() + 2).ok_or(
158            ConnectError::RequestHeadTooLarge {
159                len: usize::MAX,
160                max,
161            },
162        )?;
163        len = len
164            .checked_add(header_len)
165            .ok_or(ConnectError::RequestHeadTooLarge {
166                len: usize::MAX,
167                max,
168            })?;
169        if len > max {
170            return Err(ConnectError::RequestHeadTooLarge { len, max });
171        }
172    }
173    len = len
174        .checked_add(2)
175        .ok_or(ConnectError::RequestHeadTooLarge {
176            len: usize::MAX,
177            max,
178        })?;
179    if len > max {
180        return Err(ConnectError::RequestHeadTooLarge { len, max });
181    }
182
183    out.extend_from_slice(request_line.as_bytes());
184    out.extend_from_slice(host_line.as_bytes());
185    if let Some(auth) = request.proxy_authorization {
186        out.extend_from_slice(b"Proxy-Authorization: ");
187        out.extend_from_slice(auth.as_bytes());
188        out.extend_from_slice(b"\r\n");
189    }
190    for (name, value) in request.extra_headers {
191        out.extend_from_slice(name.as_bytes());
192        out.extend_from_slice(b": ");
193        out.extend_from_slice(value);
194        out.extend_from_slice(b"\r\n");
195    }
196    out.extend_from_slice(b"\r\n");
197    debug_assert_eq!(out.len(), len);
198    Ok(out)
199}
200
201/// Validate a header name as an HTTP token without echoing it.
202fn validate_header_name(name: &str) -> Result<(), ConnectError> {
203    if name.is_empty() || name.len() > 256 {
204        return Err(ConnectError::InvalidHeader);
205    }
206    for byte in name.bytes() {
207        if !is_token_byte(byte) {
208            return Err(ConnectError::InvalidHeader);
209        }
210    }
211    Ok(())
212}
213
214/// Validate raw header value bytes (allows `obs-text`, rejects framing controls).
215fn validate_header_value_bytes(value: &[u8]) -> Result<(), ConnectError> {
216    for byte in value {
217        // HT (0x09) is allowed; CR/LF, other C0 controls, and DEL would
218        // allow response splitting and are rejected.
219        if matches!(byte, 0x00..=0x08 | 0x0A..=0x1F | 0x7F) {
220            return Err(ConnectError::InvalidHeader);
221        }
222    }
223    Ok(())
224}
225
226/// HTTP `tchar` per RFC 9110 ยง5.1.
227fn is_token_byte(byte: u8) -> bool {
228    matches!(
229        byte,
230        b'!' | b'#'
231            | b'$'
232            | b'%'
233            | b'&'
234            | b'\''
235            | b'*'
236            | b'+'
237            | b'-'
238            | b'.'
239            | b'^'
240            | b'_'
241            | b'`'
242            | b'|'
243            | b'~'
244            | b'0'..=b'9'
245            | b'A'..=b'Z'
246            | b'a'..=b'z'
247    )
248}