Skip to main content

open_net/api/ws/
handshake_diagnostic.rs

1use crate::error::NetError;
2use crate::module::transport::failure::{ConnectStage, ConnectionFailure};
3use http::header::{HeaderName, HeaderValue, CONTENT_TYPE, RETRY_AFTER};
4use http::HeaderMap;
5use serde::de::{DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor};
6use std::fmt;
7
8const MAX_ALLOWLIST_CODES: usize = 32;
9const MAX_CODE_BYTES: usize = 64;
10const MAX_BODY_INPUT_BYTES: usize = 16 * 1024;
11const MAX_HEADER_VALUE_BYTES: usize = 128;
12
13/// Optional handshake-diagnostic configuration. By default, only safe response
14/// headers and a stable error classification are retained; the response body is
15/// not retained.
16///
17/// A body summary contains only a code that exactly matches a public error code
18/// configured by the caller; no error message or original text fragment is
19/// retained. `Debug` displays only the number of configured error codes.
20#[derive(Clone, Default)]
21pub struct HandshakeDiagnosticOptions {
22    /// Top-level JSON `code` values that may be exposed; an empty list disables body-summary capture.
23    /// Up to 32 entries are accepted (duplicates count), and each entry contains 1–64 ASCII uppercase letters, digits, or underscores.
24    pub public_json_codes: Vec<String>,
25}
26
27impl HandshakeDiagnosticOptions {
28    /// Checks the public code list without copying or modifying its entries.
29    ///
30    /// At most 32 entries are accepted, including duplicates. Each must contain
31    /// 1–64 ASCII uppercase letters, digits or underscores.
32    ///
33    /// Capture requires a complete JSON object within 16 KiB, a unique
34    /// `Content-Length` matching the bytes already available, a recognized JSON
35    /// content type and no transfer encoding or compression. Only the unique
36    /// top-level `code` string is considered; comparison is case sensitive.
37    /// This does not request more body bytes or extend the handshake deadline.
38    pub fn validate(&self) -> crate::Result<()> {
39        if self.public_json_codes.len() > MAX_ALLOWLIST_CODES {
40            return Err(NetError::config(
41                "diagnostics.public_json_codes",
42                "must contain at most 32 public codes, including duplicates",
43            ));
44        }
45        for code in &self.public_json_codes {
46            if code.is_empty()
47                || code.len() > MAX_CODE_BYTES
48                || !code
49                    .bytes()
50                    .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
51            {
52                return Err(NetError::config(
53                    "diagnostics.public_json_codes",
54                    "each public code must contain 1–64 ASCII uppercase letters, digits or underscores",
55                ));
56            }
57        }
58        Ok(())
59    }
60}
61
62impl fmt::Debug for HandshakeDiagnosticOptions {
63    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64        formatter
65            .debug_struct("HandshakeDiagnosticOptions")
66            .field("public_json_code_count", &self.public_json_codes.len())
67            .finish()
68    }
69}
70
71/// Stable handshake-diagnostic classification that supplements the original
72/// failure without changing its retryability, stage, timeout, or HTTP status.
73#[non_exhaustive]
74#[derive(Clone, Copy, Debug, Eq, PartialEq)]
75pub enum HandshakeDiagnosticKind {
76    /// The HTTP response rejected a WebSocket handshake or proxy handshake.
77    HttpRejected,
78    /// An operating-system I/O error; only its category is retained, not the
79    /// original text, which may contain sensitive information.
80    Io(
81        /// The I/O error category returned by the operating system.
82        std::io::ErrorKind,
83    ),
84    /// TLS certificate verification failed.
85    TlsCertificate,
86    /// TLS negotiation or protocol failed except certificate verification.
87    TlsProtocol,
88    /// Invalid HTTP or WebSocket protocol data.
89    Protocol,
90    /// The original deadline for the current handshake attempt has been reached.
91    Timeout,
92    /// Domain name resolution failed and there is no more precise classification that can be safely preserved.
93    Dns,
94    /// Request construction, handshake provider, configuration, or local event delivery failed.
95    Local,
96    /// A more precise and safe classification of the error cannot be given.
97    Other,
98}
99
100/// Result of safe response-body summary capture, or the specific reason no summary was collected.
101#[non_exhaustive]
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum HandshakeBodyCaptureState {
104    /// The configuration requires that the body be omitted, for example, the allowed list of public error codes is empty.
105    Omitted,
106    /// No body data is available, or allocating memory for the safe summary failed.
107    Unavailable,
108    /// Unable to verify body length and integrity based on currently available bytes.
109    Incomplete,
110    /// HTTP body delimitation, content type, or JSON representation is not supported or is ambiguous.
111    Unsupported,
112    /// The available body or declared length exceeds the 16 KiB input limit.
113    TooLarge,
114    /// The JSON is valid, but a unique top-level string error code that matches the allowed list was not found.
115    Unrecognized,
116    /// A summary was collected containing only a code allowed by configuration.
117    Captured,
118}
119
120/// Size-bounded diagnostic information attached to one failed handshake attempt.
121///
122/// Only normalized `content-type` and numeric `retry-after` values are retained.
123/// The body summary is generated from configured public codes and never copies
124/// arbitrary response messages. Total retained string data is below 2 KiB, each
125/// response header is below 128 bytes, and the summary is below 512 bytes;
126/// `Debug` never prints string contents.
127///
128/// This value owns no timer and is not stored in a global cache. Its lifecycle is
129/// determined by the holder.
130#[derive(Clone)]
131pub struct HandshakeDiagnostic {
132    /// Safe diagnostic classification that supplements the original failure.
133    kind: HandshakeDiagnosticKind,
134    /// Security response headers retained and normalized from the fixed allowed list.
135    headers: HeaderMap,
136    /// `code=PUBLIC_CODE` when capture succeeds; `None` otherwise.
137    body_summary: Option<String>,
138    /// Body-summary capture result or omission reason.
139    body_capture_state: HandshakeBodyCaptureState,
140}
141
142impl HandshakeDiagnostic {
143    pub(crate) fn new(kind: HandshakeDiagnosticKind) -> Self {
144        Self {
145            kind,
146            headers: HeaderMap::new(),
147            body_summary: None,
148            body_capture_state: HandshakeBodyCaptureState::Unavailable,
149        }
150    }
151
152    pub(crate) fn http<'a>(
153        options: &HandshakeDiagnosticOptions,
154        headers: impl Iterator<Item = (&'a str, &'a [u8])>,
155        body: Option<&[u8]>,
156    ) -> Self {
157        let metadata = HttpMetadata::read(headers);
158        let mut diagnostic = Self::new(HandshakeDiagnosticKind::HttpRejected);
159        if let Some(content_type) = metadata.json_content_type() {
160            diagnostic.retain_header(CONTENT_TYPE, content_type);
161        }
162        if let Some(seconds) = metadata.retry_after.unique().and_then(parse_decimal) {
163            // u64 has at most 20 decimal digits; write without copying any
164            // untrusted input or requesting an unbounded temporary allocation.
165            let mut normalized = String::new();
166            if normalized.try_reserve_exact(20).is_ok() {
167                use std::fmt::Write;
168                if write!(&mut normalized, "{seconds}").is_ok() {
169                    diagnostic.retain_header(RETRY_AFTER, &normalized);
170                } else {
171                    log_capture_allocation_failure();
172                }
173            } else {
174                log_capture_allocation_failure();
175            }
176        }
177        let (state, summary) = capture_body(options, &metadata, body);
178        diagnostic.body_capture_state = state;
179        diagnostic.body_summary = summary;
180        diagnostic
181    }
182
183    pub(crate) fn from_failure(failure: ConnectionFailure) -> Self {
184        use HandshakeDiagnosticKind as Kind;
185        let kind = if failure.http_status().is_some() {
186            Kind::HttpRejected
187        } else if failure.error().kind() == crate::error::ErrorKind::TimedOut {
188            Kind::Timeout
189        } else {
190            match failure.stage() {
191                ConnectStage::Provider
192                | ConnectStage::RequestBuild
193                | ConnectStage::EventDelivery => Kind::Local,
194                ConnectStage::Dns => Kind::Dns,
195                ConnectStage::Tls | ConnectStage::ProxyTls => Kind::TlsProtocol,
196                _ if failure.error().kind() == crate::error::ErrorKind::Tls => Kind::TlsProtocol,
197                _ if failure.error().kind() == crate::error::ErrorKind::Protocol => Kind::Protocol,
198                _ => Kind::Other,
199            }
200        };
201        Self::new(kind)
202    }
203
204    fn retain_header(&mut self, name: HeaderName, value: &str) {
205        let Some(value) = try_owned(value) else {
206            return;
207        };
208        let Ok(value) = HeaderValue::from_maybe_shared(bytes::Bytes::from(value)) else {
209            return;
210        };
211        if self.headers.try_insert(name, value).is_err() {
212            log_capture_allocation_failure();
213        }
214    }
215
216    /// A safe supplement to the existing failure classification.
217    pub fn kind(&self) -> HandshakeDiagnosticKind {
218        self.kind
219    }
220    /// Normalized fixed-allowlist values; never credentials or arbitrary headers.
221    pub fn headers(&self) -> &HeaderMap {
222        &self.headers
223    }
224    /// `code=PUBLIC_CODE` when a unique configured code was captured.
225    pub fn body_summary(&self) -> Option<&str> {
226        self.body_summary.as_deref()
227    }
228    /// The result of the body capture policy, including reasons for omission.
229    pub fn body_capture_state(&self) -> HandshakeBodyCaptureState {
230        self.body_capture_state
231    }
232}
233
234fn try_owned(value: &str) -> Option<String> {
235    let mut owned = String::new();
236    if owned.try_reserve_exact(value.len()).is_err() {
237        log_capture_allocation_failure();
238        return None;
239    }
240    owned.push_str(value);
241    Some(owned)
242}
243
244fn log_capture_allocation_failure() {
245    crate::log_e!(crate::common::log::log_def::LogType::WSC; "handshake_diagnostic", "error", "safe_capture_allocation_failed");
246}
247
248/// Borrowed value and duplicate-detection state for one response header; used
249/// to reject ambiguous diagnostic input.
250#[derive(Default)]
251struct HeaderField<'a> {
252    /// The raw response header value when first encountered; `None` if not present.
253    value: Option<&'a [u8]>,
254    /// Whether the response header with the same name appears again; when it is `true`, it cannot be used as a unique value.
255    duplicate: bool,
256}
257
258impl<'a> HeaderField<'a> {
259    fn insert(&mut self, value: &'a [u8]) {
260        if self.value.is_some() {
261            self.duplicate = true;
262        } else {
263            self.value = Some(value);
264        }
265    }
266
267    fn unique(&self) -> Option<&'a [u8]> {
268        if self.duplicate {
269            None
270        } else {
271            self.value
272        }
273    }
274}
275
276/// Diagnostic metadata extracted from a handshake HTTP response. It borrows
277/// header values and never retains an arbitrary response body.
278#[derive(Default)]
279struct HttpMetadata<'a> {
280    /// Content type used to determine whether JSON body capture is supported.
281    content_type: HeaderField<'a>,
282    /// The declared body length, used to verify that the current bytes constitute the complete response body.
283    content_length: HeaderField<'a>,
284    /// Content encoding; only a missing value or a unique `identity` value
285    /// permits body-summary capture.
286    content_encoding: HeaderField<'a>,
287    /// Retry-after value; only a unique value that parses as decimal seconds is
288    /// retained.
289    retry_after: HeaderField<'a>,
290    /// Whether `Transfer-Encoding` appears; when present, body-summary capture
291    /// is disabled.
292    transfer_encoding: bool,
293}
294
295impl<'a> HttpMetadata<'a> {
296    fn read(headers: impl Iterator<Item = (&'a str, &'a [u8])>) -> Self {
297        let mut metadata = Self::default();
298        for (name, value) in headers {
299            if name.eq_ignore_ascii_case("content-type") {
300                metadata.content_type.insert(value);
301            } else if name.eq_ignore_ascii_case("content-length") {
302                metadata.content_length.insert(value);
303            } else if name.eq_ignore_ascii_case("content-encoding") {
304                metadata.content_encoding.insert(value);
305            } else if name.eq_ignore_ascii_case("retry-after") {
306                metadata.retry_after.insert(value);
307            } else if name.eq_ignore_ascii_case("transfer-encoding") {
308                metadata.transfer_encoding = true;
309            }
310        }
311        metadata
312    }
313
314    fn json_content_type(&self) -> Option<&'static str> {
315        let value = self.content_type.unique()?;
316        if value.len() > MAX_HEADER_VALUE_BYTES {
317            return None;
318        }
319        let media_type = trim_ows(value.split(|byte| *byte == b';').next()?);
320        if media_type.eq_ignore_ascii_case(b"application/json") {
321            Some("application/json")
322        } else if media_type.eq_ignore_ascii_case(b"application/problem+json") {
323            Some("application/problem+json")
324        } else {
325            None
326        }
327    }
328
329    fn has_supported_encoding(&self) -> bool {
330        if self.transfer_encoding || self.content_encoding.duplicate {
331            return false;
332        }
333        match self.content_encoding.value {
334            None => true,
335            Some(value) => {
336                value.len() <= MAX_HEADER_VALUE_BYTES
337                    && trim_ows(value).eq_ignore_ascii_case(b"identity")
338            }
339        }
340    }
341}
342
343fn trim_ows(mut value: &[u8]) -> &[u8] {
344    while let Some((byte, rest)) = value.split_first() {
345        if matches!(byte, b' ' | b'\t') {
346            value = rest;
347        } else {
348            break;
349        }
350    }
351    while let Some((byte, rest)) = value.split_last() {
352        if matches!(byte, b' ' | b'\t') {
353            value = rest;
354        } else {
355            break;
356        }
357    }
358    value
359}
360
361fn parse_decimal(value: &[u8]) -> Option<u64> {
362    if value.len() > MAX_HEADER_VALUE_BYTES {
363        return None;
364    }
365    let value = trim_ows(value);
366    if value.is_empty() || !value.iter().all(u8::is_ascii_digit) {
367        return None;
368    }
369    std::str::from_utf8(value).ok()?.parse().ok()
370}
371
372fn capture_body(
373    options: &HandshakeDiagnosticOptions,
374    metadata: &HttpMetadata<'_>,
375    body: Option<&[u8]>,
376) -> (HandshakeBodyCaptureState, Option<String>) {
377    use HandshakeBodyCaptureState as State;
378    if options.public_json_codes.is_empty() {
379        return (State::Omitted, None);
380    }
381    let Some(body) = body.filter(|body| !body.is_empty()) else {
382        return (State::Unavailable, None);
383    };
384    if body.len() > MAX_BODY_INPUT_BYTES {
385        return (State::TooLarge, None);
386    }
387    if metadata.json_content_type().is_none()
388        || !metadata.has_supported_encoding()
389        || metadata.content_length.duplicate
390    {
391        return (State::Unsupported, None);
392    }
393    let Some(length) = metadata.content_length.unique() else {
394        return (State::Incomplete, None);
395    };
396    let Some(length) = parse_decimal(length) else {
397        return (State::Unsupported, None);
398    };
399    if length > MAX_BODY_INPUT_BYTES as u64 {
400        return (State::TooLarge, None);
401    }
402    if length != body.len() as u64 {
403        return (State::Incomplete, None);
404    }
405    if std::str::from_utf8(body).is_err() {
406        return (State::Unsupported, None);
407    }
408    let mut deserializer = serde_json::Deserializer::from_slice(body);
409    let selected = CodeObjectSeed {
410        codes: &options.public_json_codes,
411    }
412    .deserialize(&mut deserializer);
413    let Ok(selected) = selected else {
414        return (State::Unsupported, None);
415    };
416    if deserializer.end().is_err() {
417        return (State::Unsupported, None);
418    }
419    let Some(code) = selected.and_then(|index| options.public_json_codes.get(index)) else {
420        return (State::Unrecognized, None);
421    };
422    let mut summary = String::new();
423    if summary
424        .try_reserve_exact("code=".len() + code.len())
425        .is_err()
426    {
427        log_capture_allocation_failure();
428        return (State::Unavailable, None);
429    }
430    summary.push_str("code=");
431    summary.push_str(code);
432    (State::Captured, Some(summary))
433}
434
435/// Parses the top-level JSON object and looks for unique public error codes, without saving arbitrary keys or strings.
436/// Unknown values are consumed by serde's ignored-value parser without
437/// constructing objects; the total input size is bounded before parsing begins.
438struct CodeObjectSeed<'a> {
439    /// An allowed list of public error codes for exact matching of the top-level `code` value.
440    codes: &'a [String],
441}
442
443impl<'de> DeserializeSeed<'de> for CodeObjectSeed<'_> {
444    type Value = Option<usize>;
445
446    fn deserialize<D: serde::Deserializer<'de>>(
447        self,
448        deserializer: D,
449    ) -> Result<Self::Value, D::Error> {
450        deserializer.deserialize_map(self)
451    }
452}
453
454impl<'de> Visitor<'de> for CodeObjectSeed<'_> {
455    type Value = Option<usize>;
456
457    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
458        formatter.write_str("a JSON object with at most one top-level code")
459    }
460
461    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
462        let mut seen_code = false;
463        let mut selected = None;
464        while let Some(is_code) = map.next_key_seed(CodeKeySeed)? {
465            if is_code {
466                if seen_code {
467                    return Err(serde::de::Error::custom("duplicate diagnostic code"));
468                }
469                seen_code = true;
470                selected = map.next_value_seed(CodeValueSeed { codes: self.codes })?;
471            } else {
472                map.next_value::<IgnoredAny>()?;
473            }
474        }
475        Ok(selected)
476    }
477}
478
479/// Recognizes whether a JSON object key is exactly `code`, without allocating or retaining the key string.
480struct CodeKeySeed;
481
482impl<'de> DeserializeSeed<'de> for CodeKeySeed {
483    type Value = bool;
484
485    fn deserialize<D: serde::Deserializer<'de>>(self, deserializer: D) -> Result<bool, D::Error> {
486        deserializer.deserialize_str(self)
487    }
488}
489
490impl Visitor<'_> for CodeKeySeed {
491    type Value = bool;
492
493    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
494        formatter.write_str("a JSON object key")
495    }
496
497    fn visit_str<E: serde::de::Error>(self, key: &str) -> Result<bool, E> {
498        Ok(key == "code")
499    }
500}
501
502/// Maps JSON string error codes to allowed-list indexes; consumed non-string
503/// values are treated as mismatches.
504struct CodeValueSeed<'a> {
505    /// Allowed list of public error codes for exact case comparison.
506    codes: &'a [String],
507}
508
509impl<'de> DeserializeSeed<'de> for CodeValueSeed<'_> {
510    type Value = Option<usize>;
511
512    fn deserialize<D: serde::Deserializer<'de>>(
513        self,
514        deserializer: D,
515    ) -> Result<Self::Value, D::Error> {
516        deserializer.deserialize_any(self)
517    }
518}
519
520impl<'de> Visitor<'de> for CodeValueSeed<'_> {
521    type Value = Option<usize>;
522
523    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
524        formatter.write_str("a public diagnostic code")
525    }
526
527    fn visit_str<E: serde::de::Error>(self, code: &str) -> Result<Self::Value, E> {
528        Ok(self.codes.iter().position(|allowed| allowed == code))
529    }
530
531    fn visit_bool<E: serde::de::Error>(self, _value: bool) -> Result<Self::Value, E> {
532        Ok(None)
533    }
534    fn visit_i64<E: serde::de::Error>(self, _value: i64) -> Result<Self::Value, E> {
535        Ok(None)
536    }
537    fn visit_u64<E: serde::de::Error>(self, _value: u64) -> Result<Self::Value, E> {
538        Ok(None)
539    }
540    fn visit_f64<E: serde::de::Error>(self, _value: f64) -> Result<Self::Value, E> {
541        Ok(None)
542    }
543    fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
544        Ok(None)
545    }
546
547    fn visit_seq<S: SeqAccess<'de>>(self, mut sequence: S) -> Result<Self::Value, S::Error> {
548        while sequence.next_element::<IgnoredAny>()?.is_some() {}
549        Ok(None)
550    }
551
552    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
553        while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
554        Ok(None)
555    }
556}
557
558impl fmt::Debug for HandshakeDiagnostic {
559    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
560        formatter
561            .debug_struct("HandshakeDiagnostic")
562            .field("kind", &self.kind)
563            .field("header_count", &self.headers.len())
564            .field(
565                "body_summary_bytes",
566                &self.body_summary.as_ref().map(String::len),
567            )
568            .field("body_capture_state", &self.body_capture_state)
569            .finish()
570    }
571}
572
573#[cfg(test)]
574#[path = "handshake_diagnostic_tests.rs"]
575mod tests;
576
577#[cfg(test)]
578#[path = "handshake_diagnostic_api_tests.rs"]
579mod api_tests;