Skip to main content

web_transport_proto/
connect.rs

1use std::{fmt, str::FromStr, sync::Arc};
2
3use bytes::{Buf, BufMut, BytesMut};
4use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
5use url::{Position, Url};
6
7use super::{qpack, Frame, VarInt, MAX_FRAME_SIZE};
8
9use thiserror::Error;
10
11// RFC 9114 section 4.2.2: each decoded field costs name + value + 32 bytes.
12pub(crate) const MAX_FIELD_SECTION_SIZE: u64 = 16 * 1024;
13
14// Errors that can occur during the connect request.
15#[derive(Error, Debug, Clone)]
16#[non_exhaustive]
17pub enum ConnectError {
18    #[error("unexpected end of input")]
19    UnexpectedEnd,
20
21    #[error("qpack error")]
22    QpackError(#[from] qpack::DecodeError),
23
24    #[error("unexpected frame {0:?}")]
25    UnexpectedFrame(Frame),
26
27    #[error("invalid method")]
28    InvalidMethod,
29
30    #[error("invalid url")]
31    InvalidUrl(#[from] url::ParseError),
32
33    #[error("invalid status")]
34    InvalidStatus,
35
36    #[error("expected 200, got: {0:?}")]
37    WrongStatus(Option<http::StatusCode>),
38
39    #[error("expected connect, got: {0:?}")]
40    WrongMethod(Option<http::method::Method>),
41
42    #[error("expected https, got: {0:?}")]
43    WrongScheme(Option<String>),
44
45    #[error("expected authority header")]
46    WrongAuthority,
47
48    #[error("expected webtransport, got: {0:?}")]
49    WrongProtocol(Option<String>),
50
51    #[error("expected path header")]
52    WrongPath,
53
54    #[error("invalid protocol header")]
55    InvalidProtocol,
56
57    #[error("structured field error: {0}")]
58    StructuredFieldError(Arc<sfv::Error>),
59
60    #[error("frame too large")]
61    FrameTooLarge,
62
63    #[error("non-200 status: {0:?}")]
64    ErrorStatus(http::StatusCode),
65
66    #[error("io error: {0}")]
67    Io(Arc<std::io::Error>),
68
69    #[error("invalid http header value")]
70    InvalidHttpHeaderValue,
71
72    #[error("invalid http header name")]
73    InvalidHttpHeaderName,
74
75    /// The encoded HEADERS frame or its decoded field section exceeds the CONNECT limit.
76    #[error("field section too large")]
77    FieldSectionTooLarge,
78}
79
80impl From<qpack::FieldSectionError> for ConnectError {
81    fn from(err: qpack::FieldSectionError) -> Self {
82        match err {
83            qpack::FieldSectionError::Decode(err) => Self::QpackError(err),
84            qpack::FieldSectionError::TooLarge => Self::FieldSectionTooLarge,
85        }
86    }
87}
88
89impl From<std::io::Error> for ConnectError {
90    fn from(err: std::io::Error) -> Self {
91        ConnectError::Io(Arc::new(err))
92    }
93}
94
95impl From<sfv::Error> for ConnectError {
96    fn from(err: sfv::Error) -> Self {
97        ConnectError::StructuredFieldError(Arc::new(err))
98    }
99}
100
101/// A CONNECT request to initiate a WebTransport session.
102///
103/// The [`Debug`](fmt::Debug) output is safe to log. It keeps the URL's scheme,
104/// host, port, and path, the protocols, and the header names, but redacts the
105/// URL's userinfo, query, and fragment. Header values are redacted too, except
106/// `origin` and `user-agent` when not marked
107/// [sensitive](http::HeaderValue::set_sensitive).
108#[non_exhaustive]
109#[derive(Clone)]
110pub struct ConnectRequest {
111    /// The URL to connect to.
112    pub url: Url,
113
114    /// The subprotocols requested (if any).
115    pub protocols: Vec<String>,
116
117    /// The raw HTTP/3 headers from the request.
118    pub headers: http::HeaderMap,
119}
120
121impl ConnectRequest {
122    pub fn new(url: impl Into<Url>) -> Self {
123        Self {
124            url: url.into(),
125            protocols: Vec::new(),
126            headers: http::HeaderMap::new(),
127        }
128    }
129
130    pub fn with_protocol(mut self, protocol: impl Into<String>) -> Self {
131        self.protocols.push(protocol.into());
132        self
133    }
134
135    pub fn with_protocols(mut self, protocols: impl IntoIterator<Item = String>) -> Self {
136        self.protocols.extend(protocols);
137        self
138    }
139
140    pub fn with_header(mut self, name: http::HeaderName, value: http::HeaderValue) -> Self {
141        self.headers.append(name, value);
142        self
143    }
144
145    pub fn with_headers(mut self, headers: http::HeaderMap) -> Self {
146        self.headers.extend(headers);
147        self
148    }
149
150    pub fn decode<B: Buf>(buf: &mut B) -> Result<Self, ConnectError> {
151        let mut data = decode_headers_frame(buf)?;
152        Self::decode_headers(&mut data)
153    }
154
155    fn decode_headers<B: Buf>(data: &mut B) -> Result<Self, ConnectError> {
156        let headers = qpack::Headers::decode(data)?;
157
158        let scheme = match headers.get(":scheme") {
159            Some("https") => "https",
160            Some(scheme) => Err(ConnectError::WrongScheme(Some(scheme.to_string())))?,
161            None => return Err(ConnectError::WrongScheme(None)),
162        };
163
164        let authority = headers
165            .get(":authority")
166            .ok_or(ConnectError::WrongAuthority)?;
167
168        let path_and_query = headers.get(":path").ok_or(ConnectError::WrongPath)?;
169
170        let method = headers.get(":method");
171        match method
172            .map(|method| method.try_into().map_err(|_| ConnectError::InvalidMethod))
173            .transpose()?
174        {
175            Some(http::Method::CONNECT) => (),
176            o => return Err(ConnectError::WrongMethod(o)),
177        };
178
179        let protocol = headers.get(":protocol");
180        if protocol != Some("webtransport") {
181            return Err(ConnectError::WrongProtocol(protocol.map(|s| s.to_string())));
182        }
183
184        let protocols = headers
185            .get(protocol_negotiation::AVAILABLE_NAME)
186            .map(protocol_negotiation::decode_list)
187            .transpose()
188            .map_err(|_| ConnectError::InvalidProtocol)?
189            .unwrap_or_default();
190
191        let url = Url::parse(&format!("{scheme}://{authority}{path_and_query}"))?;
192
193        // Save all headers, excluding pseudo-headers and protocol negotiation headers
194        // (protocol negotiation is handled via the `protocols` field).
195        let mut raw_headers = http::HeaderMap::new();
196        for (item_header_name, item_header_value) in headers.fields.iter() {
197            if item_header_name.starts_with(':') {
198                continue;
199            }
200            if item_header_name == protocol_negotiation::AVAILABLE_NAME {
201                continue;
202            }
203            let header_name = http::HeaderName::from_bytes(item_header_name.as_bytes())
204                .map_err(|_| ConnectError::InvalidHttpHeaderName)?;
205            let header_value = http::HeaderValue::from_str(item_header_value)
206                .map_err(|_| ConnectError::InvalidHttpHeaderValue)?;
207            raw_headers.append(header_name, header_value);
208        }
209
210        Ok(Self {
211            url,
212            protocols,
213            headers: raw_headers,
214        })
215    }
216
217    /// Read a CONNECT request from a stream, consuming only the exact bytes of the frame.
218    pub async fn read<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Self, ConnectError> {
219        let buf = read_headers_frame(stream).await?;
220        Self::decode_headers(&mut buf.as_slice())
221    }
222
223    pub fn encode<B: BufMut>(&self, buf: &mut B) -> Result<(), ConnectError> {
224        let mut headers = qpack::Headers::default();
225        for (item_header_name, item_header_value) in self.headers.iter() {
226            // Skip protocol negotiation headers; they are derived from `self.protocols`.
227            if item_header_name == protocol_negotiation::AVAILABLE_NAME {
228                continue;
229            }
230            // http::HeaderValue can contain arbitrary bytes (not just UTF-8).
231            // The to_str() method fails when the header value contains invalid UTF-8 bytes
232            let item_header_value_str = item_header_value
233                .to_str()
234                .map_err(|_| ConnectError::InvalidHttpHeaderValue)?;
235            headers.set(item_header_name.as_str(), item_header_value_str);
236        }
237        headers.set(":method", "CONNECT");
238        headers.set(":scheme", self.url.scheme());
239        headers.set(":authority", self.url.authority());
240        let path_and_query = match self.url.query() {
241            Some(query) => format!("{}?{}", self.url.path(), query),
242            None => self.url.path().to_string(),
243        };
244        headers.set(":path", &path_and_query);
245        headers.set(":protocol", "webtransport");
246
247        if !self.protocols.is_empty() {
248            let encoded = protocol_negotiation::encode_list(&self.protocols)?;
249            headers.set(protocol_negotiation::AVAILABLE_NAME, &encoded);
250        }
251
252        encode_headers_frame(&headers, buf)
253    }
254
255    pub async fn write<S: AsyncWrite + Unpin>(&self, stream: &mut S) -> Result<(), ConnectError> {
256        let mut buf = BytesMut::new();
257        self.encode(&mut buf)?;
258        stream.write_all_buf(&mut buf).await?;
259        Ok(())
260    }
261}
262
263impl From<Url> for ConnectRequest {
264    fn from(url: Url) -> Self {
265        Self {
266            url,
267            protocols: Vec::new(),
268            headers: http::HeaderMap::new(),
269        }
270    }
271}
272
273/// Header values shown by [`ConnectRequest`]'s `Debug` output.
274///
275/// This is an allowlist so that credentials in unknown or custom headers
276/// (`authorization`, `cookie`, `x-api-key`, ...) are redacted by default.
277const DEBUG_VISIBLE_HEADERS: [http::HeaderName; 2] =
278    [http::header::ORIGIN, http::header::USER_AGENT];
279
280/// Replaces a redacted value in `Debug` output.
281struct Redacted;
282
283impl fmt::Debug for Redacted {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        f.write_str("[redacted]")
286    }
287}
288
289/// Formats a URL with its userinfo, query, and fragment redacted.
290struct RedactedUrl<'a>(&'a Url);
291
292impl fmt::Debug for RedactedUrl<'_> {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        let url = self.0;
295        let mut redacted = String::from(&url[..Position::BeforeUsername]);
296        if !url.username().is_empty() || url.password().is_some() {
297            redacted.push_str("[redacted]@");
298        }
299        redacted.push_str(&url[Position::BeforeHost..Position::AfterPath]);
300        if url.query().is_some() {
301            redacted.push_str("?[redacted]");
302        }
303        if url.fragment().is_some() {
304            redacted.push_str("#[redacted]");
305        }
306        fmt::Debug::fmt(&redacted, f)
307    }
308}
309
310/// Formats headers with every value outside [`DEBUG_VISIBLE_HEADERS`] redacted.
311struct RedactedHeaders<'a>(&'a http::HeaderMap);
312
313impl fmt::Debug for RedactedHeaders<'_> {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        let mut map = f.debug_map();
316        for (name, value) in self.0 {
317            if DEBUG_VISIBLE_HEADERS.contains(name) && !value.is_sensitive() {
318                map.entry(name, value);
319            } else {
320                map.entry(name, &Redacted);
321            }
322        }
323        map.finish()
324    }
325}
326
327impl fmt::Debug for ConnectRequest {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        f.debug_struct("ConnectRequest")
330            .field("url", &RedactedUrl(&self.url))
331            .field("protocols", &self.protocols)
332            .field("headers", &RedactedHeaders(&self.headers))
333            .finish()
334    }
335}
336
337/// A CONNECT response to accept or reject a WebTransport session.
338#[non_exhaustive]
339#[derive(Debug, Clone)]
340pub struct ConnectResponse {
341    /// The status code of the response.
342    pub status: http::status::StatusCode,
343
344    /// The subprotocol selected by the server, if any
345    pub protocol: Option<String>,
346}
347
348impl ConnectResponse {
349    pub const OK: Self = Self {
350        status: http::StatusCode::OK,
351        protocol: None,
352    };
353
354    pub fn new(status: http::StatusCode) -> Self {
355        Self {
356            status,
357            protocol: None,
358        }
359    }
360
361    pub fn with_protocol(mut self, protocol: impl Into<String>) -> Self {
362        self.protocol = Some(protocol.into());
363        self
364    }
365
366    pub fn decode<B: Buf>(buf: &mut B) -> Result<Self, ConnectError> {
367        let mut data = decode_headers_frame(buf)?;
368        Self::decode_headers(&mut data)
369    }
370
371    fn decode_headers<B: Buf>(data: &mut B) -> Result<Self, ConnectError> {
372        let headers = qpack::Headers::decode(data)?;
373
374        let status = match headers
375            .get(":status")
376            .map(|status| {
377                http::StatusCode::from_str(status).map_err(|_| ConnectError::InvalidStatus)
378            })
379            .transpose()?
380        {
381            Some(status) if status.is_success() => status,
382            o => return Err(ConnectError::WrongStatus(o)),
383        };
384
385        let protocol = headers
386            .get(protocol_negotiation::SELECTED_NAME)
387            .map(protocol_negotiation::decode_item)
388            .transpose()
389            .map_err(|_| ConnectError::InvalidProtocol)?;
390
391        Ok(Self { status, protocol })
392    }
393
394    /// Read a CONNECT response from a stream, consuming only the exact bytes of the frame.
395    pub async fn read<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Self, ConnectError> {
396        let buf = read_headers_frame(stream).await?;
397        Self::decode_headers(&mut buf.as_slice())
398    }
399
400    pub fn encode<B: BufMut>(&self, buf: &mut B) -> Result<(), ConnectError> {
401        let mut headers = qpack::Headers::default();
402        headers.set(":status", self.status.as_str());
403        headers.set("sec-webtransport-http3-draft", "draft02");
404
405        if let Some(protocol) = self.protocol.as_ref() {
406            let encoded = protocol_negotiation::encode_item(protocol)?;
407            headers.set(protocol_negotiation::SELECTED_NAME, &encoded);
408        }
409
410        encode_headers_frame(&headers, buf)
411    }
412
413    pub async fn write<S: AsyncWrite + Unpin>(&self, stream: &mut S) -> Result<(), ConnectError> {
414        let mut buf = BytesMut::new();
415        self.encode(&mut buf)?;
416        stream.write_all_buf(&mut buf).await?;
417        Ok(())
418    }
419}
420
421impl Default for ConnectResponse {
422    fn default() -> Self {
423        Self::OK
424    }
425}
426
427impl From<http::StatusCode> for ConnectResponse {
428    fn from(status: http::StatusCode) -> Self {
429        Self {
430            status,
431            protocol: None,
432        }
433    }
434}
435
436fn check_frame_size(typ: Frame, size: u64) -> Result<(), ConnectError> {
437    if typ == Frame::HEADERS && size > MAX_FIELD_SECTION_SIZE {
438        return Err(ConnectError::FieldSectionTooLarge);
439    }
440    if size > MAX_FRAME_SIZE {
441        return Err(ConnectError::FrameTooLarge);
442    }
443    Ok(())
444}
445
446fn encode_headers_frame<B: BufMut>(
447    headers: &qpack::Headers,
448    buf: &mut B,
449) -> Result<(), ConnectError> {
450    // Use a temporary buffer so we can compute the size and write nothing on error.
451    let mut tmp = Vec::new();
452    headers.encode(&mut tmp)?;
453    let size = VarInt::from_u32(tmp.len() as u32);
454
455    Frame::HEADERS.encode(buf);
456    size.encode(buf);
457    buf.put_slice(&tmp);
458
459    Ok(())
460}
461
462fn decode_headers_frame<B: Buf>(buf: &mut B) -> Result<bytes::buf::Take<&mut B>, ConnectError> {
463    let (typ, data) = Frame::read_bounded(buf, MAX_FIELD_SECTION_SIZE, MAX_FRAME_SIZE).map_err(
464        |err| match err {
465            crate::frame::FrameReadError::UnexpectedEnd => ConnectError::UnexpectedEnd,
466            crate::frame::FrameReadError::TooLarge(Frame::HEADERS) => {
467                ConnectError::FieldSectionTooLarge
468            }
469            crate::frame::FrameReadError::TooLarge(_) => ConnectError::FrameTooLarge,
470        },
471    )?;
472    if typ != Frame::HEADERS {
473        return Err(ConnectError::UnexpectedFrame(typ));
474    }
475    Ok(data)
476}
477
478/// Read the next HEADERS frame from the stream, skipping any GREASE frames.
479///
480/// Returns the raw payload bytes of the HEADERS frame.
481async fn read_headers_frame<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Vec<u8>, ConnectError> {
482    loop {
483        let typ = Frame(
484            VarInt::read(stream)
485                .await
486                .map_err(|_| ConnectError::UnexpectedEnd)?,
487        );
488        let size = VarInt::read(stream)
489            .await
490            .map_err(|_| ConnectError::UnexpectedEnd)?;
491
492        let size = size.into_inner();
493        check_frame_size(typ, size)?;
494
495        let mut payload = stream.take(size);
496
497        if typ.is_grease() {
498            let n = tokio::io::copy(&mut payload, &mut tokio::io::sink()).await?;
499            if n < size {
500                return Err(ConnectError::UnexpectedEnd);
501            }
502            continue;
503        }
504
505        let mut buf = Vec::with_capacity(size as usize);
506        payload.read_to_end(&mut buf).await?;
507
508        if buf.len() < size as usize {
509            return Err(ConnectError::UnexpectedEnd);
510        }
511
512        if typ != Frame::HEADERS {
513            return Err(ConnectError::UnexpectedFrame(typ));
514        }
515
516        return Ok(buf);
517    }
518}
519
520mod protocol_negotiation {
521    //! WebTransport sub-protocol negotiation using RFC 8941 Structured Fields,
522    //!
523    //! according to [draft 14](https://www.ietf.org/archive/id/draft-ietf-webtrans-http3-14.html#section-3.3)
524
525    use sfv::{Item, ItemSerializer, List, ListEntry, ListSerializer, Parser, StringRef};
526
527    use crate::ConnectError;
528
529    /// The header name for the available protocols, sent within the WebTransport Connect request.
530    pub const AVAILABLE_NAME: &str = "wt-available-protocols";
531    /// The header name for the selected protocol, sent within the WebTransport Connect response.
532    pub const SELECTED_NAME: &str = "wt-protocol";
533
534    /// Encode a list of protocol strings as an RFC 8941 Structured Field List.
535    pub fn encode_list(protocols: &[String]) -> Result<String, ConnectError> {
536        let mut serializer = ListSerializer::new();
537        for protocol in protocols {
538            let s = StringRef::from_str(protocol)?;
539            let _ = serializer.bare_item(s);
540        }
541        serializer.finish().ok_or(ConnectError::InvalidProtocol)
542    }
543
544    /// Decode an RFC 8941 Structured Field List of strings.
545    pub fn decode_list(value: &str) -> Result<Vec<String>, ConnectError> {
546        let list = Parser::new(value).parse::<List>()?;
547
548        list.iter()
549            .map(|entry| match entry {
550                ListEntry::Item(item) => Ok(item
551                    .bare_item
552                    .as_string()
553                    .ok_or(ConnectError::InvalidProtocol)?
554                    .as_str()
555                    .to_string()),
556                _ => Err(ConnectError::InvalidProtocol),
557            })
558            .collect()
559    }
560
561    /// Encode a single string as an RFC 8941 Structured Field Item.
562    pub fn encode_item(protocol: &str) -> Result<String, ConnectError> {
563        let s = StringRef::from_str(protocol)?;
564        Ok(ItemSerializer::new().bare_item(s).finish())
565    }
566
567    /// Decode an RFC 8941 Structured Field Item (single string).
568    pub fn decode_item(value: &str) -> Result<String, ConnectError> {
569        let item = Parser::new(value).parse::<Item>()?;
570        Ok(item
571            .bare_item
572            .as_string()
573            .ok_or(ConnectError::InvalidProtocol)?
574            .as_str()
575            .to_string())
576    }
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582    use std::io::Cursor;
583
584    /// Build a framed CONNECT request on the wire.
585    fn encode_request(url: &str) -> Vec<u8> {
586        let req = ConnectRequest::new(Url::parse(url).unwrap());
587        let mut buf = Vec::new();
588        req.encode(&mut buf).unwrap();
589        buf
590    }
591
592    /// Build a framed CONNECT response on the wire.
593    fn encode_response() -> Vec<u8> {
594        let resp = ConnectResponse::OK;
595        let mut buf = Vec::new();
596        resp.encode(&mut buf).unwrap();
597        buf
598    }
599
600    /// Encode a GREASE frame: type (0x21 = first GREASE value) + length + payload.
601    fn encode_grease_frame(payload: &[u8]) -> Vec<u8> {
602        let mut buf = Vec::new();
603        VarInt::from_u32(0x21).encode(&mut buf); // GREASE frame type
604        VarInt::from_u32(payload.len() as u32).encode(&mut buf);
605        buf.extend_from_slice(payload);
606        buf
607    }
608
609    fn reframe(payload: &[u8]) -> Vec<u8> {
610        let mut wire = Vec::new();
611        Frame::HEADERS.encode(&mut wire);
612        VarInt::from_u32(payload.len() as u32).encode(&mut wire);
613        wire.extend_from_slice(payload);
614        wire
615    }
616
617    fn payload(mut wire: &[u8]) -> Vec<u8> {
618        let (_, mut data) = Frame::read(&mut wire).unwrap();
619        data.copy_to_bytes(data.remaining()).to_vec()
620    }
621
622    fn append_literal(payload: &mut Vec<u8>, name: &[u8], value: &[u8]) {
623        qpack::encode_prefix(payload, 3, 0b00100, name.len());
624        payload.extend_from_slice(name);
625        qpack::encode_prefix(payload, 7, 0, value.len());
626        payload.extend_from_slice(value);
627    }
628
629    fn assert_section_too_large<T: std::fmt::Debug>(result: Result<T, ConnectError>) {
630        assert_eq!(
631            result
632                .expect_err("oversized section was accepted")
633                .to_string(),
634            "field section too large"
635        );
636    }
637
638    #[test]
639    fn connect_rejects_literal_field_accordion() {
640        let alphabet = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
641        for base in [encode_request("https://example.com/"), encode_response()] {
642            let mut headers = payload(&base);
643            for i in 0..4_000 {
644                append_literal(&mut headers, &[alphabet[i / 64], alphabet[i % 64]], b"");
645            }
646            assert!(headers.len() < 16 * 1024);
647            let wire = reframe(&headers);
648            assert_section_too_large(ConnectRequest::decode(&mut wire.as_slice()));
649            assert_section_too_large(ConnectResponse::decode(&mut wire.as_slice()));
650        }
651    }
652
653    #[test]
654    fn response_charges_repeated_static_fields() {
655        let mut headers = payload(&encode_response());
656        // The indexed `:status: 200` line is one byte but costs 42 decoded bytes.
657        let status = headers[2];
658        assert_eq!(status, 0b1100_0000 | 25);
659        headers.resize(headers.len() + 500, status);
660        assert!(headers.len() < MAX_FIELD_SECTION_SIZE as usize);
661        assert_section_too_large(ConnectResponse::decode(&mut reframe(&headers).as_slice()));
662    }
663
664    #[tokio::test]
665    async fn request_encode_refuses_field_section_over_limit() {
666        // The pseudo-headers for https://example.com/ cost 234 bytes; `x-pad` costs 37 plus its value.
667        let fill = MAX_FIELD_SECTION_SIZE as usize - 234 - 37;
668        let request = |len: usize| {
669            ConnectRequest::new(Url::parse("https://example.com/").unwrap()).with_header(
670                http::HeaderName::from_static("x-pad"),
671                http::HeaderValue::from_str(&"a".repeat(len)).unwrap(),
672            )
673        };
674
675        let mut wire = Vec::new();
676        request(fill).encode(&mut wire).unwrap();
677        let decoded = ConnectRequest::decode(&mut wire.as_slice()).unwrap();
678        assert_eq!(decoded.headers["x-pad"].len(), fill);
679
680        let mut wire = Vec::new();
681        assert_section_too_large(request(fill + 1).encode(&mut wire));
682        assert_section_too_large(request(fill + 1).write(&mut wire).await);
683        assert!(
684            wire.is_empty(),
685            "a refused request wrote {} bytes",
686            wire.len()
687        );
688    }
689
690    #[tokio::test]
691    async fn response_encode_refuses_field_section_over_limit() {
692        let response =
693            ConnectResponse::OK.with_protocol("a".repeat(MAX_FIELD_SECTION_SIZE as usize));
694        let mut wire = Vec::new();
695        assert_section_too_large(response.encode(&mut wire));
696        assert_section_too_large(response.write(&mut wire).await);
697        assert!(
698            wire.is_empty(),
699            "a refused response wrote {} bytes",
700            wire.len()
701        );
702    }
703
704    // RFC 7541 Appendix B gives 'a' the five-bit code 00011.
705    fn huffman_a(count: usize) -> Vec<u8> {
706        let bits = count * 5;
707        let mut encoded = vec![0; bits.div_ceil(8)];
708        for i in 0..count {
709            for bit in [3, 4] {
710                let position = i * 5 + bit;
711                encoded[position / 8] |= 1 << (7 - position % 8);
712            }
713        }
714        for position in bits..encoded.len() * 8 {
715            encoded[position / 8] |= 1 << (7 - position % 8);
716        }
717        encoded
718    }
719
720    #[test]
721    fn connect_rejects_huffman_expansion() {
722        for base in [encode_request("https://example.com/"), encode_response()] {
723            let mut headers = payload(&base);
724            qpack::encode_prefix(&mut headers, 3, 0b00100, 1);
725            headers.push(b'x');
726            let encoded = huffman_a(17_000);
727            qpack::encode_prefix(&mut headers, 7, 1, encoded.len());
728            headers.extend_from_slice(&encoded);
729            assert!(headers.len() < 16 * 1024);
730            let wire = reframe(&headers);
731            assert_section_too_large(ConnectRequest::decode(&mut wire.as_slice()));
732            assert_section_too_large(ConnectResponse::decode(&mut wire.as_slice()));
733        }
734    }
735
736    #[tokio::test]
737    async fn connect_rejects_declared_size_before_payload_arrives() {
738        let mut wire = Vec::new();
739        Frame::HEADERS.encode(&mut wire);
740        VarInt::from_u32(16 * 1024 + 1).encode(&mut wire);
741        assert_section_too_large(ConnectRequest::decode(&mut wire.as_slice()));
742        assert_section_too_large(ConnectResponse::decode(&mut wire.as_slice()));
743        assert_section_too_large(ConnectRequest::read(&mut Cursor::new(wire.clone())).await);
744        assert_section_too_large(ConnectResponse::read(&mut Cursor::new(wire)).await);
745    }
746
747    #[test]
748    fn response_charges_duplicate_literal_names() {
749        let mut headers = payload(&encode_response());
750        for _ in 0..500 {
751            append_literal(&mut headers, b"x", b"");
752        }
753        assert_section_too_large(ConnectResponse::decode(&mut reframe(&headers).as_slice()));
754    }
755
756    #[test]
757    fn connect_rejects_huffman_name_expansion() {
758        let mut headers = payload(&encode_request("https://example.com/"));
759        let name = huffman_a(17_000);
760        qpack::encode_prefix(&mut headers, 3, 0b00101, name.len());
761        headers.extend_from_slice(&name);
762        qpack::encode_prefix(&mut headers, 7, 0, 0);
763        assert!(headers.len() < MAX_FIELD_SECTION_SIZE as usize);
764        let wire = reframe(&headers);
765        assert_section_too_large(ConnectRequest::decode(&mut wire.as_slice()));
766        assert_section_too_large(ConnectResponse::decode(&mut wire.as_slice()));
767    }
768
769    #[tokio::test]
770    async fn grease_keeps_its_frame_budget_and_skips_iteratively() {
771        let mut grease = encode_grease_frame(&vec![0; 20 * 1024]);
772        for _ in 0..10_000 {
773            grease.extend_from_slice(&encode_grease_frame(b""));
774        }
775        for base in [encode_request("https://example.com/"), encode_response()] {
776            let mut wire = grease.clone();
777            wire.extend_from_slice(&base);
778            if base == encode_response() {
779                assert_eq!(
780                    ConnectResponse::decode(&mut wire.as_slice())
781                        .unwrap()
782                        .status,
783                    http::StatusCode::OK
784                );
785                assert_eq!(
786                    ConnectResponse::read(&mut Cursor::new(wire))
787                        .await
788                        .unwrap()
789                        .status,
790                    http::StatusCode::OK
791                );
792            } else {
793                assert_eq!(
794                    ConnectRequest::decode(&mut wire.as_slice())
795                        .unwrap()
796                        .url
797                        .as_str(),
798                    "https://example.com/"
799                );
800                assert_eq!(
801                    ConnectRequest::read(&mut Cursor::new(wire))
802                        .await
803                        .unwrap()
804                        .url
805                        .as_str(),
806                    "https://example.com/"
807                );
808            }
809        }
810        let wire = encode_grease_frame(&vec![0; MAX_FRAME_SIZE as usize + 1]);
811        assert!(matches!(
812            ConnectRequest::decode(&mut wire.as_slice()),
813            Err(ConnectError::FrameTooLarge)
814        ));
815        assert!(matches!(
816            ConnectResponse::read(&mut Cursor::new(wire)).await,
817            Err(ConnectError::FrameTooLarge)
818        ));
819    }
820
821    #[test]
822    fn declared_size_is_checked_without_pointer_width_truncation() {
823        let mut wire = Vec::new();
824        Frame::HEADERS.encode(&mut wire);
825        VarInt::try_from((1_u64 << 32) + 2)
826            .unwrap()
827            .encode(&mut wire);
828        wire.extend_from_slice(&[0, 0]);
829        assert_section_too_large(ConnectRequest::decode(&mut wire.as_slice()));
830        assert_section_too_large(ConnectResponse::decode(&mut wire.as_slice()));
831    }
832
833    // ---- ConnectRequest::read tests ----
834
835    #[tokio::test]
836    async fn request_read_exact_consumption() {
837        // Verify read() consumes only the frame bytes, not trailing data.
838        let mut wire = encode_request("https://example.com/path");
839        let trailing = b"trailing data";
840        wire.extend_from_slice(trailing);
841
842        let mut cursor = Cursor::new(wire);
843        let req = ConnectRequest::read(&mut cursor).await.unwrap();
844        assert_eq!(req.url.as_str(), "https://example.com/path");
845
846        // The cursor should be positioned right after the frame, leaving trailing data.
847        let pos = cursor.position() as usize;
848        let remaining = &cursor.into_inner()[pos..];
849        assert_eq!(remaining, trailing);
850    }
851
852    #[tokio::test]
853    async fn request_read_roundtrip() {
854        let wire = encode_request("https://example.com/foo?bar=1");
855        let mut cursor = Cursor::new(wire);
856        let req = ConnectRequest::read(&mut cursor).await.unwrap();
857        assert_eq!(req.url.as_str(), "https://example.com/foo?bar=1");
858    }
859
860    #[tokio::test]
861    async fn request_read_skips_grease() {
862        // Prepend a GREASE frame before the real HEADERS frame.
863        let mut wire = encode_grease_frame(b"junk");
864        wire.extend_from_slice(&encode_request("https://example.com/"));
865
866        let mut cursor = Cursor::new(wire);
867        let req = ConnectRequest::read(&mut cursor).await.unwrap();
868        assert_eq!(req.url.as_str(), "https://example.com/");
869    }
870
871    #[tokio::test]
872    async fn request_read_rejects_frame_too_large() {
873        // Craft a frame header claiming a huge payload.
874        let mut wire = Vec::new();
875        Frame::HEADERS.encode(&mut wire);
876        // Refuse the HEADERS length before reading any payload.
877        VarInt::from_u32(128 * 1024).encode(&mut wire);
878
879        let mut cursor = Cursor::new(wire);
880        let err = ConnectRequest::read(&mut cursor).await.unwrap_err();
881        assert!(
882            matches!(err, ConnectError::FieldSectionTooLarge),
883            "expected FieldSectionTooLarge, got {err:?}"
884        );
885    }
886
887    #[tokio::test]
888    async fn request_read_rejects_wrong_frame_type() {
889        let mut wire = Vec::new();
890        Frame::DATA.encode(&mut wire);
891        VarInt::from_u32(0).encode(&mut wire);
892
893        let mut cursor = Cursor::new(wire);
894        let err = ConnectRequest::read(&mut cursor).await.unwrap_err();
895        assert!(
896            matches!(err, ConnectError::UnexpectedFrame(f) if f == Frame::DATA),
897            "expected UnexpectedFrame(DATA), got {err:?}"
898        );
899    }
900
901    #[tokio::test]
902    async fn request_read_empty_stream() {
903        let mut cursor = Cursor::new(Vec::<u8>::new());
904        let err = ConnectRequest::read(&mut cursor).await.unwrap_err();
905        assert!(matches!(err, ConnectError::UnexpectedEnd));
906    }
907
908    // ---- ConnectResponse::read tests ----
909
910    #[tokio::test]
911    async fn response_read_exact_consumption() {
912        let mut wire = encode_response();
913        let trailing = b"extra bytes";
914        wire.extend_from_slice(trailing);
915
916        let mut cursor = Cursor::new(wire);
917        let resp = ConnectResponse::read(&mut cursor).await.unwrap();
918        assert_eq!(resp.status, http::StatusCode::OK);
919
920        let pos = cursor.position() as usize;
921        let remaining = &cursor.into_inner()[pos..];
922        assert_eq!(remaining, trailing);
923    }
924
925    #[tokio::test]
926    async fn response_read_roundtrip() {
927        let wire = encode_response();
928        let mut cursor = Cursor::new(wire);
929        let resp = ConnectResponse::read(&mut cursor).await.unwrap();
930        assert_eq!(resp.status, http::StatusCode::OK);
931    }
932
933    #[tokio::test]
934    async fn response_read_skips_grease() {
935        let mut wire = encode_grease_frame(b"grease");
936        wire.extend_from_slice(&encode_response());
937
938        let mut cursor = Cursor::new(wire);
939        let resp = ConnectResponse::read(&mut cursor).await.unwrap();
940        assert_eq!(resp.status, http::StatusCode::OK);
941    }
942
943    #[tokio::test]
944    async fn response_read_rejects_frame_too_large() {
945        let mut wire = Vec::new();
946        Frame::HEADERS.encode(&mut wire);
947        VarInt::from_u32(128 * 1024).encode(&mut wire);
948
949        let mut cursor = Cursor::new(wire);
950        let err = ConnectResponse::read(&mut cursor).await.unwrap_err();
951        assert!(
952            matches!(err, ConnectError::FieldSectionTooLarge),
953            "expected FieldSectionTooLarge, got {err:?}"
954        );
955    }
956
957    #[tokio::test]
958    async fn response_read_rejects_wrong_frame_type() {
959        let mut wire = Vec::new();
960        Frame::SETTINGS.encode(&mut wire);
961        VarInt::from_u32(0).encode(&mut wire);
962
963        let mut cursor = Cursor::new(wire);
964        let err = ConnectResponse::read(&mut cursor).await.unwrap_err();
965        assert!(
966            matches!(err, ConnectError::UnexpectedFrame(f) if f == Frame::SETTINGS),
967            "expected UnexpectedFrame(SETTINGS), got {err:?}"
968        );
969    }
970
971    #[tokio::test]
972    async fn response_read_empty_stream() {
973        let mut cursor = Cursor::new(Vec::<u8>::new());
974        let err = ConnectResponse::read(&mut cursor).await.unwrap_err();
975        assert!(matches!(err, ConnectError::UnexpectedEnd));
976    }
977
978    // ---- Truncated payload tests ----
979
980    #[tokio::test]
981    async fn request_read_truncated_payload() {
982        // Frame header claims 100 bytes but only 5 are present.
983        let mut wire = Vec::new();
984        Frame::HEADERS.encode(&mut wire);
985        VarInt::from_u32(100).encode(&mut wire);
986        wire.extend_from_slice(b"short");
987
988        let mut cursor = Cursor::new(wire);
989        let err = ConnectRequest::read(&mut cursor).await.unwrap_err();
990        assert!(matches!(err, ConnectError::UnexpectedEnd));
991    }
992
993    #[tokio::test]
994    async fn response_read_truncated_payload() {
995        let mut wire = Vec::new();
996        Frame::HEADERS.encode(&mut wire);
997        VarInt::from_u32(100).encode(&mut wire);
998        wire.extend_from_slice(b"short");
999
1000        let mut cursor = Cursor::new(wire);
1001        let err = ConnectResponse::read(&mut cursor).await.unwrap_err();
1002        assert!(matches!(err, ConnectError::UnexpectedEnd));
1003    }
1004
1005    #[tokio::test]
1006    async fn request_read_truncated_grease() {
1007        // GREASE frame claims 100 bytes but only 3 are present.
1008        let mut wire = Vec::new();
1009        VarInt::from_u32(0x21).encode(&mut wire);
1010        VarInt::from_u32(100).encode(&mut wire);
1011        wire.extend_from_slice(b"abc");
1012
1013        let mut cursor = Cursor::new(wire);
1014        let err = ConnectRequest::read(&mut cursor).await.unwrap_err();
1015        assert!(matches!(err, ConnectError::UnexpectedEnd));
1016    }
1017
1018    #[test]
1019    fn request_debug_keeps_url_without_credentials() {
1020        let req = ConnectRequest::new(Url::parse("https://example.com:4443/moq/room").unwrap())
1021            .with_protocol("moq-lite-03");
1022        assert_eq!(
1023            format!("{req:?}"),
1024            r#"ConnectRequest { url: "https://example.com:4443/moq/room", protocols: ["moq-lite-03"], headers: {} }"#
1025        );
1026    }
1027
1028    #[test]
1029    fn request_debug_redacts_url_credentials() {
1030        let url = "https://alice:hunter2@example.com/moq?jwt=SECRET&x=1#access_token=SECRET";
1031        let req = ConnectRequest::new(Url::parse(url).unwrap());
1032        let debug = format!("{req:?}");
1033        assert!(
1034            debug.contains(r#"url: "https://[redacted]@example.com/moq?[redacted]#[redacted]""#),
1035            "{debug}"
1036        );
1037        for secret in ["alice", "hunter2", "SECRET", "x=1"] {
1038            assert!(!debug.contains(secret), "{secret} leaked: {debug}");
1039        }
1040
1041        let req = ConnectRequest::new(Url::parse("https://alice@example.com/").unwrap());
1042        assert!(format!("{req:?}").contains(r#""https://[redacted]@example.com/""#));
1043    }
1044
1045    #[test]
1046    fn request_debug_redacts_header_values() {
1047        use http::{header, HeaderName, HeaderValue};
1048
1049        let mut sensitive_agent = HeaderValue::from_static("agent-SECRET");
1050        sensitive_agent.set_sensitive(true);
1051
1052        let req = ConnectRequest::new(Url::parse("https://example.com/").unwrap())
1053            .with_header(
1054                header::AUTHORIZATION,
1055                HeaderValue::from_static("Bearer SECRET"),
1056            )
1057            .with_header(
1058                header::PROXY_AUTHORIZATION,
1059                HeaderValue::from_static("Basic SECRET"),
1060            )
1061            .with_header(header::COOKIE, HeaderValue::from_static("session=SECRET"))
1062            .with_header(
1063                header::SET_COOKIE,
1064                HeaderValue::from_static("session=SECRET"),
1065            )
1066            .with_header(
1067                HeaderName::from_static("x-api-key"),
1068                HeaderValue::from_static("SECRET"),
1069            )
1070            .with_header(
1071                header::ORIGIN,
1072                HeaderValue::from_static("https://app.example"),
1073            )
1074            .with_header(header::USER_AGENT, sensitive_agent);
1075        let debug = format!("{req:?}");
1076
1077        assert!(!debug.contains("SECRET"), "{debug}");
1078        for name in [
1079            "authorization",
1080            "proxy-authorization",
1081            "cookie",
1082            "set-cookie",
1083            "x-api-key",
1084        ] {
1085            assert!(
1086                debug.contains(&format!(r#""{name}": [redacted]"#)),
1087                "{name}: {debug}"
1088            );
1089        }
1090        assert!(
1091            debug.contains(r#""origin": "https://app.example""#),
1092            "{debug}"
1093        );
1094        assert!(debug.contains(r#""user-agent": [redacted]"#), "{debug}");
1095    }
1096
1097    #[test]
1098    fn decoded_request_debug_redacts_credentials() {
1099        let req = ConnectRequest::new(Url::parse("https://example.com/moq?jwt=SECRET").unwrap())
1100            .with_header(
1101                http::header::AUTHORIZATION,
1102                http::HeaderValue::from_static("Bearer SECRET"),
1103            )
1104            .with_header(
1105                http::header::USER_AGENT,
1106                http::HeaderValue::from_static("moq-test"),
1107            );
1108        let mut wire = Vec::new();
1109        req.encode(&mut wire).unwrap();
1110
1111        let decoded = ConnectRequest::decode(&mut wire.as_slice()).unwrap();
1112        assert_eq!(decoded.url.query(), Some("jwt=SECRET"));
1113
1114        // Decoded header order is unspecified, so check each entry separately.
1115        let debug = format!("{decoded:?}");
1116        assert!(!debug.contains("SECRET"), "{debug}");
1117        for expected in [
1118            r#"url: "https://example.com/moq?[redacted]""#,
1119            r#""authorization": [redacted]"#,
1120            r#""user-agent": "moq-test""#,
1121        ] {
1122            assert!(debug.contains(expected), "{expected}: {debug}");
1123        }
1124    }
1125}