diff --git a/AGENTS.md b/AGENTS.md index fa1d6a0..a1ef78f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,6 +4,15 @@ The design target is extensible, cross-platform, and mobile-friendly networking Preserve clear layering and strong architectural boundaries; do not introduce shortcut designs that make the system harder to evolve Treat code as the source of truth and keep documentation aligned with actual behavior +## RFC Conformance + +- Strict conformance to applicable network protocol RFCs is a design and release requirement for every supported feature. Code records actual behavior; applicable RFCs define required protocol behavior. Resolve conflicts by fixing implementation and tests. +- Identify the RFC sections, endpoint role, applicable conditions, updates, and verified errata before changing protocol behavior. Record the mapping from requirements to implementation owners, independent expected values, tests, and verification status. +- Applicable MUST/MUST NOT requirements are release blockers. Follow SHOULD/SHOULD NOT by default; any RFC-permitted exception needs its specific rationale and tests. Explicitly record MAY choices and supported scope without claiming optional features are mandatory. +- Do not substitute existing behavior, OkHttp compatibility, or a dependency accepting input for protocol evidence. Compatibility choices must remain within the applicable RFC's permitted behavior. +- Derive positive, negative, wire, and failure-path tests from the specification. Probability arguments alone do not establish a protocol invariant when deterministic validation is possible. +- Do not claim conformance for unimplemented or unverified behavior. Fix or explicitly block affected work on discovered violations; this requirement does not imply that the existing library has completed a full conformance audit. + Treat the following as the canonical execution chain of the project: ``` User API diff --git a/Cargo.lock b/Cargo.lock index c8963ef..e8cd3d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1039,6 +1039,12 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -1166,6 +1172,7 @@ dependencies = [ "http-body-util", "httpdate", "hyper", + "mime", "openwire-core", "openwire-rustls", "openwire-test", diff --git a/README.md b/README.md index fa2156a..6dd6082 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,10 @@ blocks, and stable observability hooks. HTTP/2 protocol binding - `RequestBody::absent()` for typical no-body requests and `RequestBody::explicit_empty()` when zero-length framing must be explicit +- `RequestBody::content_length()` independent of replayability, plus DATA-only + `concat` and `from_stream_with_length` for known-length one-shot bodies +- optional `multipart` form encoder (`Form` / `Part`) that produces an ordinary + `RequestBody` and owns `Content-Type` before `Client::execute` - optional JSON helpers behind the `json` feature - optional WebSocket (RFC 6455) client behind the `websocket` feature, with a pluggable `WebSocketEngine` trait and a built-in native codec @@ -104,6 +108,7 @@ Optional features: | `cookies` | yes | Built-in `Jar` (`cookie_store` + public suffix list) | | `json` | no | `RequestBody::from_json` / `ResponseBody::json`, JSON pretty-print in `LoggerInterceptor` | | `websocket` | no | RFC 6455 WebSocket client | +| `multipart` | no | `multipart/form-data` encoder (`Form` / `Part`) | Optional companion crates are published with the same workspace version, for example `openwire-cache = "0.1.2"` or `openwire-tungstenite = "0.1.2"`. @@ -176,6 +181,35 @@ let response = queued.await_response().await?; Dropping `QueuedCall` does not request cancellation; call `cancel()` on the queued call or its `CallHandle` when the in-flight work should stop. +## Multipart Uploads + +Enable the `multipart` feature and build the form before `Client::execute`. +`Form::into_request` replaces any existing `Content-Type` with the generated +`multipart/form-data` value and clears stale framing headers. A known length +does not make a stream replayable: + +```rust +use bytes::Bytes; +use http::Request; +use openwire::{multipart::{Form, Part}, Client}; + +let client = Client::builder().build()?; +let request = Form::new() + .text("description", "upload from OpenWire") + .part( + "file", + Part::bytes(Bytes::from_static(b"hello\n")) + .file_name("hello.txt") + .mime_str("text/plain; charset=utf-8")?, + ) + .into_request( + Request::builder() + .method("POST") + .uri("https://example.com/upload"), + )?; +let response = client.execute(request).await?; +``` + ## Authentication Challenges `Authenticator` receives an `AuthContext` for origin `401 Unauthorized`, diff --git a/crates/openwire-core/src/body.rs b/crates/openwire-core/src/body.rs index 7204998..4eacd65 100644 --- a/crates/openwire-core/src/body.rs +++ b/crates/openwire-core/src/body.rs @@ -5,6 +5,7 @@ use bytes::Bytes; use futures_core::Stream; use futures_util::TryStreamExt; use http_body::{Body, Frame, SizeHint}; +use http_body_util::combinators::BoxBody; use http_body_util::{BodyExt, Empty, Full, StreamBody}; use pin_project_lite::pin_project; #[cfg(feature = "json")] @@ -14,30 +15,36 @@ use serde::Serialize; use crate::WireError; -pin_project! { - #[derive(Debug)] - pub struct RequestBody { - #[pin] - inner: RequestBodyInner, - replayable_len: Option, - presence: RequestBodyPresence, - } +const COMPOSITE_SKIP_BUDGET: usize = 16; +const EMPTY_FRAME_SKIP_BUDGET: usize = 16; + +#[derive(Debug)] +pub struct RequestBody { + inner: RequestBodyInner, + content_length: Option, + replayable: bool, + presence: RequestBodyPresence, + started: bool, } impl RequestBody { pub fn absent() -> Self { Self { inner: RequestBodyInner::Empty, - replayable_len: Some(0), + content_length: Some(0), + replayable: true, presence: RequestBodyPresence::Absent, + started: false, } } pub fn explicit_empty() -> Self { Self { inner: RequestBodyInner::Empty, - replayable_len: Some(0), + content_length: Some(0), + replayable: true, presence: RequestBodyPresence::Present, + started: false, } } @@ -47,8 +54,10 @@ impl RequestBody { pub fn from_bytes(bytes: Bytes) -> Self { Self { - replayable_len: Some(bytes.len() as u64), + content_length: Some(bytes.len() as u64), + replayable: true, presence: RequestBodyPresence::Present, + started: false, inner: RequestBodyInner::Replayable { bytes, emitted: false, @@ -81,9 +90,86 @@ impl RequestBody { inner: RequestBodyInner::Streaming { inner: StreamBody::new(stream).boxed(), }, - replayable_len: None, + content_length: None, + replayable: false, presence: RequestBodyPresence::Present, + started: false, + } + } + + /// DATA-only stream with a declared length. The body is not replayable. + /// + /// Reaching `length` bytes does not complete the body until the source + /// yields EOF. An oversized chunk is rejected before it is forwarded. + pub fn from_stream_with_length(stream: S, length: u64) -> Self + where + S: Stream> + Send + Sync + 'static, + E: Into + 'static, + { + let stream = stream.map_ok(Frame::data).map_err(Into::into); + Self { + inner: RequestBodyInner::Strict { + inner: StreamBody::new(stream).boxed(), + remaining: length, + eof_verified: false, + errored: false, + }, + content_length: Some(length), + replayable: false, + presence: RequestBodyPresence::Present, + started: false, + } + } + + /// Complete length at construction, independent of replayability. + pub fn content_length(&self) -> Option { + self.content_length + } + + /// DATA-only composition of fresh, unpolled children. + /// + /// Empty input yields a present explicit-empty body. Started children and + /// length overflow are rejected before any polling. + pub fn concat(bodies: Vec) -> Result { + if bodies.is_empty() { + return Ok(Self::explicit_empty()); + } + + for body in &bodies { + if body.started { + return Err(WireError::invalid_request( + "cannot concatenate a request body that has already been polled", + )); + } } + + let mut total = Some(0u64); + let mut replayable = true; + for body in &bodies { + replayable &= body.replayable; + match (total, body.content_length) { + (Some(acc), Some(len)) => { + total = Some(acc.checked_add(len).ok_or_else(|| { + WireError::invalid_request( + "concatenated request body length overflowed u64", + ) + })?); + } + _ => total = None, + } + } + + Ok(Self { + inner: RequestBodyInner::Composite { + children: bodies, + cursor: 0, + errored: false, + }, + content_length: total, + replayable, + presence: RequestBodyPresence::Present, + started: false, + }) } pub fn try_clone(&self) -> Option { @@ -93,12 +179,23 @@ impl RequestBody { RequestBodyPresence::Present => Self::explicit_empty(), }), RequestBodyInner::Replayable { bytes, .. } => Some(Self::from_bytes(bytes.clone())), - RequestBodyInner::Streaming { .. } => None, + RequestBodyInner::Streaming { .. } | RequestBodyInner::Strict { .. } => None, + RequestBodyInner::Composite { children, .. } => { + let cloned = children + .iter() + .map(RequestBody::try_clone) + .collect::>>()?; + Self::concat(cloned).ok() + } } } pub fn replayable_len(&self) -> Option { - self.replayable_len + if self.replayable { + self.content_length + } else { + None + } } pub fn is_absent(&self) -> bool { @@ -108,6 +205,8 @@ impl RequestBody { /// Wraps an arbitrary body as a present, non-replayable request body. /// /// Used by transport observers that instrument an already-built `RequestBody`. + /// DATA size hints are not treated as framing length because the inner body + /// may still emit trailers. pub fn from_body(body: B) -> Self where B: Body + Send + Sync + 'static, @@ -116,8 +215,10 @@ impl RequestBody { inner: RequestBodyInner::Streaming { inner: body.boxed(), }, - replayable_len: None, + content_length: None, + replayable: false, presence: RequestBodyPresence::Present, + started: false, } } } @@ -136,9 +237,11 @@ impl Body for RequestBody { self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll, Self::Error>>> { - match self.project().inner.project() { - RequestBodyInnerProj::Empty => Poll::Ready(None), - RequestBodyInnerProj::Replayable { bytes, emitted } => { + let this = self.get_mut(); + this.started = true; + match &mut this.inner { + RequestBodyInner::Empty => Poll::Ready(None), + RequestBodyInner::Replayable { bytes, emitted } => { if *emitted { return Poll::Ready(None); } @@ -150,7 +253,19 @@ impl Body for RequestBody { Poll::Ready(Some(Ok(Frame::data(bytes.clone())))) } } - RequestBodyInnerProj::Streaming { inner } => inner.poll_frame(cx), + RequestBodyInner::Streaming { inner } => Pin::new(inner).poll_frame(cx), + RequestBodyInner::Strict { + inner, + remaining, + eof_verified, + errored, + .. + } => poll_strict(inner, remaining, eof_verified, errored, cx), + RequestBodyInner::Composite { + children, + cursor, + errored, + } => poll_composite(children, cursor, errored, cx), } } @@ -159,14 +274,72 @@ impl Body for RequestBody { RequestBodyInner::Empty => true, RequestBodyInner::Replayable { bytes, emitted } => *emitted || bytes.is_empty(), RequestBodyInner::Streaming { inner } => inner.is_end_stream(), + RequestBodyInner::Strict { + eof_verified, + errored, + .. + } => *errored || *eof_verified, + RequestBodyInner::Composite { + children, + cursor, + errored, + } => { + *errored + || children + .get(*cursor..) + .map(|rest| rest.iter().all(Body::is_end_stream)) + .unwrap_or(true) + } } } fn size_hint(&self) -> SizeHint { match &self.inner { RequestBodyInner::Empty => SizeHint::with_exact(0), - RequestBodyInner::Replayable { bytes, .. } => SizeHint::with_exact(bytes.len() as u64), - RequestBodyInner::Streaming { inner } => inner.size_hint(), + RequestBodyInner::Replayable { bytes, emitted } => { + if *emitted { + SizeHint::with_exact(0) + } else { + SizeHint::with_exact(bytes.len() as u64) + } + } + RequestBodyInner::Streaming { inner } => { + let inner = inner.size_hint(); + if self.content_length.is_some() { + inner + } else { + // DATA size alone cannot establish framing length: the inner + // body may still emit trailers. Keep the lower bound so + // consumers can estimate remaining DATA without letting an + // exact hint suppress trailing frames. + let mut hint = SizeHint::new(); + hint.set_lower(inner.lower()); + hint + } + } + RequestBodyInner::Strict { + remaining, + eof_verified, + errored, + .. + } => { + if *errored || *eof_verified { + SizeHint::with_exact(0) + } else { + SizeHint::with_exact(*remaining) + } + } + RequestBodyInner::Composite { + children, + cursor, + errored, + } => { + if *errored { + SizeHint::with_exact(0) + } else { + composite_size_hint(children.get(*cursor..).unwrap_or(&[])) + } + } } } } @@ -201,20 +374,27 @@ impl From<&'static str> for RequestBody { } } -pin_project! { - #[project = RequestBodyInnerProj] - #[derive(Debug)] - enum RequestBodyInner { - Empty, - Replayable { - bytes: Bytes, - emitted: bool, - }, - Streaming { - #[pin] - inner: http_body_util::combinators::BoxBody, - }, - } +#[derive(Debug)] +enum RequestBodyInner { + Empty, + Replayable { + bytes: Bytes, + emitted: bool, + }, + Streaming { + inner: BoxBody, + }, + Strict { + inner: BoxBody, + remaining: u64, + eof_verified: bool, + errored: bool, + }, + Composite { + children: Vec, + cursor: usize, + errored: bool, + }, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -223,11 +403,152 @@ enum RequestBodyPresence { Present, } +fn poll_strict( + inner: &mut BoxBody, + remaining: &mut u64, + eof_verified: &mut bool, + errored: &mut bool, + cx: &mut Context<'_>, +) -> Poll, WireError>>> { + if *errored || *eof_verified { + return Poll::Ready(None); + } + + let mut skips = 0usize; + loop { + match Pin::new(&mut *inner).poll_frame(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + if *remaining > 0 { + *errored = true; + return Poll::Ready(Some(Err(body_length_error( + "request body ended before declared content length", + )))); + } + *eof_verified = true; + return Poll::Ready(None); + } + Poll::Ready(Some(Err(error))) => { + *errored = true; + return Poll::Ready(Some(Err(error))); + } + Poll::Ready(Some(Ok(frame))) => { + let Ok(data) = frame.into_data() else { + *errored = true; + return Poll::Ready(Some(Err(body_length_error( + "strict-length request body cannot include trailers", + )))); + }; + if data.is_empty() { + skips += 1; + if skips >= EMPTY_FRAME_SKIP_BUDGET { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + continue; + } + let chunk_len = data.len() as u64; + if chunk_len > *remaining { + *errored = true; + return Poll::Ready(Some(Err(body_length_error( + "request body exceeded declared content length", + )))); + } + *remaining -= chunk_len; + return Poll::Ready(Some(Ok(Frame::data(data)))); + } + } + } +} + +fn poll_composite( + children: &mut [RequestBody], + cursor: &mut usize, + errored: &mut bool, + cx: &mut Context<'_>, +) -> Poll, WireError>>> { + if *errored { + return Poll::Ready(None); + } + + let mut skips = 0usize; + while *cursor < children.len() { + match Pin::new(&mut children[*cursor]).poll_frame(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + *cursor += 1; + skips += 1; + if skips >= COMPOSITE_SKIP_BUDGET && *cursor < children.len() { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + } + Poll::Ready(Some(Err(error))) => { + *errored = true; + return Poll::Ready(Some(Err(error))); + } + Poll::Ready(Some(Ok(frame))) => { + if !frame.is_data() { + *errored = true; + return Poll::Ready(Some(Err(WireError::body( + "concatenated request body cannot include trailers", + std::io::Error::other("non-DATA frame in concatenated body"), + )))); + } + let data = frame.into_data().expect("concatenated frame was DATA"); + if data.is_empty() { + skips += 1; + if skips >= COMPOSITE_SKIP_BUDGET { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + continue; + } + return Poll::Ready(Some(Ok(Frame::data(data)))); + } + } + } + + Poll::Ready(None) +} + +fn composite_size_hint(children: &[RequestBody]) -> SizeHint { + let mut exact = Some(0u64); + let mut lower = 0u64; + let mut upper = Some(0u64); + for child in children { + let hint = child.size_hint(); + lower = lower.saturating_add(hint.lower()); + match (upper, hint.upper()) { + (Some(acc), Some(len)) => upper = acc.checked_add(len), + _ => upper = None, + } + match (exact, hint.exact()) { + (Some(acc), Some(len)) => exact = acc.checked_add(len), + _ => exact = None, + } + } + if let Some(exact) = exact { + SizeHint::with_exact(exact) + } else { + let mut hint = SizeHint::new(); + hint.set_lower(lower); + if let Some(upper) = upper { + hint.set_upper(upper); + } + hint + } +} + +fn body_length_error(message: &'static str) -> WireError { + WireError::body(message, std::io::Error::other(message)) +} + pin_project! { #[derive(Debug)] pub struct ResponseBody { #[pin] - inner: http_body_util::combinators::BoxBody, + inner: BoxBody, } } @@ -240,7 +561,7 @@ impl ResponseBody { ) } - pub fn new(inner: http_body_util::combinators::BoxBody) -> Self { + pub fn new(inner: BoxBody) -> Self { Self { inner } } @@ -310,13 +631,91 @@ impl From for ResponseBody { #[cfg(test)] mod tests { - #[cfg(feature = "json")] + use std::pin::Pin; + use std::sync::{Arc, OnceLock}; + use std::task::{Context, Poll, Wake, Waker}; + use bytes::Bytes; - #[cfg(feature = "json")] + use futures_util::{stream, Stream}; + use http::HeaderMap; + use http_body::{Body, Frame, SizeHint}; use http_body_util::BodyExt; + use super::RequestBody; + use crate::{WireError, WireErrorKind}; + #[cfg(feature = "json")] - use super::{RequestBody, ResponseBody}; + use super::ResponseBody; + + fn noop_cx() -> Context<'static> { + struct Noop; + impl Wake for Noop { + fn wake(self: Arc) {} + } + static WAKER: OnceLock = OnceLock::new(); + let waker = WAKER.get_or_init(|| Waker::from(Arc::new(Noop))); + Context::from_waker(waker) + } + + async fn collect_data(body: RequestBody) -> Result { + Ok(body.collect().await?.to_bytes()) + } + + struct ExactDataThenTrailers { + data: Option, + trailers: Option, + } + + impl Body for ExactDataThenTrailers { + type Data = Bytes; + type Error = WireError; + + fn poll_frame( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + let this = self.get_mut(); + if let Some(data) = this.data.take() { + if data.is_empty() { + // Fall through to trailers so zero DATA + trailers is expressible. + } else { + return Poll::Ready(Some(Ok(Frame::data(data)))); + } + } + if let Some(trailers) = this.trailers.take() { + return Poll::Ready(Some(Ok(Frame::trailers(trailers)))); + } + Poll::Ready(None) + } + + fn size_hint(&self) -> SizeHint { + SizeHint::with_exact( + self.data + .as_ref() + .map(|data| data.len() as u64) + .unwrap_or(0), + ) + } + } + + struct PendingThen { + pending: bool, + inner: S, + } + + impl> + Unpin> stream::Stream for PendingThen { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.pending { + this.pending = false; + cx.waker().wake_by_ref(); + return Poll::Pending; + } + Pin::new(&mut this.inner).poll_next(cx) + } + } #[cfg(feature = "json")] #[tokio::test] @@ -344,4 +743,413 @@ mod tests { .expect("json"); assert_eq!(value["ok"], true); } + + #[test] + fn replayable_bytes_report_remaining_size_after_emission() { + let mut body = RequestBody::from_bytes(Bytes::from_static(b"hello")); + assert_eq!(body.content_length(), Some(5)); + assert_eq!(body.replayable_len(), Some(5)); + assert_eq!(body.size_hint().exact(), Some(5)); + + let mut cx = noop_cx(); + let frame = Pin::new(&mut body) + .poll_frame(&mut cx) + .ready() + .expect("ready") + .expect("data") + .expect("ok"); + assert_eq!( + frame.into_data().expect("data"), + Bytes::from_static(b"hello") + ); + assert_eq!(body.content_length(), Some(5)); + assert_eq!(body.replayable_len(), Some(5)); + assert_eq!(body.size_hint().exact(), Some(0)); + assert!(body.is_end_stream()); + } + + #[test] + fn known_length_one_shot_is_not_replayable() { + let body = RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"abc"))]), + 3, + ); + assert_eq!(body.content_length(), Some(3)); + assert_eq!(body.replayable_len(), None); + assert!(body.try_clone().is_none()); + assert_eq!(body.size_hint().exact(), Some(3)); + } + + #[tokio::test] + async fn concat_replays_after_partial_and_complete_consumption() { + let mut body = RequestBody::concat(vec![ + RequestBody::from_bytes(Bytes::from_static(b"ab")), + RequestBody::from_bytes(Bytes::from_static(b"cd")), + ]) + .expect("concat"); + assert_eq!(body.content_length(), Some(4)); + assert_eq!(body.replayable_len(), Some(4)); + + let mut cx = noop_cx(); + let first = Pin::new(&mut body) + .poll_frame(&mut cx) + .ready() + .expect("ready") + .expect("data") + .expect("ok"); + assert_eq!(first.into_data().expect("data"), Bytes::from_static(b"ab")); + + let mid_clone = body.try_clone().expect("clone after partial"); + assert_eq!( + collect_data(mid_clone).await.expect("mid"), + Bytes::from_static(b"abcd") + ); + + let rest = collect_data(body).await.expect("rest"); + assert_eq!(rest, Bytes::from_static(b"cd")); + + let complete = RequestBody::concat(vec![ + RequestBody::from_bytes(Bytes::from_static(b"ab")), + RequestBody::from_bytes(Bytes::from_static(b"cd")), + ]) + .expect("concat"); + let after = complete.try_clone().expect("clone before"); + assert_eq!( + collect_data(complete).await.expect("complete"), + Bytes::from_static(b"abcd") + ); + assert_eq!( + collect_data(after).await.expect("after"), + Bytes::from_static(b"abcd") + ); + } + + #[tokio::test] + async fn empty_concat_is_present_explicit_empty() { + let body = RequestBody::concat(Vec::new()).expect("empty concat"); + assert!(!body.is_absent()); + assert_eq!(body.content_length(), Some(0)); + assert_eq!(body.replayable_len(), Some(0)); + assert!(body.is_end_stream()); + assert_eq!(collect_data(body).await.expect("bytes"), Bytes::new()); + } + + #[test] + fn concat_rejects_length_overflow() { + let error = RequestBody::concat(vec![ + RequestBody::from_stream_with_length( + stream::empty::>(), + u64::MAX, + ), + RequestBody::from_stream_with_length(stream::empty::>(), 1), + ]) + .expect_err("overflow"); + assert_eq!(error.kind(), WireErrorKind::InvalidRequest); + assert!(error.message().contains("overflowed"), "error = {error}"); + } + + #[tokio::test] + async fn concat_rejects_trailers_and_does_not_emit_later_children() { + let trailing = ExactDataThenTrailers { + data: Some(Bytes::from_static(b"x")), + trailers: Some(HeaderMap::new()), + }; + let mut body = RequestBody::concat(vec![ + RequestBody::from_body(trailing), + RequestBody::from_bytes(Bytes::from_static(b"later")), + ]) + .expect("concat"); + assert_eq!(body.content_length(), None); + + let first = std::pin::pin!(&mut body) + .frame() + .await + .expect("data") + .expect("ok"); + assert_eq!(first.into_data().expect("data"), Bytes::from_static(b"x")); + + let error = std::pin::pin!(&mut body) + .frame() + .await + .expect("error frame") + .expect_err("trailers"); + assert_eq!(error.kind(), WireErrorKind::Body); + + assert!(std::pin::pin!(&mut body).frame().await.is_none()); + } + + #[tokio::test] + async fn concat_terminal_error_then_none() { + let mut body = RequestBody::concat(vec![ + RequestBody::from_stream(stream::iter(vec![Err(WireError::internal( + "source read failed", + std::io::Error::other("read"), + ))])), + RequestBody::from_bytes(Bytes::from_static(b"later")), + ]) + .expect("concat"); + + let error = std::pin::pin!(&mut body) + .frame() + .await + .expect("error frame") + .expect_err("read"); + assert_eq!(error.kind(), WireErrorKind::Internal); + assert!(std::pin::pin!(&mut body).frame().await.is_none()); + } + + #[tokio::test] + async fn concat_pending_then_data() { + let pending = RequestBody::from_stream(PendingThen { + pending: true, + inner: stream::iter(vec![Ok::(Bytes::from_static(b"go"))]), + }); + let body = RequestBody::concat(vec![ + pending, + RequestBody::from_bytes(Bytes::from_static(b"!")), + ]) + .expect("concat"); + assert_eq!( + collect_data(body).await.expect("bytes"), + Bytes::from_static(b"go!") + ); + } + + #[tokio::test] + async fn strict_length_rejects_early_eof() { + let body = RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"ab"))]), + 4, + ); + let error = collect_data(body).await.expect_err("early eof"); + assert_eq!(error.kind(), WireErrorKind::Body); + assert!( + error.message().contains("before declared"), + "error = {error}" + ); + } + + #[tokio::test] + async fn strict_length_rejects_oversized_chunk_before_forwarding() { + let body = RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"abcd"))]), + 2, + ); + let error = collect_data(body).await.expect_err("too long"); + assert_eq!(error.kind(), WireErrorKind::Body); + assert!(error.message().contains("exceeded"), "error = {error}"); + } + + #[tokio::test] + async fn strict_length_rejects_declared_zero_with_data() { + let body = RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"x"))]), + 0, + ); + let error = collect_data(body).await.expect_err("zero with data"); + assert_eq!(error.kind(), WireErrorKind::Body); + } + + #[tokio::test] + async fn strict_length_rejects_extra_chunk_after_declared_count() { + let body = RequestBody::from_stream_with_length( + stream::iter(vec![ + Ok::(Bytes::from_static(b"ab")), + Ok(Bytes::from_static(b"c")), + ]), + 2, + ); + let error = collect_data(body).await.expect_err("extra chunk"); + assert_eq!(error.kind(), WireErrorKind::Body); + assert!(error.message().contains("exceeded"), "error = {error}"); + } + + #[tokio::test] + async fn strict_length_requires_eof_before_composite_suffix() { + let payload = RequestBody::from_stream_with_length( + stream::iter(vec![ + Ok::(Bytes::from_static(b"ab")), + Ok(Bytes::from_static(b"c")), + ]), + 2, + ); + let mut body = RequestBody::concat(vec![ + payload, + RequestBody::from_bytes(Bytes::from_static(b"SUFFIX")), + ]) + .expect("concat"); + assert_eq!(body.content_length(), Some(8)); + assert_eq!(body.replayable_len(), None); + + let first = std::pin::pin!(&mut body) + .frame() + .await + .expect("data") + .expect("ok"); + assert_eq!(first.into_data().expect("data"), Bytes::from_static(b"ab")); + let error = std::pin::pin!(&mut body) + .frame() + .await + .expect("error frame") + .expect_err("extra"); + assert_eq!(error.kind(), WireErrorKind::Body); + assert!(std::pin::pin!(&mut body).frame().await.is_none()); + } + + #[tokio::test] + async fn strict_length_valid_eof_then_suffix() { + let payload = RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"ab"))]), + 2, + ); + let body = RequestBody::concat(vec![ + payload, + RequestBody::from_bytes(Bytes::from_static(b"CD")), + ]) + .expect("concat"); + assert_eq!( + collect_data(body).await.expect("bytes"), + Bytes::from_static(b"abCD") + ); + } + + #[test] + fn concat_rejects_started_child_but_accepts_fresh_clone() { + let mut body = RequestBody::from_bytes(Bytes::from_static(b"abc")); + let mut cx = noop_cx(); + let _ = Pin::new(&mut body).poll_frame(&mut cx); + + let error = RequestBody::concat(vec![body]).expect_err("started"); + assert_eq!(error.kind(), WireErrorKind::InvalidRequest); + + let mut original = RequestBody::from_bytes(Bytes::from_static(b"abc")); + let _ = Pin::new(&mut original).poll_frame(&mut cx); + let clone = original.try_clone().expect("clone"); + let concat = RequestBody::concat(vec![clone]).expect("fresh clone"); + assert_eq!(concat.content_length(), Some(3)); + } + + #[test] + fn from_body_exact_hint_does_not_establish_content_length() { + let body = RequestBody::from_body(ExactDataThenTrailers { + data: Some(Bytes::from_static(b"xyz")), + trailers: Some(HeaderMap::new()), + }); + assert_eq!(body.size_hint().exact(), None); + assert_eq!(body.size_hint().lower(), 3); + assert_eq!(body.content_length(), None); + assert_eq!(body.replayable_len(), None); + assert!(body.try_clone().is_none()); + } + + #[tokio::test] + async fn from_body_zero_data_still_forwards_trailers_outside_concat() { + let mut body = RequestBody::from_body(ExactDataThenTrailers { + data: Some(Bytes::new()), + trailers: Some(HeaderMap::new()), + }); + let frame = std::pin::pin!(&mut body) + .frame() + .await + .expect("trailers") + .expect("ok"); + assert!(frame.is_trailers()); + } + + #[test] + fn composite_is_end_stream_after_final_replayable_data_without_extra_poll() { + let mut body = + RequestBody::concat(vec![RequestBody::from_bytes(Bytes::from_static(b"ab"))]) + .expect("concat"); + assert!(!body.is_end_stream()); + let mut cx = noop_cx(); + let _ = Pin::new(&mut body).poll_frame(&mut cx); + assert!(body.is_end_stream()); + assert_eq!(body.size_hint().exact(), Some(0)); + assert_eq!(body.content_length(), Some(2)); + } + + #[test] + fn top_level_strict_length_waits_for_source_eof() { + let mut body = RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"ab"))]), + 2, + ); + let mut cx = noop_cx(); + let _ = Pin::new(&mut body).poll_frame(&mut cx); + assert_eq!(body.size_hint().exact(), Some(0)); + assert!(!body.is_end_stream()); + assert_eq!(body.content_length(), Some(2)); + assert!(matches!( + Pin::new(&mut body).poll_frame(&mut cx), + Poll::Ready(None) + )); + assert!(body.is_end_stream()); + } + + #[tokio::test] + async fn concat_still_waits_for_strict_eof_before_suffix() { + let payload = RequestBody::from_stream_with_length( + stream::iter(vec![ + Ok::(Bytes::from_static(b"ab")), + Ok(Bytes::from_static(b"c")), + ]), + 2, + ); + let mut body = RequestBody::concat(vec![ + payload, + RequestBody::from_bytes(Bytes::from_static(b"SUFFIX")), + ]) + .expect("concat"); + let first = std::pin::pin!(&mut body) + .frame() + .await + .expect("data") + .expect("ok"); + assert_eq!(first.into_data().expect("data"), Bytes::from_static(b"ab")); + assert!(!body.is_end_stream()); + let error = std::pin::pin!(&mut body) + .frame() + .await + .expect("error frame") + .expect_err("extra"); + assert_eq!(error.kind(), WireErrorKind::Body); + } + + struct EmptyForever; + + impl Stream for EmptyForever { + type Item = Result; + fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Some(Ok(Bytes::new()))) + } + } + + #[test] + fn strict_length_empty_frames_yield_pending_instead_of_spinning() { + let mut body = RequestBody::from_stream_with_length(EmptyForever, 4); + let mut cx = noop_cx(); + let mut polls = 0usize; + for _ in 0..8 { + polls += 1; + match Pin::new(&mut body).poll_frame(&mut cx) { + Poll::Pending => break, + Poll::Ready(_) => {} + } + } + assert!(polls < 8, "empty frames must not monopolize the executor"); + } + + trait PollExt { + fn ready(self) -> Option; + } + + impl PollExt for Poll { + fn ready(self) -> Option { + match self { + Poll::Ready(value) => Some(value), + Poll::Pending => None, + } + } + } } diff --git a/crates/openwire/Cargo.toml b/crates/openwire/Cargo.toml index 0e89e0f..8e1b9b3 100644 --- a/crates/openwire/Cargo.toml +++ b/crates/openwire/Cargo.toml @@ -31,6 +31,7 @@ brotli = ["compression-core", "async-compression/brotli"] zstd = ["compression-core", "async-compression/zstd"] compression-core = ["dep:async-compression", "async-compression/futures-io"] compression = ["gzip", "deflate", "brotli", "zstd"] +multipart = ["dep:getrandom", "dep:mime"] [dependencies] async-compression = { workspace = true, optional = true } @@ -50,6 +51,7 @@ hyper.workspace = true openwire-core.workspace = true openwire-tokio.workspace = true getrandom = { workspace = true, optional = true } +mime = { version = "0.3", default-features = false, optional = true } openwire-rustls = { workspace = true, optional = true } parking_lot.workspace = true pin-project-lite.workspace = true @@ -86,6 +88,10 @@ required-features = ["websocket"] name = "websocket_subprotocol" required-features = ["websocket"] +[[example]] +name = "post_multipart" +required-features = ["multipart"] + [[bench]] name = "perf_baseline" harness = false diff --git a/crates/openwire/examples/post_multipart.rs b/crates/openwire/examples/post_multipart.rs new file mode 100644 index 0000000..ee02bc3 --- /dev/null +++ b/crates/openwire/examples/post_multipart.rs @@ -0,0 +1,41 @@ +//! Multipart form upload. +//! +//! Requires `--features multipart`. +//! +//! For a large payload, replace the file part with a one-shot stream: +//! +//! ```ignore +//! Part::stream_with_length(stream, known_len) +//! .file_name("hello.txt") +//! .mime_str("text/plain; charset=utf-8")? +//! ``` +//! +//! A known length does not make the stream replayable. + +use bytes::Bytes; +use http::Request; +use openwire::{ + multipart::{Form, Part}, + Client, +}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let client = Client::builder().build()?; + let request = Form::new() + .text("description", "upload from OpenWire") + .part( + "file", + Part::bytes(Bytes::from_static(b"hello\n")) + .file_name("hello.txt") + .mime_str("text/plain; charset=utf-8")?, + ) + .into_request( + Request::builder() + .method("POST") + .uri("https://example.com/upload"), + )?; + let response = client.execute(request).await?; + println!("status = {}", response.status()); + Ok(()) +} diff --git a/crates/openwire/src/bridge.rs b/crates/openwire/src/bridge.rs index d56138f..2c8ba83 100644 --- a/crates/openwire/src/bridge.rs +++ b/crates/openwire/src/bridge.rs @@ -77,7 +77,7 @@ pub(crate) fn normalize_request( } normalize_host_header(request, strict_host_header)?; normalize_user_agent_header(request); - normalize_body_headers(request); + normalize_body_headers(request)?; #[cfg(feature = "compression-core")] let transparent_compression = crate::compression::normalize_request(request); #[cfg(not(feature = "compression-core"))] @@ -145,32 +145,39 @@ fn normalize_user_agent_header(request: &mut Request) { } } -fn normalize_body_headers(request: &mut Request) { +fn normalize_body_headers(request: &mut Request) -> Result<(), WireError> { let version = request.version(); let body_is_absent = request.body().is_absent(); - let replayable_len = request.body().replayable_len(); + let content_length = request.body().content_length(); let headers = request.headers_mut(); if body_is_absent { headers.remove(CONTENT_LENGTH); headers.remove(TRANSFER_ENCODING); - return; + return Ok(()); } - match replayable_len { + match content_length { Some(len) => { let value = HeaderValue::from_str(&len.to_string()) .expect("numeric content-length is always a valid header value"); headers.insert(CONTENT_LENGTH, value); headers.remove(TRANSFER_ENCODING); + Ok(()) } None => { + if version == Version::HTTP_10 { + return Err(WireError::invalid_request( + "HTTP/1.0 request cannot send a body of unknown length", + )); + } headers.remove(CONTENT_LENGTH); if uses_chunked_transfer_encoding(version) { headers.insert(TRANSFER_ENCODING, CHUNKED.clone()); } else { headers.remove(TRANSFER_ENCODING); } + Ok(()) } } } @@ -185,7 +192,7 @@ mod tests { use http::{Method, Request, Version}; use super::{normalize_body_headers, normalize_request}; - use crate::RequestBody; + use crate::{RequestBody, WireErrorKind}; #[test] fn synthesized_host_omits_default_http_port() { @@ -291,7 +298,7 @@ mod tests { .body(RequestBody::empty()) .expect("request"); - normalize_body_headers(&mut request); + normalize_body_headers(&mut request).expect("normalize"); assert!(request.headers().get(CONTENT_LENGTH).is_none()); assert!(request.headers().get(TRANSFER_ENCODING).is_none()); @@ -305,7 +312,7 @@ mod tests { .body(RequestBody::explicit_empty()) .expect("request"); - normalize_body_headers(&mut request); + normalize_body_headers(&mut request).expect("normalize"); assert_eq!( request @@ -390,7 +397,99 @@ mod tests { >())) .expect("request"); - normalize_body_headers(&mut request); + normalize_body_headers(&mut request).expect("normalize"); + + assert!(request.headers().get(CONTENT_LENGTH).is_none()); + assert_eq!( + request + .headers() + .get(TRANSFER_ENCODING) + .and_then(|value| value.to_str().ok()), + Some("chunked") + ); + } + + #[test] + fn known_length_one_shot_body_sets_content_length() { + let mut request = Request::builder() + .method(Method::POST) + .uri("http://example.com/") + .version(Version::HTTP_11) + .body(RequestBody::from_stream_with_length( + futures_util::stream::iter(vec![Ok::( + bytes::Bytes::from_static(b"abc"), + )]), + 3, + )) + .expect("request"); + + normalize_body_headers(&mut request).expect("normalize"); + + assert_eq!( + request + .headers() + .get(CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()), + Some("3") + ); + assert!(request.headers().get(TRANSFER_ENCODING).is_none()); + assert!(request.body().try_clone().is_none()); + } + + #[test] + fn http10_unknown_length_body_is_rejected() { + let mut request = Request::builder() + .method(Method::POST) + .uri("http://example.com/") + .version(Version::HTTP_10) + .body(RequestBody::from_stream(futures_util::stream::empty::< + Result, + >())) + .expect("request"); + + let error = normalize_body_headers(&mut request).expect_err("http/1.0 unknown length"); + assert_eq!(error.kind(), WireErrorKind::InvalidRequest); + assert!(error.message().contains("HTTP/1.0"), "error = {error}"); + assert!(request.headers().get(CONTENT_LENGTH).is_none()); + assert!(request.headers().get(TRANSFER_ENCODING).is_none()); + } + + #[test] + fn from_body_with_exact_size_hint_stays_chunked_on_http11() { + use http::HeaderMap; + use http_body::{Body, Frame, SizeHint}; + use std::pin::Pin; + use std::task::{Context, Poll}; + + struct ExactThenTrailers; + + impl Body for ExactThenTrailers { + type Data = bytes::Bytes; + type Error = crate::WireError; + + fn poll_frame( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + Poll::Ready(Some(Ok(Frame::trailers(HeaderMap::new())))) + } + + fn size_hint(&self) -> SizeHint { + SizeHint::with_exact(0) + } + } + + let mut request = Request::builder() + .method(Method::POST) + .uri("http://example.com/") + .version(Version::HTTP_11) + .body(RequestBody::from_body(ExactThenTrailers)) + .expect("request"); + + assert_eq!(request.body().size_hint().exact(), None); + assert_eq!(request.body().content_length(), None); + + normalize_body_headers(&mut request).expect("normalize"); assert!(request.headers().get(CONTENT_LENGTH).is_none()); assert_eq!( diff --git a/crates/openwire/src/lib.rs b/crates/openwire/src/lib.rs index a490c92..8b2be8f 100644 --- a/crates/openwire/src/lib.rs +++ b/crates/openwire/src/lib.rs @@ -13,6 +13,9 @@ mod sync_util; mod trace; mod transport; +#[cfg(feature = "multipart")] +pub mod multipart; + #[cfg(feature = "websocket")] pub mod websocket; diff --git a/crates/openwire/src/multipart.rs b/crates/openwire/src/multipart.rs new file mode 100644 index 0000000..12e86fb --- /dev/null +++ b/crates/openwire/src/multipart.rs @@ -0,0 +1,1513 @@ +//! Client-side `multipart/form-data` encoder. +//! +//! Encoding happens before [`Client::execute`](crate::Client::execute). The +//! result is an ordinary [`RequestBody`] plus a generated `Content-Type`. + +use std::pin::Pin; +use std::task::{Context, Poll}; + +use bytes::Bytes; +use futures_util::Stream; +use http::header::{CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING}; +use http::{HeaderValue, Request}; +use mime::Mime; +use openwire_core::{RequestBody, WireError}; +use pin_project_lite::pin_project; + +const BOUNDARY_ATTEMPTS: usize = 16; +const BOUNDARY_RANDOM_BYTES: usize = 24; +const EMPTY_CHUNK_SKIP_BUDGET: usize = 16; +const CRLF: &[u8] = b"\r\n"; +const DASH_DASH: &[u8] = b"--"; + +pub struct Form { + fields: Vec, +} + +struct FormField { + name: String, + part: Part, +} + +pub struct Part { + payload: PartPayload, + file_name: Option, + mime: Option, +} + +enum PartPayload { + Memory { + bytes: Bytes, + kind: MemoryKind, + }, + Stream { + inner: Pin> + Send + Sync>>, + length: Option, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MemoryKind { + Text, + Bytes, +} + +#[derive(Clone, Debug)] +struct ValidatedMime { + serialized: String, +} + +impl Form { + pub fn new() -> Self { + Self { fields: Vec::new() } + } + + pub fn text(self, name: impl Into, value: impl Into) -> Self { + self.part(name, Part::text(value)) + } + + pub fn part(mut self, name: impl Into, part: Part) -> Self { + self.fields.push(FormField { + name: name.into(), + part, + }); + self + } + + pub fn into_parts(self) -> Result<(HeaderValue, RequestBody), WireError> { + if self.fields.is_empty() { + return Err(WireError::invalid_request( + "multipart form must contain at least one part", + )); + } + + let mut encoded_fields = Vec::with_capacity(self.fields.len()); + for field in self.fields { + encoded_fields.push(EncodedField::from_form_field(field)?); + } + + let boundary = select_boundary(&encoded_fields)?; + let mut segments = Vec::new(); + for field in encoded_fields { + segments.push(RequestBody::from_bytes(part_preamble(&boundary, &field))); + segments.push(field.into_payload_body(&boundary)?); + segments.push(RequestBody::from_bytes(Bytes::from_static(CRLF))); + } + segments.push(RequestBody::from_bytes(closing_delimiter(&boundary))); + + let content_type = HeaderValue::from_str(&format!( + "multipart/form-data; boundary={boundary}" + )) + .map_err(|error| { + WireError::internal( + "generated multipart Content-Type is not a valid header value", + error, + ) + })?; + let body = RequestBody::concat(segments)?; + Ok((content_type, body)) + } + + #[cfg(test)] + fn into_parts_with_boundary( + self, + boundary: &str, + ) -> Result<(HeaderValue, RequestBody), WireError> { + let mut encoded_fields = Vec::with_capacity(self.fields.len()); + for field in self.fields { + encoded_fields.push(EncodedField::from_form_field(field)?); + } + let mut segments = Vec::new(); + for field in encoded_fields { + segments.push(RequestBody::from_bytes(part_preamble(boundary, &field))); + segments.push(field.into_payload_body(boundary)?); + segments.push(RequestBody::from_bytes(Bytes::from_static(CRLF))); + } + segments.push(RequestBody::from_bytes(closing_delimiter(boundary))); + let content_type = + HeaderValue::from_str(&format!("multipart/form-data; boundary={boundary}")) + .expect("header"); + Ok((content_type, RequestBody::concat(segments)?)) + } + + pub fn into_request( + self, + builder: http::request::Builder, + ) -> Result, WireError> { + let (content_type, body) = self.into_parts()?; + let mut request = builder.body(body)?; + if request.headers().contains_key(CONTENT_ENCODING) { + return Err(WireError::invalid_request( + "multipart request cannot reuse a pre-existing Content-Encoding", + )); + } + request.headers_mut().insert(CONTENT_TYPE, content_type); + request.headers_mut().remove(CONTENT_LENGTH); + request.headers_mut().remove(TRANSFER_ENCODING); + Ok(request) + } +} + +impl Default for Form { + fn default() -> Self { + Self::new() + } +} + +impl Part { + pub fn text(value: impl Into) -> Self { + Self { + payload: PartPayload::Memory { + bytes: Bytes::from(value.into()), + kind: MemoryKind::Text, + }, + file_name: None, + mime: None, + } + } + + pub fn bytes(value: impl Into) -> Self { + Self { + payload: PartPayload::Memory { + bytes: value.into(), + kind: MemoryKind::Bytes, + }, + file_name: None, + mime: None, + } + } + + pub fn stream(stream: S) -> Self + where + S: Stream> + Send + Sync + 'static, + E: Into + 'static, + { + Self { + payload: PartPayload::Stream { + inner: Box::pin(map_err_stream(stream)), + length: None, + }, + file_name: None, + mime: None, + } + } + + pub fn stream_with_length(stream: S, length: u64) -> Self + where + S: Stream> + Send + Sync + 'static, + E: Into + 'static, + { + Self { + payload: PartPayload::Stream { + inner: Box::pin(map_err_stream(stream)), + length: Some(length), + }, + file_name: None, + mime: None, + } + } + + pub fn file_name(mut self, name: impl Into) -> Self { + self.file_name = Some(name.into()); + self + } + + pub fn mime_str(mut self, value: &str) -> Result { + self.mime = Some(validate_mime(value, self.is_library_text())?); + Ok(self) + } + + fn is_library_text(&self) -> bool { + matches!( + self.payload, + PartPayload::Memory { + kind: MemoryKind::Text, + .. + } + ) + } +} + +struct EncodedField { + name: String, + file_name: Option, + content_type: String, + payload: EncodedPayload, +} + +enum EncodedPayload { + Memory(Bytes), + Stream { + inner: Pin> + Send + Sync>>, + length: Option, + }, +} + +impl EncodedField { + fn from_form_field(field: FormField) -> Result { + validate_token_text(&field.name, "multipart field name")?; + if let Some(file_name) = &field.part.file_name { + validate_token_text(file_name, "multipart file name")?; + } + + let content_type = match field.part.mime { + Some(mime) => mime.serialized, + None if field.part.is_library_text() => "text/plain; charset=utf-8".to_owned(), + None => "application/octet-stream".to_owned(), + }; + + let payload = match field.part.payload { + PartPayload::Memory { bytes, .. } => EncodedPayload::Memory(bytes), + PartPayload::Stream { inner, length } => EncodedPayload::Stream { inner, length }, + }; + + Ok(Self { + name: field.name, + file_name: field.part.file_name, + content_type, + payload, + }) + } + + fn into_payload_body(self, boundary: &str) -> Result { + match self.payload { + EncodedPayload::Memory(bytes) => Ok(RequestBody::from_bytes(bytes)), + EncodedPayload::Stream { inner, length } => { + let guarded = BoundaryGuardStream { + inner, + needle: dash_boundary(boundary), + ready: None, + hold: Vec::new(), + at_line_start: true, + }; + Ok(match length { + Some(length) => RequestBody::from_stream_with_length(guarded, length), + None => RequestBody::from_stream(guarded), + }) + } + } + } +} + +fn wrap_payload_read_error(error: WireError) -> WireError { + if error.kind() == openwire_core::WireErrorKind::Body { + error + } else { + WireError::body( + "multipart payload read failed", + std::io::Error::other(error.to_string()), + ) + } +} + +fn map_err_stream(stream: S) -> impl Stream> + Send + Sync +where + S: Stream> + Send + Sync + 'static, + E: Into + 'static, +{ + MapErrStream { inner: stream } +} + +pin_project! { + struct MapErrStream { + #[pin] + inner: S, + } +} + +impl Stream for MapErrStream +where + S: Stream>, + E: Into, +{ + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match self.project().inner.poll_next(cx) { + Poll::Pending => Poll::Pending, + Poll::Ready(None) => Poll::Ready(None), + Poll::Ready(Some(Ok(bytes))) => Poll::Ready(Some(Ok(bytes))), + Poll::Ready(Some(Err(error))) => { + Poll::Ready(Some(Err(wrap_payload_read_error(error.into())))) + } + } + } +} + +pin_project! { + struct BoundaryGuardStream { + #[pin] + inner: S, + needle: Vec, + ready: Option, + hold: Vec, + at_line_start: bool, + } +} + +impl Stream for BoundaryGuardStream +where + S: Stream>, +{ + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut this = self.project(); + let mut skips = 0usize; + loop { + if let Some(ready) = this.ready.take() { + if !ready.is_empty() { + return Poll::Ready(Some(Ok(ready))); + } + } + match this.inner.as_mut().poll_next(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + if this.hold.is_empty() { + return Poll::Ready(None); + } + if collision_in_pending(this.hold, this.needle, *this.at_line_start) { + return Poll::Ready(Some(Err(boundary_collision_error()))); + } + let rest = Bytes::from(std::mem::take(this.hold)); + return Poll::Ready(Some(Ok(rest))); + } + Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))), + Poll::Ready(Some(Ok(chunk))) => { + if chunk.is_empty() { + skips += 1; + if skips >= EMPTY_CHUNK_SKIP_BUDGET { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + continue; + } + match split_safe_chunk( + chunk, + this.hold, + this.ready, + this.needle, + this.at_line_start, + ) { + Ok(Some(safe)) => return Poll::Ready(Some(Ok(safe))), + Ok(None) => { + skips += 1; + if skips >= EMPTY_CHUNK_SKIP_BUDGET { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + continue; + } + Err(error) => return Poll::Ready(Some(Err(error))), + } + } + } + } + } +} + +fn select_boundary(fields: &[EncodedField]) -> Result { + for _ in 0..BOUNDARY_ATTEMPTS { + let boundary = random_boundary()?; + if memory_payloads_collide(fields, &boundary) { + continue; + } + return Ok(boundary); + } + Err(WireError::invalid_request( + "failed to select a multipart boundary that does not collide with in-memory payloads", + )) +} + +fn random_boundary() -> Result { + let mut bytes = [0u8; BOUNDARY_RANDOM_BYTES]; + getrandom::getrandom(&mut bytes).map_err(|error| { + WireError::internal( + "failed to generate multipart boundary", + std::io::Error::other(error.to_string()), + ) + })?; + Ok(hex_encode(&bytes)) +} + +fn hex_encode(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + out +} + +fn memory_payloads_collide(fields: &[EncodedField], boundary: &str) -> bool { + let needle = dash_boundary(boundary); + fields.iter().any(|field| match &field.payload { + EncodedPayload::Memory(bytes) => contains_dash_boundary(bytes, &needle), + EncodedPayload::Stream { .. } => false, + }) +} + +fn contains_dash_boundary(haystack: &[u8], needle: &[u8]) -> bool { + contains_dash_boundary_from(haystack, needle, true) +} + +fn contains_dash_boundary_from(haystack: &[u8], needle: &[u8], at_line_start: bool) -> bool { + if needle.is_empty() { + return false; + } + if at_line_start && haystack.starts_with(needle) { + return true; + } + haystack + .windows(2 + needle.len()) + .any(|window| window.starts_with(CRLF) && window[2..].starts_with(needle)) +} + +fn dash_boundary(boundary: &str) -> Vec { + let mut out = Vec::with_capacity(2 + boundary.len()); + out.extend_from_slice(DASH_DASH); + out.extend_from_slice(boundary.as_bytes()); + out +} + +fn closing_delimiter(boundary: &str) -> Bytes { + let mut out = Vec::with_capacity(6 + boundary.len()); + out.extend_from_slice(DASH_DASH); + out.extend_from_slice(boundary.as_bytes()); + out.extend_from_slice(DASH_DASH); + out.extend_from_slice(CRLF); + Bytes::from(out) +} + +fn part_preamble(boundary: &str, field: &EncodedField) -> Bytes { + let mut out = String::new(); + out.push_str("--"); + out.push_str(boundary); + out.push_str("\r\n"); + out.push_str("Content-Disposition: form-data; name="); + out.push_str("ed_string(&field.name)); + if let Some(file_name) = &field.file_name { + out.push_str("; filename="); + out.push_str("ed_string(&encode_filename(file_name))); + } + out.push_str("\r\nContent-Type: "); + out.push_str(&field.content_type); + out.push_str("\r\n\r\n"); + Bytes::from(out) +} + +fn quoted_string(value: &str) -> String { + let mut out = String::with_capacity(value.len() + 2); + out.push('"'); + for ch in value.chars() { + if ch == '"' || ch == '\\' { + out.push('\\'); + } + out.push(ch); + } + out.push('"'); + out +} + +fn encode_filename(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.as_bytes() { + match byte { + b'%' | 0x80..=0xff => { + out.push('%'); + out.push(HEX_UPPER[(byte >> 4) as usize] as char); + out.push(HEX_UPPER[(byte & 0x0f) as usize] as char); + } + _ => out.push(*byte as char), + } + } + out +} + +const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF"; + +fn validate_token_text(value: &str, label: &str) -> Result<(), WireError> { + if value.bytes().any(|byte| byte < 0x20 || byte == 0x7f) { + return Err(WireError::invalid_request(format!( + "{label} contains a forbidden control character" + ))); + } + Ok(()) +} + +fn validate_mime(value: &str, library_text: bool) -> Result { + if value.bytes().any(|byte| byte < 0x20 || byte == 0x7f) { + return Err(WireError::invalid_request( + "multipart media type contains a forbidden control character", + )); + } + // mime 0.3 does not support every quoted-pair. Validate only the essence + // there, and parse the complete parameter grammar below. + let essence = value.split(';').next().unwrap_or(value).trim(); + let parsed: Mime = essence.parse().map_err(|error| { + WireError::invalid_request(format!("multipart media type is invalid: {error}")) + })?; + if parsed.type_() == mime::STAR || parsed.subtype() == mime::STAR { + return Err(WireError::invalid_request( + "multipart media type must be a concrete type, not a range", + )); + } + if parsed.type_() == mime::MULTIPART { + return Err(WireError::invalid_request( + "nested multipart media types are not supported", + )); + } + + let params = parse_mime_parameters(value)?; + for (_name, param_value) in ¶ms { + if param_value.bytes().any(|byte| byte < 0x20 || byte == 0x7f) { + return Err(WireError::invalid_request( + "multipart media type parameter contains a forbidden control character", + )); + } + } + + if library_text { + if let Some((_, charset)) = params + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("charset")) + { + if !charset.eq_ignore_ascii_case("utf-8") { + return Err(WireError::invalid_request( + "text part Content-Type charset must be utf-8", + )); + } + } + } + + let is_text_plain = parsed.type_() == mime::TEXT && parsed.subtype() == mime::PLAIN; + if library_text && is_text_plain && !params.iter().any(|(name, _)| name == "charset") { + return Ok(ValidatedMime { + serialized: format_media_type_with_utf8( + parsed.type_().as_str(), + parsed.subtype().as_str(), + ¶ms, + ), + }); + } + + Ok(ValidatedMime { + serialized: format_media_type(parsed.type_().as_str(), parsed.subtype().as_str(), ¶ms), + }) +} + +fn parse_mime_parameters(value: &str) -> Result, WireError> { + let Some((_, rest)) = value.split_once(';') else { + return Ok(Vec::new()); + }; + let bytes = rest.as_bytes(); + let mut index = 0usize; + let mut params = Vec::new(); + while index < bytes.len() { + while index < bytes.len() + && (bytes[index] == b' ' || bytes[index] == b'\t' || bytes[index] == b';') + { + index += 1; + } + if index >= bytes.len() { + break; + } + let name_start = index; + while index < bytes.len() && is_mime_token_byte(bytes[index]) { + index += 1; + } + if index == name_start { + return Err(WireError::invalid_request( + "multipart media type parameter name is invalid", + )); + } + let name = rest[name_start..index].to_ascii_lowercase(); + if params.iter().any(|(existing, _)| existing == &name) { + return Err(WireError::invalid_request( + "multipart media type has a duplicate parameter name", + )); + } + if index >= bytes.len() || bytes[index] != b'=' { + return Err(WireError::invalid_request( + "multipart media type parameter is missing a value", + )); + } + index += 1; + let value = if index < bytes.len() && bytes[index] == b'"' { + index += 1; + let mut decoded = Vec::new(); + loop { + if index == bytes.len() { + return Err(WireError::invalid_request( + "multipart media type quoted-string is not closed", + )); + } + match bytes[index] { + b'\\' => { + index += 1; + let Some(&escaped) = bytes.get(index) else { + return Err(WireError::invalid_request( + "multipart media type quoted-string is truncated", + )); + }; + decoded.push(escaped); + index += 1; + } + b'"' => { + index += 1; + break; + } + byte => { + decoded.push(byte); + index += 1; + } + } + } + String::from_utf8(decoded).map_err(|error| { + WireError::invalid_request(format!( + "multipart media type parameter is not valid UTF-8: {error}" + )) + })? + } else { + let value_start = index; + while index < bytes.len() && is_mime_token_byte(bytes[index]) { + index += 1; + } + if index == value_start { + return Err(WireError::invalid_request( + "multipart media type parameter value must be a token or quoted-string", + )); + } + rest[value_start..index].to_owned() + }; + while index < bytes.len() && bytes[index] == b' ' { + index += 1; + } + if index < bytes.len() && bytes[index] != b';' { + return Err(WireError::invalid_request( + "multipart media type parameters must be separated by semicolons", + )); + } + params.push((name, value)); + } + Ok(params) +} + +fn format_media_type(type_: &str, subtype: &str, params: &[(String, String)]) -> String { + let mut out = format!("{type_}/{subtype}"); + for (name, value) in params { + out.push_str("; "); + out.push_str(name); + out.push('='); + out.push_str(&format_mime_parameter_value(value)); + } + out +} + +fn format_media_type_with_utf8(type_: &str, subtype: &str, params: &[(String, String)]) -> String { + let mut out = format!("{type_}/{subtype}; charset=utf-8"); + for (name, value) in params { + if name.eq_ignore_ascii_case("charset") { + continue; + } + out.push_str("; "); + out.push_str(name); + out.push('='); + out.push_str(&format_mime_parameter_value(value)); + } + out +} + +fn format_mime_parameter_value(value: &str) -> String { + if is_mime_token(value) { + value.to_owned() + } else { + quoted_string(value) + } +} + +fn is_mime_token(value: &str) -> bool { + !value.is_empty() && value.bytes().all(is_mime_token_byte) +} + +fn is_mime_token_byte(byte: u8) -> bool { + matches!(byte, + b'0'..=b'9' + | b'A'..=b'Z' + | b'a'..=b'z' + | b'!' + | b'#' + | b'$' + | b'%' + | b'&' + | b'\'' + | b'*' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'{' + | b'|' + | b'}' + | b'~' + ) +} + +fn split_safe_chunk( + chunk: Bytes, + hold: &mut Vec, + ready: &mut Option, + needle: &[u8], + at_line_start: &mut bool, +) -> Result, WireError> { + let mut previous = std::mem::take(hold); + let previous_len = previous.len(); + let total = previous_len + chunk.len(); + // Treat the retained prefix and source chunk as one view. Only unresolved + // bytes are copied; the large safe chunk region stays a Bytes slice. + let byte_at = |index: usize| { + if index < previous_len { + previous[index] + } else { + chunk[index - previous_len] + } + }; + let mut safe_end = total; + for start in 0..total { + let is_line_start = (start == 0 && *at_line_start) + || (start >= 2 && byte_at(start - 2) == b'\r' && byte_at(start - 1) == b'\n'); + if !is_line_start { + continue; + } + let available = needle.len().min(total - start); + if (0..available).all(|offset| byte_at(start + offset) == needle[offset]) { + if available == needle.len() { + return Err(boundary_collision_error()); + } + safe_end = start; + break; + } + } + if safe_end == total && total > 0 && byte_at(total - 1) == b'\r' { + safe_end -= 1; + } + if safe_end > 0 { + *at_line_start = + safe_end >= 2 && byte_at(safe_end - 2) == b'\r' && byte_at(safe_end - 1) == b'\n'; + } + hold.extend((safe_end..total).map(byte_at)); + debug_assert!(hold.len() < needle.len()); + + let safe_chunk = chunk.slice(..safe_end.saturating_sub(previous_len)); + previous.truncate(safe_end.min(previous_len)); + if previous.is_empty() { + Ok((!safe_chunk.is_empty()).then_some(safe_chunk)) + } else { + if !safe_chunk.is_empty() { + *ready = Some(safe_chunk); + } + Ok(Some(Bytes::from(previous))) + } +} + +fn collision_in_pending(pending: &[u8], needle: &[u8], at_line_start: bool) -> bool { + contains_dash_boundary_from(pending, needle, at_line_start) +} + +fn boundary_collision_error() -> WireError { + WireError::body( + "multipart payload collided with the selected boundary", + std::io::Error::other("multipart boundary collision"), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use futures_util::stream; + use http::Method; + use http_body_util::BodyExt; + use openwire_core::WireErrorKind; + use std::pin::Pin; + use std::sync::{Arc, Mutex, OnceLock}; + use std::task::{Context, Poll, Wake, Waker}; + + use http_body::Body; + + fn collect(body: RequestBody) -> Bytes { + futures_executor_collect(body) + } + + fn futures_executor_collect(body: RequestBody) -> Bytes { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(async { body.collect().await.expect("body").to_bytes() }) + } + + fn collect_result(body: RequestBody) -> Result { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(async { Ok(body.collect().await?.to_bytes()) }) + } + + fn parse_boundary(content_type: &HeaderValue) -> String { + let value = content_type.to_str().expect("ascii"); + let prefix = "multipart/form-data; boundary="; + assert!(value.starts_with(prefix), "content-type = {value}"); + value[prefix.len()..].to_owned() + } + + fn expected_form(boundary: &str, parts: &[(&str, Option<&str>, &str, &[u8])]) -> Bytes { + let mut out = Vec::new(); + for (name, file_name, content_type, payload) in parts { + out.extend_from_slice(DASH_DASH); + out.extend_from_slice(boundary.as_bytes()); + out.extend_from_slice(CRLF); + out.extend_from_slice(b"Content-Disposition: form-data; name="); + out.extend_from_slice(quoted_string(name).as_bytes()); + if let Some(file_name) = file_name { + out.extend_from_slice(b"; filename="); + out.extend_from_slice(quoted_string(&encode_filename(file_name)).as_bytes()); + } + out.extend_from_slice(b"\r\nContent-Type: "); + out.extend_from_slice(content_type.as_bytes()); + out.extend_from_slice(b"\r\n\r\n"); + out.extend_from_slice(payload); + out.extend_from_slice(CRLF); + } + out.extend_from_slice(&closing_delimiter(boundary)); + Bytes::from(out) + } + + #[test] + fn encodes_text_and_bytes_with_rfc_shape() { + let (content_type, body) = Form::new() + .text("description", "upload from OpenWire") + .part( + "file", + Part::bytes(Bytes::from_static(b"hello\n")) + .file_name("hello.txt") + .mime_str("text/plain; charset=utf-8") + .expect("mime"), + ) + .into_parts() + .expect("form"); + let boundary = parse_boundary(&content_type); + assert_eq!(boundary.len(), 48); + assert!(body.try_clone().is_some()); + assert_eq!(body.content_length(), Some(body.replayable_len().unwrap())); + let encoded = collect(body); + assert_eq!( + encoded, + expected_form( + &boundary, + &[ + ( + "description", + None, + "text/plain; charset=utf-8", + b"upload from OpenWire", + ), + ( + "file", + Some("hello.txt"), + "text/plain; charset=utf-8", + b"hello\n", + ), + ], + ) + ); + assert!(encoded.windows(2).any(|window| window == CRLF)); + let close = closing_delimiter(&boundary); + assert!( + encoded.ends_with(close.as_ref()), + "closing delimiter must be --boundary--CRLF with no padding" + ); + assert!( + !encoded.windows(3).any(|window| window == b"-- "), + "delimiter must not include padding spaces" + ); + } + + #[test] + fn keeps_duplicate_fields_in_insertion_order() { + let (content_type, body) = Form::new() + .text("tag", "one") + .text("tag", "two") + .into_parts() + .expect("form"); + let boundary = parse_boundary(&content_type); + assert_eq!( + collect(body), + expected_form( + &boundary, + &[ + ("tag", None, "text/plain; charset=utf-8", b"one"), + ("tag", None, "text/plain; charset=utf-8", b"two"), + ], + ) + ); + } + + #[test] + fn allows_empty_values_and_zero_byte_files() { + let (content_type, body) = Form::new() + .text("empty", "") + .part("file", Part::bytes(Bytes::new()).file_name("empty.bin")) + .into_parts() + .expect("form"); + let boundary = parse_boundary(&content_type); + assert_eq!( + collect(body), + expected_form( + &boundary, + &[ + ("empty", None, "text/plain; charset=utf-8", b""), + ("file", Some("empty.bin"), "application/octet-stream", b"",), + ], + ) + ); + } + + #[test] + fn escapes_quotes_and_backslashes_and_encodes_non_ascii_filenames() { + let (content_type, body) = Form::new() + .part( + r#"na"me\z"#, + Part::bytes(Bytes::from_static(b"x")).file_name("caf%é.txt"), + ) + .into_parts() + .expect("form"); + let encoded = collect(body); + let text = String::from_utf8(encoded.to_vec()).expect("utf8"); + assert!(text.contains(r#"name="na\"me\\z""#), "{text}"); + assert!(text.contains(r#"filename="caf%25%C3%A9.txt""#), "{text}"); + assert!(!text.contains("filename*="), "{text}"); + let _ = content_type; + } + + #[test] + fn rejects_control_characters_in_names() { + let error = Form::new() + .text("bad\nname", "x") + .into_parts() + .expect_err("control"); + assert_eq!(error.kind(), WireErrorKind::InvalidRequest); + } + + #[test] + fn rejects_empty_form() { + let error = Form::new().into_parts().expect_err("empty"); + assert_eq!(error.kind(), WireErrorKind::InvalidRequest); + } + + #[test] + fn rejects_media_ranges_duplicates_nested_multipart_and_charset_conflicts() { + assert_eq!( + Part::bytes(Bytes::from_static(b"x")) + .mime_str("text/*") + .map(|_| ()) + .unwrap_err() + .kind(), + WireErrorKind::InvalidRequest + ); + assert_eq!( + Part::bytes(Bytes::from_static(b"x")) + .mime_str("text/plain; charset=utf-8; charset=utf-8") + .map(|_| ()) + .unwrap_err() + .kind(), + WireErrorKind::InvalidRequest + ); + assert_eq!( + Part::bytes(Bytes::from_static(b"x")) + .mime_str("multipart/mixed; boundary=abc") + .map(|_| ()) + .unwrap_err() + .kind(), + WireErrorKind::InvalidRequest + ); + assert_eq!( + Part::text("hi") + .mime_str("text/plain; charset=iso-8859-1") + .map(|_| ()) + .unwrap_err() + .kind(), + WireErrorKind::InvalidRequest + ); + let labeled = Part::text("hi") + .mime_str("text/plain") + .expect("adds charset"); + let (_, body) = Form::new().part("a", labeled).into_parts().expect("form"); + let encoded = collect(body); + let text = String::from_utf8(encoded.to_vec()).expect("utf8"); + assert!( + text.contains("Content-Type: text/plain; charset=utf-8"), + "{text}" + ); + assert_eq!( + Part::text("中文") + .mime_str("text/html; charset=iso-8859-1") + .map(|_| ()) + .unwrap_err() + .kind(), + WireErrorKind::InvalidRequest + ); + let quoted = Part::text("hi") + .mime_str(r#"text/plain; note="a;b""#) + .expect("quoted param"); + let (_, body) = Form::new().part("a", quoted).into_parts().expect("form"); + let encoded = collect(body); + let text = String::from_utf8(encoded.to_vec()).expect("utf8"); + assert!( + text.contains(r#"Content-Type: text/plain; charset=utf-8; note="a;b""#), + "{text}" + ); + let content_type = text + .lines() + .find(|line| line.starts_with("Content-Type: ")) + .expect("content-type") + .trim_start_matches("Content-Type: "); + content_type.parse::().expect("round-trip"); + assert!(Part::bytes(Bytes::from_static(b"x")) + .mime_str(r#"application/octet-stream; x="a;x=b""#) + .map(|_| ()) + .is_ok()); + } + + #[test] + fn inline_boundary_bytes_are_not_collisions() { + let payload = Bytes::from(format!("{}--fixed-boundary", "a".repeat(100))); + let (content_type, body) = Form { + fields: vec![FormField { + name: "file".into(), + part: Part { + payload: PartPayload::Stream { + inner: Box::pin(stream::iter(vec![Ok(payload.clone())])), + length: None, + }, + file_name: None, + mime: None, + }, + }], + } + .into_parts_with_boundary("fixed-boundary") + .expect("form"); + let encoded = collect(body); + assert!(encoded + .windows(payload.len()) + .any(|window| window == payload.as_ref())); + let _ = content_type; + } + + async fn encode_chunked_payload( + chunks: Vec, + boundary: &str, + ) -> (Vec, Option) { + use futures_util::StreamExt; + + let source = stream::iter(chunks).then(|chunk| async move { + tokio::task::yield_now().await; + Ok::<_, WireError>(chunk) + }); + let (_, mut body) = Form::new() + .part("file", Part::stream(source)) + .into_parts_with_boundary(boundary) + .expect("form"); + let mut output = Vec::new(); + while let Some(frame) = body.frame().await { + match frame { + Ok(frame) => output.extend_from_slice(&frame.into_data().expect("DATA")), + Err(error) => return (output, Some(error)), + } + } + (output, None) + } + + #[tokio::test] + async fn boundary_collisions_are_rejected_across_all_three_way_splits() { + // RFC 2046 §5.1.1: dash-boundary cannot prefix a payload line. + let boundary = "review-boundary"; + let forbidden = format!("--{boundary}"); + for prefix in ["", "safe\r\n"] { + let payload = Bytes::from(format!("{prefix}{forbidden}")); + for first in 1..payload.len() { + for second in first + 1..payload.len() { + let chunks = vec![ + payload.slice(..first), + Bytes::new(), + payload.slice(first..second), + payload.slice(second..), + ]; + let (wire, error) = encode_chunked_payload(chunks, boundary).await; + assert!(error.is_some(), "accepted collision at {first}/{second}"); + let payload_start = wire + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("part headers") + + 4; + assert!( + !wire[payload_start..] + .windows(forbidden.len()) + .any(|window| window == forbidden.as_bytes()), + "emitted complete collision at {first}/{second}" + ); + assert!(!wire.ends_with(format!("\r\n--{boundary}--\r\n").as_bytes())); + } + } + let chunks = payload + .iter() + .map(|byte| Bytes::copy_from_slice(&[*byte])) + .collect(); + assert!(encode_chunked_payload(chunks, boundary).await.1.is_some()); + } + } + + #[tokio::test] + async fn safe_stream_payload_is_preserved_across_all_three_way_splits() { + let boundary = "review-boundary"; + for payload in [ + Bytes::from_static(b"inline--review-boundary"), + Bytes::from_static(b"safe\r\n--review-boundarX\r"), + Bytes::from_static(b"\0a\r\nb\rc\nd\xff"), + ] { + for first in 1..payload.len() { + for second in first + 1..payload.len() { + let chunks = vec![ + payload.slice(..first), + payload.slice(first..second), + payload.slice(second..), + ]; + let (wire, error) = encode_chunked_payload(chunks, boundary).await; + assert!(error.is_none(), "rejected safe payload at {first}/{second}"); + let mut expected = format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"\r\nContent-Type: application/octet-stream\r\n\r\n" + ).into_bytes(); + expected.extend_from_slice(&payload); + expected.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + assert_eq!(wire, expected, "changed payload at {first}/{second}"); + } + } + } + } + + #[test] + fn mime_parameters_support_quoted_pairs_and_reject_incomplete_syntax() { + // RFC 2045 §5.1 and RFC 9110 §5.6.4: quoted-pair is part of quoted-string. + for (input, expected) in [ + ( + r#"text/plain; note="a\"b""#, + r#"text/plain; charset=utf-8; note="a\"b""#, + ), + ( + r#"text/plain; note="a\\b""#, + r#"text/plain; charset=utf-8; note="a\\b""#, + ), + ( + r#"text/plain; note="""#, + r#"text/plain; charset=utf-8; note="""#, + ), + ( + r#"text/plain; note="a\;b""#, + r#"text/plain; charset=utf-8; note="a;b""#, + ), + ] { + let part = Part::text("hello") + .mime_str(input) + .expect("valid MIME parameter"); + assert_eq!(part.mime.expect("media type").serialized, expected); + } + for input in [ + "text/plain; note=", + "text/plain; note=\"unterminated", + "text/plain; note=\"trailing\\", + "text/plain; note=\"ok\"extra=x", + "text/plain; note=\"ok\"other=\"value\"", + "text/plain; note =value", + "text/plain; note= value", + "text/plain; Note=one; note=two", + ] { + assert!( + Part::text("hello").mime_str(input).is_err(), + "accepted {input}" + ); + } + } + + #[test] + fn boundary_guard_slices_large_safe_chunks_and_retains_only_candidate_bytes() { + let needle = dash_boundary("review-boundary"); + let mut hold = b"--".to_vec(); + let mut ready = None; + let mut at_line_start = true; + let chunk = Bytes::from(vec![b'a'; 4 * 1024 * 1024]); + let original_pointer = chunk.as_ptr(); + let released = split_safe_chunk(chunk, &mut hold, &mut ready, &needle, &mut at_line_start) + .expect("safe payload") + .expect("released prefix"); + assert_eq!(released.as_ref(), b"--"); + let safe_chunk = ready.expect("zero-copy safe chunk"); + assert_eq!(safe_chunk.as_ptr(), original_pointer); + assert_eq!(safe_chunk.len(), 4 * 1024 * 1024); + assert!(hold.is_empty()); + assert!(hold.capacity() < needle.len()); + } + + #[test] + fn into_request_replaces_content_type_and_clears_framing() { + let request = Form::new() + .text("a", "b") + .into_request( + Request::builder() + .method(Method::POST) + .uri("https://example.com/upload") + .header(CONTENT_TYPE, "application/json") + .header(CONTENT_LENGTH, "999") + .header(TRANSFER_ENCODING, "chunked"), + ) + .expect("request"); + let values: Vec<_> = request + .headers() + .get_all(CONTENT_TYPE) + .iter() + .cloned() + .collect(); + assert_eq!(values.len(), 1); + assert!(values[0] + .to_str() + .expect("ascii") + .starts_with("multipart/form-data; boundary=")); + assert!(request.headers().get(CONTENT_LENGTH).is_none()); + assert!(request.headers().get(TRANSFER_ENCODING).is_none()); + } + + #[test] + fn into_request_rejects_content_encoding() { + let error = Form::new() + .text("a", "b") + .into_request( + Request::builder() + .method(Method::POST) + .uri("https://example.com/upload") + .header(CONTENT_ENCODING, "gzip"), + ) + .expect_err("encoding"); + assert_eq!(error.kind(), WireErrorKind::InvalidRequest); + } + + #[test] + fn stream_part_is_not_replayable_and_can_declare_length() { + let (_, body) = Form::new() + .part( + "file", + Part::stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"xyz"))]), + 3, + ), + ) + .into_parts() + .expect("form"); + assert!(body.try_clone().is_none()); + assert!(body.content_length().is_some()); + assert_eq!(body.replayable_len(), None); + let encoded = collect(body); + assert!(encoded.windows(3).any(|window| window == b"xyz")); + assert!(encoded.ends_with(b"--\r\n") || encoded.windows(4).any(|w| w == b"--\r\n")); + } + + #[test] + fn stream_collision_is_rejected_before_complete_prefix() { + let collision = b"--collide-boundary"; + let (_, body) = Form { + fields: vec![FormField { + name: "file".into(), + part: Part { + payload: PartPayload::Stream { + inner: Box::pin(stream::iter(vec![ + Ok(Bytes::from_static(b"ok\r\n")), + Ok(Bytes::from_static(collision)), + ])), + length: None, + }, + file_name: None, + mime: None, + }, + }], + } + .into_parts_with_boundary("collide-boundary") + .expect("form"); + let error = collect_result(body).expect_err("collision"); + assert_eq!(error.kind(), WireErrorKind::Body); + } + + #[test] + fn payload_crlf_bytes_are_preserved() { + let (content_type, body) = Form::new() + .part("file", Part::bytes(Bytes::from_static(b"a\r\nb\nc"))) + .into_parts() + .expect("form"); + let boundary = parse_boundary(&content_type); + let encoded = collect(body); + assert_eq!( + encoded, + expected_form( + &boundary, + &[("file", None, "application/octet-stream", b"a\r\nb\nc",)], + ) + ); + } + + #[test] + fn memory_payload_matching_boundary_selects_another_candidate() { + let payload = Bytes::from_static(b"placeholder"); + let (content_type, body) = Form::new() + .part("file", Part::bytes(payload.clone())) + .into_parts() + .expect("form"); + let boundary = parse_boundary(&content_type); + let encoded = collect(body); + assert!(!contains_dash_boundary( + payload.as_ref(), + &dash_boundary(&boundary) + )); + assert!(encoded + .windows(payload.len()) + .any(|window| window == payload.as_ref())); + } + + #[test] + fn prefix_only_match_is_held_across_chunks() { + let reads = Arc::new(Mutex::new(0usize)); + let stream_reads = reads.clone(); + let stream = futures_util::stream::unfold(0u8, move |step| { + let stream_reads = stream_reads.clone(); + async move { + *stream_reads.lock().expect("reads") += 1; + match step { + 0 => Some((Ok(Bytes::from_static(b"--coll")), 1)), + 1 => Some((Ok(Bytes::from_static(b"ide-boundary")), 2)), + _ => None, + } + } + }); + let (_, body) = Form { + fields: vec![FormField { + name: "file".into(), + part: Part { + payload: PartPayload::Stream { + inner: Box::pin(stream), + length: None, + }, + file_name: None, + mime: None, + }, + }], + } + .into_parts_with_boundary("collide-boundary") + .expect("form"); + let error = collect_result(body).expect_err("collision"); + assert_eq!(error.kind(), WireErrorKind::Body); + assert!(*reads.lock().expect("reads") >= 2); + } + + struct PendingOnce { + pending: bool, + inner: S, + } + + impl> + Unpin> Stream for PendingOnce { + type Item = Result; + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.pending { + this.pending = false; + cx.waker().wake_by_ref(); + return Poll::Pending; + } + Pin::new(&mut this.inner).poll_next(cx) + } + } + + #[test] + fn pending_poll_does_not_drop_prefix_state() { + let stream = PendingOnce { + pending: true, + inner: stream::iter(vec![ + Ok(Bytes::from_static(b"--x")), + Ok(Bytes::from_static(b"safe")), + ]), + }; + let (_, body) = Form { + fields: vec![FormField { + name: "file".into(), + part: Part { + payload: PartPayload::Stream { + inner: Box::pin(stream), + length: None, + }, + file_name: None, + mime: None, + }, + }], + } + .into_parts_with_boundary("zzzzzzzz") + .expect("form"); + let encoded = collect(body); + assert!( + encoded.windows(6).any(|window| window == b"--xsafe") + || encoded.windows(4).any(|window| window == b"safe") + ); + } + + struct EmptyForever; + + impl Stream for EmptyForever { + type Item = Result; + fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Some(Ok(Bytes::new()))) + } + } + + #[test] + fn empty_chunks_yield_pending_instead_of_spinning() { + let (_, mut body) = Form { + fields: vec![FormField { + name: "file".into(), + part: Part { + payload: PartPayload::Stream { + inner: Box::pin(EmptyForever), + length: None, + }, + file_name: None, + mime: None, + }, + }], + } + .into_parts_with_boundary("zzzzzzzz") + .expect("form"); + struct Noop; + impl Wake for Noop { + fn wake(self: Arc) {} + } + static WAKER: OnceLock = OnceLock::new(); + let waker = WAKER.get_or_init(|| Waker::from(Arc::new(Noop))); + let mut cx = Context::from_waker(waker); + let mut polls = 0usize; + for _ in 0..32 { + polls += 1; + match Pin::new(&mut body).poll_frame(&mut cx) { + Poll::Pending => break, + Poll::Ready(Some(Ok(_))) => {} + Poll::Ready(_) => break, + } + } + assert!(polls < 32, "empty chunks must not monopolize the executor"); + } +} diff --git a/crates/openwire/src/policy/follow_up.rs b/crates/openwire/src/policy/follow_up.rs index 32e946a..6738c96 100644 --- a/crates/openwire/src/policy/follow_up.rs +++ b/crates/openwire/src/policy/follow_up.rs @@ -3,8 +3,9 @@ use std::task::{Context, Poll}; use std::time::SystemTime; use http::header::{ - AUTHORIZATION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, EXPECT, HOST, LOCATION, - RETRY_AFTER, SET_COOKIE, TRANSFER_ENCODING, + AUTHORIZATION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_LOCATION, + CONTENT_TYPE, COOKIE, EXPECT, HOST, LAST_MODIFIED, LOCATION, RETRY_AFTER, SET_COOKIE, + TRANSFER_ENCODING, }; use http::{HeaderMap, Method, Request, Response, StatusCode, Uri, Version}; use openwire_core::{ @@ -653,34 +654,42 @@ impl RequestSnapshot { selected_proxy: Option, ) -> Result>, WireError> { let same_origin = same_origin(&self.uri, &next_uri)?; - let should_switch_to_get = matches!( - status, - StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER - ) && self.method != Method::GET - && self.method != Method::HEAD; - - let preserve_body = matches!( - status, - StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT - ); - - let body = if preserve_body { - let Some(body) = self.body else { - return Ok(None); - }; - body - } else if should_switch_to_get { - RequestBody::absent() - } else { - self.body.unwrap_or_else(RequestBody::absent) - }; - - let method = if preserve_body { - self.method - } else if should_switch_to_get { - Method::GET - } else { - self.method + let (method, body, switch_to_get) = match status { + StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => { + let Some(body) = self.body else { + return Ok(None); + }; + (self.method, body, false) + } + StatusCode::SEE_OTHER if self.method == Method::HEAD => ( + Method::HEAD, + self.body.unwrap_or_else(RequestBody::absent), + false, + ), + StatusCode::SEE_OTHER => (Method::GET, RequestBody::absent(), true), + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND if self.method == Method::POST => { + (Method::GET, RequestBody::absent(), true) + } + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND + if self.method == Method::GET || self.method == Method::HEAD => + { + ( + self.method, + self.body.unwrap_or_else(RequestBody::absent), + false, + ) + } + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => { + let Some(body) = self.body else { + return Ok(None); + }; + (self.method, body, false) + } + _ => ( + self.method, + self.body.unwrap_or_else(RequestBody::absent), + false, + ), }; let headers = self.headers.ok_or_else(|| { @@ -694,12 +703,8 @@ impl RequestSnapshot { if !same_origin { strip_sensitive_cross_origin_headers(&mut headers); } - if should_switch_to_get { - headers.remove(CONTENT_LENGTH); - headers.remove(CONTENT_TYPE); - headers.remove(CONTENT_ENCODING); - headers.remove(TRANSFER_ENCODING); - headers.remove(EXPECT); + if switch_to_get { + strip_content_headers(&mut headers); } let extensions = self.extensions.ok_or_else(|| { @@ -839,6 +844,20 @@ fn same_origin(left: &Uri, right: &Uri) -> Result { /// `Proxy-Authorization` is intentionally preserved so sticky HTTP forward /// proxies can continue to authenticate after a redirect; transport clears it /// when the selected proxy endpoint changes. +fn strip_content_headers(headers: &mut HeaderMap) { + headers.remove(CONTENT_LENGTH); + headers.remove(CONTENT_TYPE); + headers.remove(CONTENT_ENCODING); + headers.remove(TRANSFER_ENCODING); + headers.remove(EXPECT); + headers.remove(CONTENT_LANGUAGE); + headers.remove(CONTENT_LOCATION); + headers.remove(LAST_MODIFIED); + headers.remove(http::HeaderName::from_static("digest")); + headers.remove(http::HeaderName::from_static("content-digest")); + headers.remove(http::HeaderName::from_static("repr-digest")); +} + fn strip_sensitive_cross_origin_headers(headers: &mut HeaderMap) { headers.remove(AUTHORIZATION); headers.remove(COOKIE); @@ -1047,7 +1066,8 @@ mod tests { #[test] fn redirect_to_get_strips_body_describing_headers() { use http::header::{ - CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, EXPECT, TRANSFER_ENCODING, + CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_LOCATION, CONTENT_TYPE, + EXPECT, LAST_MODIFIED, TRANSFER_ENCODING, }; let request = Request::builder() .method("POST") @@ -1056,6 +1076,12 @@ mod tests { .header(CONTENT_ENCODING, "gzip") .header(TRANSFER_ENCODING, "chunked") .header(EXPECT, "100-continue") + .header(CONTENT_LANGUAGE, "en") + .header(CONTENT_LOCATION, "/item") + .header(LAST_MODIFIED, "Wed, 21 Oct 2015 07:28:00 GMT") + .header("digest", "sha-256=abc") + .header("content-digest", "sha-256=:abc:") + .header("repr-digest", "sha-256=:abc:") .body(RequestBody::from_static(b"{}")) .expect("request"); let snapshot = RequestSnapshot::capture(&request, super::SnapshotCaptureMode::Rebuildable); @@ -1074,13 +1100,21 @@ mod tests { assert!(next.headers().get(TRANSFER_ENCODING).is_none()); assert!(next.headers().get(EXPECT).is_none()); assert!(next.headers().get(CONTENT_LENGTH).is_none()); + assert!(next.headers().get(CONTENT_LANGUAGE).is_none()); + assert!(next.headers().get(CONTENT_LOCATION).is_none()); + assert!(next.headers().get(LAST_MODIFIED).is_none()); + assert!(next.headers().get("digest").is_none()); + assert!(next.headers().get("content-digest").is_none()); + assert!(next.headers().get("repr-digest").is_none()); } - /// Method/body rewrite table from RFC 9110 §15.4 and Fetch. + /// Method/body rewrite table from RFC 9110 §9.2.2 / §15.4. /// - /// 301/302/303 rewrite non-GET/HEAD to GET and drop the body (historical - /// user-agent behavior that Fetch still requires for 303, and that 301/302 - /// still do in browsers/OkHttp). 307/308 preserve method and body. + /// 301/302 rewrite POST to GET and drop the body (the selected historical + /// user-agent behavior). Other methods keep method and body when replayable. + /// 303 becomes GET retrieval except HEAD, which stays HEAD. 307/308 preserve + /// method and body; one-shot preserved bodies stop instead of substituting + /// an absent body. #[test] fn redirect_method_and_body_matrix_matches_rfc9110() { use http::header::{AUTHORIZATION, HOST}; @@ -1125,14 +1159,53 @@ mod tests { keep_api_key: true, }, Case { - name: "put_301_becomes_get", + name: "put_301_preserves", method: Method::PUT, status: StatusCode::MOVED_PERMANENTLY, body: BodyKind::Static, next: "http://source.test/next", extra: &[], expect: Expect::Follow { - method: Method::GET, + method: Method::PUT, + has_body: true, + }, + keep_authorization: true, + keep_api_key: true, + }, + Case { + name: "patch_302_preserves", + method: Method::PATCH, + status: StatusCode::FOUND, + body: BodyKind::Static, + next: "http://source.test/next", + extra: &[], + expect: Expect::Follow { + method: Method::PATCH, + has_body: true, + }, + keep_authorization: true, + keep_api_key: true, + }, + Case { + name: "put_301_stream_stops", + method: Method::PUT, + status: StatusCode::MOVED_PERMANENTLY, + body: BodyKind::Stream, + next: "http://source.test/next", + extra: &[], + expect: Expect::Stop, + keep_authorization: true, + keep_api_key: true, + }, + Case { + name: "head_303_stays_head", + method: Method::HEAD, + status: StatusCode::SEE_OTHER, + body: BodyKind::Absent, + next: "http://source.test/next", + extra: &[], + expect: Expect::Follow { + method: Method::HEAD, has_body: false, }, keep_authorization: true, diff --git a/crates/openwire/src/transport/body.rs b/crates/openwire/src/transport/body.rs index a540830..9527ca2 100644 --- a/crates/openwire/src/transport/body.rs +++ b/crates/openwire/src/transport/body.rs @@ -6,6 +6,7 @@ use std::time::Duration; use bytes::Bytes; use futures_util::task::AtomicWaker; +use http::header::{CONTENT_LENGTH, TRANSFER_ENCODING}; use http::{Request, Response}; use http_body::{Body, Frame, SizeHint}; use http_body_util::BodyExt; @@ -16,7 +17,9 @@ use openwire_core::{ CallContext, FailurePhase, RequestBody, ResponseBody, SharedTimer, WireError, WireExecutor, }; -use crate::connection::{ConnectionAvailability, ExchangeFinder, RealConnection}; +use crate::connection::{ + ConnectionAvailability, ConnectionProtocol, ExchangeFinder, RealConnection, +}; use super::bindings::{teardown_pooled_connection, ConnectionBindings, ConnectionTaskRegistry}; @@ -121,16 +124,18 @@ pub(super) struct ObservedOutgoingBody { inner: RequestBody, ctx: CallContext, bytes_sent: u64, + fixed_length: Option, started: bool, finished: bool, } impl ObservedOutgoingBody { - pub(super) fn wrap(body: RequestBody, ctx: CallContext) -> RequestBody { + fn wrap(body: RequestBody, ctx: CallContext, fixed_length: Option) -> RequestBody { RequestBody::from_body(Self { inner: body, ctx, bytes_sent: 0, + fixed_length, started: false, finished: false, }) @@ -172,9 +177,12 @@ impl Drop for ObservedOutgoingBody { if self.finished { return; } - if self.started && self.inner.is_end_stream() { + if self.started + && (self.inner.is_end_stream() || self.fixed_length == Some(self.bytes_sent)) + { // Hyper may stop polling after the exact Content-Length payload - // without a trailing `None` frame. + // on HTTP/1 without a trailing `None` frame. This is wire framing + // completion, independent of the source body's EOF validation. self.finish_successfully(); } else { self.finished = true; @@ -220,8 +228,25 @@ impl Body for ObservedOutgoingBody { } } -pub(super) fn present_empty_outgoing_body(body: &RequestBody) -> bool { - !body.is_absent() && body.is_end_stream() +fn http1_fixed_length(request: &Request, protocol: ConnectionProtocol) -> Option { + if protocol != ConnectionProtocol::Http1 || request.headers().contains_key(TRANSFER_ENCODING) { + return None; + } + request + .headers() + .get(CONTENT_LENGTH)? + .to_str() + .ok()? + .parse() + .ok() +} + +pub(super) fn present_empty_outgoing_body( + request: &Request, + protocol: ConnectionProtocol, +) -> bool { + !request.body().is_absent() + && (request.body().is_end_stream() || http1_fixed_length(request, protocol) == Some(0)) } pub(super) fn emit_present_empty_body_events(ctx: &CallContext) { @@ -233,16 +258,23 @@ pub(super) fn emit_present_empty_body_events(ctx: &CallContext) { pub(super) fn instrument_outgoing_body( request: Request, ctx: &CallContext, + protocol: ConnectionProtocol, ) -> Request { if request.body().is_absent() { ctx.mark_request_write_complete(); return request; } - if request.body().is_end_stream() { + if present_empty_outgoing_body(&request, protocol) { return request; } + // Read final framing headers after protocol binding and network + // interceptors. HTTP/2 completion always depends on EOF/END_STREAM. + let fixed_length = http1_fixed_length(&request, protocol); let (parts, body) = request.into_parts(); - Request::from_parts(parts, ObservedOutgoingBody::wrap(body, ctx.clone())) + Request::from_parts( + parts, + ObservedOutgoingBody::wrap(body, ctx.clone(), fixed_length), + ) } pub(super) struct ObservedIncomingBody { @@ -576,3 +608,135 @@ impl Body for ObservedIncomingBody { self.inner.size_hint() } } + +#[cfg(test)] +mod outgoing_tests { + use super::*; + use futures_util::{stream, StreamExt}; + use openwire_core::NoopEventListener; + + fn instrument( + body: RequestBody, + length: u64, + protocol: ConnectionProtocol, + ) -> (RequestBody, CallContext) { + let ctx = CallContext::new(Arc::new(NoopEventListener), None); + // Deliberately leave the request version at its default. Negotiated + // protocol, rather than this version, controls framing completion. + let request = Request::builder() + .header(CONTENT_LENGTH, length) + .body(body) + .expect("request"); + ( + instrument_outgoing_body(request, &ctx, protocol).into_body(), + ctx, + ) + } + + #[tokio::test] + async fn http1_fixed_length_completes_when_sender_stops_polling() { + let source = + stream::iter([Ok::<_, WireError>(Bytes::from_static(b"abc"))]).chain(stream::pending()); + let composite = RequestBody::concat(vec![RequestBody::from_stream_with_length(source, 3)]) + .expect("concat"); + let (mut body, ctx) = instrument(composite, 3, ConnectionProtocol::Http1); + assert_eq!( + body.frame().await.unwrap().unwrap().into_data().unwrap(), + "abc" + ); + assert!(!ctx.request_write_complete()); + drop(body); + assert!(ctx.request_write_complete()); + } + + #[tokio::test] + async fn http2_waits_for_eof_even_after_declared_data_is_read() { + let source = + stream::iter([Ok::<_, WireError>(Bytes::from_static(b"abc"))]).chain(stream::pending()); + let (mut body, ctx) = instrument( + RequestBody::from_stream_with_length(source, 3), + 3, + ConnectionProtocol::Http2, + ); + assert_eq!( + body.frame().await.unwrap().unwrap().into_data().unwrap(), + "abc" + ); + assert!(!body.is_end_stream()); + drop(body); + assert!( + !ctx.request_write_complete(), + "reset/cancel before EOF is incomplete on H2" + ); + } + + #[tokio::test] + async fn fixed_length_does_not_turn_source_errors_into_success() { + let source = stream::iter([ + Ok(Bytes::from_static(b"abc")), + Err(WireError::body( + "source failed", + std::io::Error::other("read failed"), + )), + ]); + let (mut body, ctx) = instrument( + RequestBody::from_stream_with_length(source, 3), + 3, + ConnectionProtocol::Http1, + ); + assert!(body.frame().await.unwrap().is_ok()); + assert!(body.frame().await.unwrap().is_err()); + drop(body); + assert!(!ctx.request_write_complete()); + assert!(ctx.request_failed_emitted()); + } + + #[tokio::test] + async fn incomplete_fixed_length_does_not_complete_when_dropped() { + let source = + stream::iter([Ok::<_, WireError>(Bytes::from_static(b"a"))]).chain(stream::pending()); + let (mut body, ctx) = instrument( + RequestBody::from_stream_with_length(source, 3), + 3, + ConnectionProtocol::Http1, + ); + assert!(body.frame().await.unwrap().is_ok()); + drop(body); + assert!(!ctx.request_write_complete()); + } + + #[tokio::test] + async fn transfer_encoding_and_arbitrary_trailers_require_eof() { + let source = + stream::iter([Ok::<_, WireError>(Bytes::from_static(b"abc"))]).chain(stream::pending()); + let arbitrary = RequestBody::from_body(RequestBody::from_stream_with_length(source, 3)); + let ctx = CallContext::new(Arc::new(NoopEventListener), None); + let request = Request::builder() + .header(CONTENT_LENGTH, 3) + .header(TRANSFER_ENCODING, "chunked") + .body(arbitrary) + .unwrap(); + let mut body = + instrument_outgoing_body(request, &ctx, ConnectionProtocol::Http1).into_body(); + assert!(body.frame().await.unwrap().is_ok()); + drop(body); + assert!(!ctx.request_write_complete()); + } + + #[test] + fn zero_length_is_empty_framing_only_for_http1() { + for protocol in [ConnectionProtocol::Http1, ConnectionProtocol::Http2] { + let request = Request::builder() + .header(CONTENT_LENGTH, 0) + .body(RequestBody::from_stream_with_length( + stream::pending::>(), + 0, + )) + .unwrap(); + assert_eq!( + present_empty_outgoing_body(&request, protocol), + protocol == ConnectionProtocol::Http1 + ); + } + } +} diff --git a/crates/openwire/src/transport/service.rs b/crates/openwire/src/transport/service.rs index 495beff..d6f742d 100644 --- a/crates/openwire/src/transport/service.rs +++ b/crates/openwire/src/transport/service.rs @@ -870,7 +870,8 @@ async fn send_bound_request( connection.route().kind(), )?; ctx.reset_request_exchange_observation(); - let request = instrument_outgoing_body(request, &ctx); + let protocol = connection.protocol(); + let request = instrument_outgoing_body(request, &ctx, protocol); match binding { AcquiredBinding::Http1 { info, mut sender } => { @@ -887,7 +888,7 @@ async fn send_bound_request( map_hyper_error(error) })?; let request_requests_close = connection_header_requests_close(request.headers()); - let response = dispatch_try_send_request(&ctx, request, |request| { + let response = dispatch_try_send_request(&ctx, request, protocol, |request| { sender.try_send_request(request) }); let response = response.await; @@ -934,7 +935,7 @@ async fn send_bound_request( ); map_hyper_error(error) })?; - let response = dispatch_try_send_request(&ctx, request, |request| { + let response = dispatch_try_send_request(&ctx, request, protocol, |request| { sender.try_send_request(request) }); let response = response.await; @@ -972,11 +973,16 @@ async fn send_bound_request( } } -fn dispatch_try_send_request(ctx: &CallContext, request: Request, send: F) -> T +fn dispatch_try_send_request( + ctx: &CallContext, + request: Request, + protocol: ConnectionProtocol, + send: F, +) -> T where F: FnOnce(Request) -> T, { - let present_empty = present_empty_outgoing_body(request.body()); + let present_empty = present_empty_outgoing_body(&request, protocol); ctx.listener().request_headers_start(ctx); let pending = send(request); ctx.listener().request_headers_end(ctx); diff --git a/crates/openwire/tests/auth.rs b/crates/openwire/tests/auth.rs index 066ab03..b7f601f 100644 --- a/crates/openwire/tests/auth.rs +++ b/crates/openwire/tests/auth.rs @@ -164,6 +164,90 @@ async fn streaming_request_bodies_are_not_authenticated_on_401() { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } +#[cfg(feature = "multipart")] +#[tokio::test] +async fn replayable_multipart_form_is_authenticated_on_401() { + use openwire::multipart::{Form, Part}; + + let server = spawn_http1(|request: Request| async move { + let auth = request + .headers() + .get(AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let _ = collect_request_body(request).await; + if auth.as_deref() == Some("Bearer good") { + ok_text("authorized") + } else { + Response::builder() + .status(StatusCode::UNAUTHORIZED) + .header("www-authenticate", "Bearer realm=\"openwire\"") + .body(http_body_util::Full::new(bytes::Bytes::new())) + .expect("unauthorized response") + } + }) + .await; + + let authenticator = StaticAuthorizationAuthenticator::new("Bearer good"); + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .authenticator(authenticator.clone()) + .build() + .expect("client"); + let request = Form::new() + .text("a", "b") + .part("file", Part::bytes(Bytes::from_static(b"hello"))) + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/form-auth", + server.addr().port() + ))) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(authenticator.calls(), 1); + assert_eq!( + response.into_body().text().await.expect("body"), + "authorized" + ); +} + +#[cfg(feature = "multipart")] +#[tokio::test] +async fn one_shot_multipart_form_is_not_authenticated_on_401() { + use openwire::multipart::{Form, Part}; + + let server = spawn_http1(|request: Request| async move { + let _ = collect_request_body(request).await; + Response::builder() + .status(StatusCode::UNAUTHORIZED) + .header("www-authenticate", "Bearer realm=\"openwire\"") + .body(http_body_util::Full::new(bytes::Bytes::new())) + .expect("unauthorized response") + }) + .await; + + let authenticator = StaticAuthorizationAuthenticator::new("Bearer good"); + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .authenticator(authenticator.clone()) + .build() + .expect("client"); + let request = Form::new() + .part( + "file", + Part::stream(stream::iter(vec![Ok::( + Bytes::from_static(b"one-shot"), + )])), + ) + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/form-stream-auth", + server.addr().port() + ))) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(authenticator.calls(), 0); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} + #[tokio::test] async fn auth_attempts_are_limited_and_counted_independently() { let server = spawn_http1(|_request: Request| async move { diff --git a/crates/openwire/tests/compression_bridge.rs b/crates/openwire/tests/compression_bridge.rs index d0650fd..57ba912 100644 --- a/crates/openwire/tests/compression_bridge.rs +++ b/crates/openwire/tests/compression_bridge.rs @@ -422,3 +422,237 @@ async fn bridge_interceptor_preserves_explicit_accept_encoding_and_wire_body() { let body = response.into_body().bytes().await.expect("body"); assert_eq!(body.as_ref(), expected_wire_body.as_slice()); } + +#[tokio::test] +async fn known_length_one_shot_stream_uses_content_length() { + let observed_server_request = Arc::new(Mutex::new(None)); + let observed_server_request_clone = observed_server_request.clone(); + let server = spawn_http1(move |request: Request| { + let observed_server_request = observed_server_request_clone.clone(); + async move { + let headers = ObservedHeaders::capture(request.headers()); + let body = collect_request_body(request).await; + *observed_server_request + .lock() + .expect("observed server request") = Some(ObservedServerRequest { + headers, + body: String::from_utf8(body.to_vec()).expect("utf-8"), + }); + ok_text("one-shot") + } + }) + .await; + + let interceptor = HeaderCaptureInterceptor::default(); + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .network_interceptor(interceptor.clone()) + .build() + .expect("client"); + + let request = Request::builder() + .method("POST") + .uri(format!( + "http://openwire.test:{}/one-shot-length", + server.addr().port() + )) + .header(CONTENT_LENGTH, "999") + .header(TRANSFER_ENCODING, "identity") + .body(RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"abc"))]), + 3, + )) + .expect("request"); + + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "one-shot"); + + let expected = ObservedHeaders { + host: Some(format!("openwire.test:{}", server.addr().port())), + user_agent: Some(default_user_agent().to_owned()), + accept_encoding: Some(default_accept_encoding().to_owned()), + content_length: Some("3".to_owned()), + transfer_encoding: None, + }; + assert_eq!(interceptor.take_single(), expected); + assert_eq!( + take_observed_server_request(&observed_server_request), + ObservedServerRequest { + headers: expected, + body: "abc".to_owned(), + } + ); +} + +#[tokio::test] +async fn from_body_exact_size_hint_keeps_chunked_http11_and_trailers() { + use http::HeaderMap; + use http_body::{Body, Frame, SizeHint}; + use std::pin::Pin; + use std::task::{Context, Poll}; + + struct DataThenTrailers { + data: Option, + trailers: Option, + } + + impl Body for DataThenTrailers { + type Data = Bytes; + type Error = WireError; + + fn poll_frame( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + let this = self.get_mut(); + if let Some(data) = this.data.take() { + if !data.is_empty() { + return Poll::Ready(Some(Ok(Frame::data(data)))); + } + } + if let Some(trailers) = this.trailers.take() { + return Poll::Ready(Some(Ok(Frame::trailers(trailers)))); + } + Poll::Ready(None) + } + + fn size_hint(&self) -> SizeHint { + SizeHint::with_exact( + self.data + .as_ref() + .map(|data| data.len() as u64) + .unwrap_or(0), + ) + } + } + + let observed = Arc::new(Mutex::new(None)); + let server = spawn_raw_http1_capture_request(observed.clone()).await; + let interceptor = HeaderCaptureInterceptor::default(); + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .network_interceptor(interceptor.clone()) + .build() + .expect("client"); + + let mut trailer_map = HeaderMap::new(); + trailer_map.insert("x-test-trailer", "1".parse().expect("trailer")); + let request = Request::builder() + .method("POST") + .uri(format!( + "http://openwire.test:{}/trailers", + server.addr().port() + )) + .header(http::header::TRAILER, "x-test-trailer") + .body(RequestBody::from_body(DataThenTrailers { + data: Some(Bytes::from_static(b"xyz")), + trailers: Some(trailer_map), + })) + .expect("request"); + assert_eq!(request.body().size_hint().exact(), None); + assert_eq!(request.body().content_length(), None); + + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + let captured = interceptor.take_single(); + assert!(captured.content_length.is_none()); + assert_eq!(captured.transfer_encoding.as_deref(), Some("chunked")); + + let wire = observed + .lock() + .expect("observed") + .clone() + .expect("captured request"); + let text = String::from_utf8_lossy(&wire); + assert!( + text.to_ascii_lowercase() + .contains("transfer-encoding: chunked"), + "{text}" + ); + assert!( + !text.to_ascii_lowercase().contains("content-length:"), + "{text}" + ); + assert!(text.contains("3\r\nxyz\r\n"), "{text:?}"); + assert!( + text.to_ascii_lowercase().contains("x-test-trailer: 1"), + "{text}" + ); +} + +#[tokio::test] +async fn from_body_zero_data_with_trailers_stays_chunked() { + use http::HeaderMap; + use http_body::{Body, Frame, SizeHint}; + use std::pin::Pin; + use std::task::{Context, Poll}; + + struct TrailersOnly(HeaderMap); + + impl Body for TrailersOnly { + type Data = Bytes; + type Error = WireError; + + fn poll_frame( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + let this = self.get_mut(); + if this.0.is_empty() { + Poll::Ready(None) + } else { + Poll::Ready(Some(Ok(Frame::trailers(std::mem::take(&mut this.0))))) + } + } + + fn size_hint(&self) -> SizeHint { + SizeHint::with_exact(0) + } + } + + let observed = Arc::new(Mutex::new(None)); + let server = spawn_raw_http1_capture_request(observed.clone()).await; + let interceptor = HeaderCaptureInterceptor::default(); + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .network_interceptor(interceptor.clone()) + .build() + .expect("client"); + + let mut trailer_map = HeaderMap::new(); + trailer_map.insert("x-empty-trailer", "yes".parse().expect("trailer")); + let request = Request::builder() + .method("POST") + .uri(format!( + "http://openwire.test:{}/zero-trailers", + server.addr().port() + )) + .header(http::header::TRAILER, "x-empty-trailer") + .body(RequestBody::from_body(TrailersOnly(trailer_map))) + .expect("request"); + + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + let captured = interceptor.take_single(); + assert!(captured.content_length.is_none()); + assert_eq!(captured.transfer_encoding.as_deref(), Some("chunked")); + let wire = observed + .lock() + .expect("observed") + .clone() + .expect("captured request"); + let text = String::from_utf8_lossy(&wire); + assert!( + text.to_ascii_lowercase() + .contains("transfer-encoding: chunked"), + "{text}" + ); + assert!( + !text.to_ascii_lowercase().contains("content-length:"), + "{text}" + ); + assert!( + text.to_ascii_lowercase().contains("x-empty-trailer: yes"), + "{text}" + ); +} diff --git a/crates/openwire/tests/events.rs b/crates/openwire/tests/events.rs index ff516ca..b70c6e5 100644 --- a/crates/openwire/tests/events.rs +++ b/crates/openwire/tests/events.rs @@ -24,6 +24,67 @@ fn get(uri: impl AsRef) -> Request { .expect("request") } +#[tokio::test] +async fn known_length_composites_emit_body_completion_once() { + use bytes::Bytes; + use futures_util::stream; + use openwire::WireError; + use openwire_test::collect_request_body; + + let server = spawn_http1(|request: Request| async move { + ok_text(collect_request_body(request).await) + }) + .await; + for (prefix, payload, nested) in [ + ("", "abc", false), + ("prefix", "abc", false), + ("", "", false), + ("", "abc", true), + ] { + let expected = format!("{prefix}{payload}"); + let stream_body = RequestBody::from_stream_with_length( + stream::iter([Ok::(Bytes::copy_from_slice( + payload.as_bytes(), + ))]), + payload.len() as u64, + ); + let mut body = RequestBody::concat(vec![RequestBody::from(prefix.to_owned()), stream_body]) + .expect("concat"); + if nested { + body = RequestBody::concat(vec![body]).expect("nested concat"); + } + let events = RecordingEventListenerFactory::default(); + let client = Client::builder() + .event_listener_factory(events.clone()) + .build() + .expect("client"); + let request = Request::builder() + .method(Method::POST) + .uri(format!("http://{}/upload", server.addr())) + .body(body) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), expected); + let recorded = events.events(); + for event in [ + "request_body_start".to_owned(), + format!("request_body_end {}", expected.len()), + ] { + assert_eq!( + recorded.iter().filter(|actual| *actual == &event).count(), + 1, + "{recorded:?}" + ); + } + events.assert_contains_in_order(&[ + "request_headers_end", + "request_body_start", + "request_body_end", + "call_end", + ]); + } +} + #[tokio::test] async fn successful_http1_get_emits_architecture_lifecycle() { let server = MockWebServer::http1().await; diff --git a/crates/openwire/tests/multipart.rs b/crates/openwire/tests/multipart.rs new file mode 100644 index 0000000..6a21371 --- /dev/null +++ b/crates/openwire/tests/multipart.rs @@ -0,0 +1,619 @@ +#![cfg(feature = "multipart")] + +mod support; + +use std::pin::Pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; + +use bytes::Bytes; +use futures_util::stream::{self, Stream}; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, TE, TRANSFER_ENCODING}; +use http::{Request, Version}; +use http_body_util::BodyExt; +use hyper::body::Incoming; +use openwire::multipart::{Form, Part}; +use openwire::{Client, RustlsTlsConnector, WireError, WireErrorKind}; +use openwire_test::{ + collect_request_body, ok_text, spawn_http1, spawn_https_http2_with_hosts, + RecordingEventListenerFactory, StaticDnsResolver, +}; + +use support::*; + +fn sample_form() -> Form { + Form::new() + .text("description", "upload from OpenWire") + .part( + "file", + Part::bytes(Bytes::from_static(b"hello\n")) + .file_name("hello.txt") + .mime_str("text/plain; charset=utf-8") + .expect("mime"), + ) +} + +fn content_type_boundary(value: &http::HeaderValue) -> String { + let value = value.to_str().expect("ascii"); + let prefix = "multipart/form-data; boundary="; + assert!(value.starts_with(prefix), "content-type = {value}"); + value[prefix.len()..].to_owned() +} + +#[tokio::test] +async fn http11_upload_matches_encoded_body_and_content_type() { + let observed = Arc::new(Mutex::new(None)); + let observed_clone = observed.clone(); + let interceptor = HeaderCaptureInterceptor::default(); + let events = RecordingEventListenerFactory::default(); + let server = spawn_http1(move |request: Request| { + let observed = observed_clone.clone(); + async move { + let content_type = request + .headers() + .get(CONTENT_TYPE) + .cloned() + .expect("content-type"); + let content_length = request + .headers() + .get(CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let transfer_encoding = request.headers().get(TRANSFER_ENCODING).cloned(); + let body = collect_request_body(request).await; + *observed.lock().expect("observed") = + Some((content_type, content_length, transfer_encoding, body)); + ok_text("ok") + } + }) + .await; + + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .network_interceptor(interceptor.clone()) + .event_listener_factory(events.clone()) + .build() + .expect("client"); + + let request = sample_form() + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/upload", + server.addr().port() + ))) + .expect("request"); + let content_type = request + .headers() + .get(CONTENT_TYPE) + .cloned() + .expect("content-type"); + let expected_len = request.body().content_length().expect("known length"); + let expected_bytes = request + .body() + .try_clone() + .expect("replayable") + .collect() + .await + .expect("collect") + .to_bytes(); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + + let captured = observed + .lock() + .expect("observed") + .clone() + .expect("captured"); + assert_eq!(captured.0, content_type); + assert_eq!( + captured.1.as_deref(), + Some(expected_len.to_string().as_str()) + ); + assert!(captured.2.is_none()); + assert_eq!(captured.3, expected_bytes); + assert!(interceptor.take_single().transfer_encoding.is_none()); + events.assert_contains_in_order(&[ + "request_body_start", + &format!("request_body_end {expected_len}"), + ]); + let body_end_count = events + .events() + .iter() + .filter(|event| event.starts_with("request_body_end ")) + .count(); + assert_eq!(body_end_count, 1); +} + +#[tokio::test] +async fn http2_upload_omits_transfer_encoding_and_matches_encoded_bytes() { + let observed = Arc::new(Mutex::new(None)); + let observed_clone = observed.clone(); + let server = + spawn_https_http2_with_hosts(&["openwire.test"], move |request: Request| { + let observed = observed_clone.clone(); + async move { + let version = request.version(); + let content_type = request + .headers() + .get(CONTENT_TYPE) + .cloned() + .expect("content-type"); + let content_length = request.headers().get(CONTENT_LENGTH).cloned(); + let transfer_encoding = request.headers().get(TRANSFER_ENCODING).cloned(); + let te = request.headers().get(TE).cloned(); + let connection = request.headers().get(http::header::CONNECTION).cloned(); + let body = collect_request_body(request).await; + *observed.lock().expect("observed") = Some(( + version, + content_type, + content_length, + transfer_encoding, + te, + connection, + body, + )); + ok_text("h2") + } + }) + .await; + + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .tls_connector( + RustlsTlsConnector::builder() + .add_root_certificates_pem(server.tls_root_pem().expect("root pem")) + .expect("root cert") + .build() + .expect("tls"), + ) + .build() + .expect("client"); + + let request = sample_form() + .into_request(Request::builder().method("POST").uri(format!( + "https://openwire.test:{}/upload", + server.addr().port() + ))) + .expect("request"); + let content_type = request + .headers() + .get(CONTENT_TYPE) + .cloned() + .expect("content-type"); + let expected_bytes = request + .body() + .try_clone() + .expect("replayable") + .collect() + .await + .expect("collect") + .to_bytes(); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.version(), Version::HTTP_2); + assert_eq!(response.into_body().text().await.expect("body"), "h2"); + + let captured = observed + .lock() + .expect("observed") + .clone() + .expect("captured"); + assert_eq!(captured.0, Version::HTTP_2); + assert_eq!(captured.1, content_type); + assert!(captured.2.is_some()); + assert!(captured.3.is_none()); + assert!(captured.4.is_none()); + assert!(captured.5.is_none()); + assert_eq!(captured.6, expected_bytes); +} + +#[tokio::test] +async fn known_length_one_shot_form_uses_content_length() { + let observed = Arc::new(Mutex::new(None)); + let observed_clone = observed.clone(); + let server = spawn_http1(move |request: Request| { + let observed = observed_clone.clone(); + async move { + let content_length = request + .headers() + .get(CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let transfer_encoding = request.headers().get(TRANSFER_ENCODING).cloned(); + let body = collect_request_body(request).await; + *observed.lock().expect("observed") = Some((content_length, transfer_encoding, body)); + ok_text("ok") + } + }) + .await; + + let payload = Bytes::from_static(b"xyz"); + let form = Form::new().part( + "file", + Part::stream_with_length( + stream::iter(vec![Ok::(payload.clone())]), + payload.len() as u64, + ), + ); + let (_, encoded) = Form::new() + .part("file", Part::bytes(payload.clone())) + .into_parts() + .expect("expected"); + let expected_len = encoded.content_length().expect("length"); + + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .build() + .expect("client"); + let request = form + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/one-shot", + server.addr().port() + ))) + .expect("request"); + assert!(request.body().try_clone().is_none()); + assert_eq!(request.body().content_length(), Some(expected_len)); + + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + let captured = observed + .lock() + .expect("observed") + .clone() + .expect("captured"); + assert_eq!( + captured.0.as_deref(), + Some(expected_len.to_string().as_str()) + ); + assert!(captured.1.is_none()); +} + +#[tokio::test] +async fn unknown_length_stream_form_uses_http11_chunked() { + let observed = Arc::new(Mutex::new(None)); + let observed_clone = observed.clone(); + let server = spawn_http1(move |request: Request| { + let observed = observed_clone.clone(); + async move { + let content_length = request.headers().get(CONTENT_LENGTH).cloned(); + let transfer_encoding = request + .headers() + .get(TRANSFER_ENCODING) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let body = collect_request_body(request).await; + *observed.lock().expect("observed") = Some((content_length, transfer_encoding, body)); + ok_text("ok") + } + }) + .await; + + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .build() + .expect("client"); + let request = Form::new() + .part( + "file", + Part::stream(stream::iter(vec![Ok::( + Bytes::from_static(b"chunked-payload"), + )])), + ) + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/chunked", + server.addr().port() + ))) + .expect("request"); + assert!(request.body().content_length().is_none()); + + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + let captured = observed + .lock() + .expect("observed") + .clone() + .expect("captured"); + assert!(captured.0.is_none()); + assert_eq!(captured.1.as_deref(), Some("chunked")); + assert!(captured + .2 + .windows(15) + .any(|window| window == b"chunked-payload")); +} + +#[tokio::test] +async fn http10_unknown_length_form_is_rejected_before_io() { + let attempts = Arc::new(AtomicUsize::new(0)); + let handler_attempts = attempts.clone(); + let interceptor = HeaderCaptureInterceptor::default(); + let server = spawn_http1(move |_request: Request| { + handler_attempts.fetch_add(1, Ordering::SeqCst); + async move { ok_text("should not run") } + }) + .await; + + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .network_interceptor(interceptor.clone()) + .build() + .expect("client"); + let request = Form::new() + .part( + "file", + Part::stream(stream::iter(vec![Ok::( + Bytes::from_static(b"nope"), + )])), + ) + .into_request( + Request::builder() + .method("POST") + .version(Version::HTTP_10) + .uri(format!( + "http://openwire.test:{}/http10", + server.addr().port() + )), + ) + .expect("request"); + + let error = client.execute(request).await.expect_err("http/1.0"); + assert_eq!(error.kind(), WireErrorKind::InvalidRequest); + assert_eq!(attempts.load(Ordering::SeqCst), 0); + assert!(interceptor.seen.lock().expect("seen").is_empty()); +} + +#[tokio::test] +async fn source_read_error_does_not_read_later_parts() { + let later_reads = Arc::new(AtomicUsize::new(0)); + let later = later_reads.clone(); + let failing = stream::iter(vec![Err(WireError::internal( + "source read failed", + std::io::Error::other("read"), + ))]); + let later_stream = stream::unfold((), move |_| { + let later = later.clone(); + async move { + later.fetch_add(1, Ordering::SeqCst); + Some((Ok::(Bytes::from_static(b"later")), ())) + } + }); + + let server = spawn_http1(|request: Request| async move { + let _ = collect_request_body(request).await; + ok_text("unused") + }) + .await; + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .build() + .expect("client"); + let request = Form::new() + .part("first", Part::stream(failing)) + .part("second", Part::stream(later_stream)) + .into_request( + Request::builder() + .method("POST") + .uri(format!("http://openwire.test:{}/err", server.addr().port())), + ) + .expect("request"); + let error = client.execute(request).await.expect_err("body error"); + assert_eq!(error.kind(), WireErrorKind::Body); + assert_eq!(later_reads.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn declared_length_mismatch_does_not_emit_suffix() { + let observed = Arc::new(Mutex::new(None)); + let observed_clone = observed.clone(); + let server = spawn_http1(move |request: Request| { + let observed = observed_clone.clone(); + async move { + let body = collect_request_body(request).await; + *observed.lock().expect("observed") = Some(body); + ok_text("unused") + } + }) + .await; + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .build() + .expect("client"); + let request = Form::new() + .part( + "file", + Part::stream_with_length( + stream::iter(vec![ + Ok::(Bytes::from_static(b"ab")), + Ok(Bytes::from_static(b"c")), + ]), + 2, + ), + ) + .into_request( + Request::builder() + .method("POST") + .uri(format!("http://openwire.test:{}/len", server.addr().port())), + ) + .expect("request"); + let error = client.execute(request).await.expect_err("length"); + assert_eq!(error.kind(), WireErrorKind::Body); + let maybe_body = observed.lock().expect("observed").clone(); + if let Some(body) = maybe_body { + let text = String::from_utf8_lossy(&body); + assert!( + text.matches("--").count() <= 1, + "closing delimiter must not hide a length error: {text:?}" + ); + } +} + +#[tokio::test] +async fn stream_collision_never_emits_forbidden_sequence() { + let observed = Arc::new(Mutex::new(None)); + let observed_clone = observed.clone(); + let server = spawn_http1(move |request: Request| { + let observed = observed_clone.clone(); + async move { + let body = collect_request_body(request).await; + *observed.lock().expect("observed") = Some(body); + ok_text("unused") + } + }) + .await; + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .build() + .expect("client"); + + let shared_boundary = Arc::new(Mutex::new(None::)); + let stream_boundary = shared_boundary.clone(); + let colliding = stream::unfold(0u8, move |step| { + let stream_boundary = stream_boundary.clone(); + async move { + match step { + 0 => Some((Ok::(Bytes::from_static(b"ok\r\n")), 1)), + 1 => { + let boundary = loop { + if let Some(boundary) = stream_boundary.lock().expect("boundary").clone() { + break boundary; + } + tokio::task::yield_now().await; + }; + Some((Ok(Bytes::from(format!("--{boundary}"))), 2)) + } + _ => None, + } + } + }); + let request = Form::new() + .part("file", Part::stream(colliding)) + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/collision", + server.addr().port() + ))) + .expect("request"); + let boundary = content_type_boundary(request.headers().get(CONTENT_TYPE).expect("ct")); + *shared_boundary.lock().expect("boundary") = Some(boundary.clone()); + let error = client.execute(request).await.expect_err("collision"); + assert_eq!(error.kind(), WireErrorKind::Body); + let maybe_body = observed.lock().expect("observed").clone(); + if let Some(body) = maybe_body { + let needle = format!("--{boundary}").into_bytes(); + let closer = format!("--{boundary}--").into_bytes(); + let dash_boundary_hits = body + .windows(needle.len()) + .filter(|window| *window == needle.as_slice()) + .count(); + assert!( + dash_boundary_hits <= 1, + "payload must not emit a second dash-boundary: {}", + String::from_utf8_lossy(&body) + ); + assert!( + !body.windows(closer.len()).any(|window| window == closer), + "closing delimiter must not be emitted after collision" + ); + } +} + +struct PendingOnce { + pending: bool, + inner: S, +} + +impl> + Unpin> Stream for PendingOnce { + type Item = Result; + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.pending { + this.pending = false; + cx.waker().wake_by_ref(); + return Poll::Pending; + } + Pin::new(&mut this.inner).poll_next(cx) + } +} + +#[tokio::test] +async fn pending_producer_still_uploads_complete_form() { + let observed = Arc::new(Mutex::new(None)); + let observed_clone = observed.clone(); + let server = spawn_http1(move |request: Request| { + let observed = observed_clone.clone(); + async move { + let body = collect_request_body(request).await; + *observed.lock().expect("observed") = Some(body); + ok_text("ok") + } + }) + .await; + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .build() + .expect("client"); + let request = Form::new() + .part( + "file", + Part::stream(PendingOnce { + pending: true, + inner: stream::iter(vec![Ok::(Bytes::from_static(b"xyz"))]), + }), + ) + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/pending", + server.addr().port() + ))) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + let body = observed.lock().expect("observed").clone().expect("body"); + assert!(body.windows(3).any(|window| window == b"xyz")); +} + +#[tokio::test] +async fn top_level_known_length_stream_emits_body_end() { + let events = RecordingEventListenerFactory::default(); + let server = spawn_http1(|_request: Request| async move { ok_text("ok") }).await; + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .event_listener_factory(events.clone()) + .build() + .expect("client"); + let request = Request::builder() + .method("POST") + .uri(format!( + "http://openwire.test:{}/len-events", + server.addr().port() + )) + .body(openwire::RequestBody::from_stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"abc"))]), + 3, + )) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + events.assert_contains_in_order(&["request_body_start", "request_body_end 3"]); +} + +#[tokio::test] +async fn top_level_zero_length_stream_emits_body_events() { + let events = RecordingEventListenerFactory::default(); + let server = spawn_http1(|_request: Request| async move { ok_text("ok") }).await; + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .event_listener_factory(events.clone()) + .build() + .expect("client"); + let request = Request::builder() + .method("POST") + .uri(format!( + "http://openwire.test:{}/zero-len-events", + server.addr().port() + )) + .body(openwire::RequestBody::from_stream_with_length( + stream::iter(Vec::>::new()), + 0, + )) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.into_body().text().await.expect("body"), "ok"); + events.assert_contains_in_order(&["request_body_start", "request_body_end 0"]); +} diff --git a/crates/openwire/tests/pool_http2.rs b/crates/openwire/tests/pool_http2.rs index a16089e..ebd1a72 100644 --- a/crates/openwire/tests/pool_http2.rs +++ b/crates/openwire/tests/pool_http2.rs @@ -1651,6 +1651,115 @@ async fn streaming_request_bodies_are_not_retried_on_connection_failure() { assert_eq!(connector.attempts(), 1); } +#[cfg(feature = "multipart")] +#[tokio::test] +async fn known_length_one_shot_form_is_not_retried_on_connection_failure() { + use openwire::multipart::{Form, Part}; + + let server = spawn_http1(|_request| async move { ok_text("never reached") }).await; + let connector = FailingTcpConnector::new(1); + let client = Client::builder() + .dns_resolver(StaticDnsResolver::new(server.addr())) + .tcp_connector(connector.clone()) + .max_retries(1) + .build() + .expect("client"); + + let request = Form::new() + .part( + "file", + Part::stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"xyz"))]), + 3, + ), + ) + .into_request(Request::builder().method("POST").uri(format!( + "http://openwire.test:{}/form-no-retry", + server.addr().port() + ))) + .expect("request"); + assert!(request.body().content_length().is_some()); + assert!(request.body().try_clone().is_none()); + + let error = client.execute(request).await.expect_err("should fail"); + assert_eq!(error.kind(), WireErrorKind::Connect); + assert_eq!(connector.attempts(), 1); +} + +#[cfg(feature = "multipart")] +#[tokio::test] +async fn coalesced_http2_421_does_not_retry_one_shot_form() { + use openwire::multipart::{Form, Part}; + + let attempts = Arc::new(AtomicUsize::new(0)); + let handler_attempts = attempts.clone(); + let server = spawn_https_http2_with_hosts(&["a.test", "b.test"], move |request| { + let handler_attempts = handler_attempts.clone(); + async move { + match request.uri().path() { + "/first" => ok_text("first h2"), + "/form" => { + let _ = collect_request_body(request).await; + handler_attempts.fetch_add(1, Ordering::SeqCst); + text_response(StatusCode::MISDIRECTED_REQUEST, "misdirected") + } + _ => text_response(StatusCode::NOT_FOUND, "not found"), + } + } + }) + .await; + let events = RecordingEventListenerFactory::default(); + let client = Client::builder() + .dns_resolver(HostMapResolver::new([ + ("a.test".to_owned(), server.addr()), + ("b.test".to_owned(), server.addr()), + ])) + .event_listener_factory(events.clone()) + .tls_connector( + RustlsTlsConnector::builder() + .add_root_certificates_pem(server.tls_root_pem().expect("root pem")) + .expect("root cert") + .build() + .expect("tls connector"), + ) + .build() + .expect("client"); + + let response_one = client + .execute(empty_request(format!( + "https://a.test:{}/first", + server.addr().port() + ))) + .await + .expect("response"); + let _ = response_one.into_body().text().await.expect("body"); + + let request = Form::new() + .part( + "file", + Part::stream_with_length( + stream::iter(vec![Ok::(Bytes::from_static(b"xyz"))]), + 3, + ), + ) + .into_request( + Request::builder() + .method("POST") + .uri(format!("https://b.test:{}/form", server.addr().port())), + ) + .expect("request"); + let response_two = client.execute(request).await.expect("response"); + assert_eq!(response_two.status(), StatusCode::MISDIRECTED_REQUEST); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + let events = events.events(); + assert!( + !events + .iter() + .any(|event| event.contains("misdirected_request")), + "events = {events:?}", + ); +} + #[tokio::test] async fn post_send_failure_marks_request_committed_for_retry_policy() { let accepted_connections = Arc::new(AtomicUsize::new(0)); diff --git a/crates/openwire/tests/redirect.rs b/crates/openwire/tests/redirect.rs index 8d91911..5cd13ae 100644 --- a/crates/openwire/tests/redirect.rs +++ b/crates/openwire/tests/redirect.rs @@ -622,3 +622,250 @@ async fn redirect_count_remains_independent_from_retry_count() { "events = {events:?}", ); } + +#[tokio::test] +async fn put_301_second_hop_preserves_method_and_body() { + let server = MockWebServer::http1().await; + server.enqueue( + MockResponse::new() + .status(StatusCode::MOVED_PERMANENTLY) + .header("Location", "/next") + .body("redirect"), + ); + server.enqueue(MockResponse::new().body("ok")); + + let client = Client::builder().build().expect("client"); + let request = Request::builder() + .method(Method::PUT) + .uri(server.url("/start")) + .header(http::header::CONTENT_TYPE, "application/json") + .body(RequestBody::from_static(b"payload")) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.status(), StatusCode::OK); + let _ = response.into_body().text().await.expect("body"); + + let first = server.take_request().await; + assert_eq!(first.method, Method::PUT); + assert_eq!(first.body.as_ref(), b"payload"); + + let second = server.take_request().await; + assert_eq!(second.method, Method::PUT); + assert_eq!(second.body.as_ref(), b"payload"); + assert_eq!( + second + .headers + .get(http::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()), + Some("application/json") + ); +} + +#[tokio::test] +async fn patch_302_second_hop_preserves_method_and_body() { + let server = MockWebServer::http1().await; + server.enqueue( + MockResponse::new() + .status(StatusCode::FOUND) + .header("Location", "/next") + .body("redirect"), + ); + server.enqueue(MockResponse::new().body("ok")); + + let client = Client::builder().build().expect("client"); + let request = Request::builder() + .method(Method::PATCH) + .uri(server.url("/start")) + .body(RequestBody::from_static(b"patch-body")) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.status(), StatusCode::OK); + let _ = response.into_body().text().await.expect("body"); + + let second = { + let _first = server.take_request().await; + server.take_request().await + }; + assert_eq!(second.method, Method::PATCH); + assert_eq!(second.body.as_ref(), b"patch-body"); +} + +#[tokio::test] +async fn put_301_streaming_body_is_returned() { + let attempts = Arc::new(AtomicUsize::new(0)); + let server_attempts = attempts.clone(); + let server = spawn_http1(move |request: Request| { + let server_attempts = server_attempts.clone(); + async move { + server_attempts.fetch_add(1, Ordering::SeqCst); + let _ = collect_request_body(request).await; + Response::builder() + .status(StatusCode::MOVED_PERMANENTLY) + .header("location", "/final") + .body(http_body_util::Full::new(Bytes::from_static( + b"cannot replay", + ))) + .expect("redirect response") + } + }) + .await; + let client = Client::builder().build().expect("client"); + let request = Request::builder() + .method(Method::PUT) + .uri(server.http_url("/streaming-put")) + .body(RequestBody::from_stream(stream::iter(vec![Ok::< + Bytes, + WireError, + >( + Bytes::from_static(b"streaming"), + )]))) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.status(), StatusCode::MOVED_PERMANENTLY); + assert_eq!(attempts.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn post_302_strips_content_language_and_digest_headers() { + let server = MockWebServer::http1().await; + server.enqueue( + MockResponse::new() + .status(StatusCode::FOUND) + .header("Location", "/next") + .body("redirect"), + ); + server.enqueue(MockResponse::new().body("ok")); + + let client = Client::builder().build().expect("client"); + let request = Request::builder() + .method(Method::POST) + .uri(server.url("/start")) + .header(http::header::CONTENT_TYPE, "text/plain") + .header(http::header::CONTENT_LANGUAGE, "en") + .header(http::header::CONTENT_LOCATION, "/item") + .header(http::header::LAST_MODIFIED, "Wed, 21 Oct 2015 07:28:00 GMT") + .header("digest", "sha-256=abc") + .header("content-digest", "sha-256=:abc:") + .header("repr-digest", "sha-256=:abc:") + .body(RequestBody::from_static(b"payload")) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.status(), StatusCode::OK); + let _ = response.into_body().text().await.expect("body"); + let _first = server.take_request().await; + let second = server.take_request().await; + assert_eq!(second.method, Method::GET); + assert!(second.headers.get(http::header::CONTENT_TYPE).is_none()); + assert!(second.headers.get(http::header::CONTENT_LANGUAGE).is_none()); + assert!(second.headers.get(http::header::CONTENT_LOCATION).is_none()); + assert!(second.headers.get(http::header::LAST_MODIFIED).is_none()); + assert!(second.headers.get("digest").is_none()); + assert!(second.headers.get("content-digest").is_none()); + assert!(second.headers.get("repr-digest").is_none()); +} + +#[cfg(feature = "multipart")] +#[tokio::test] +async fn multipart_307_replays_identical_boundary_and_payload() { + use openwire::multipart::{Form, Part}; + + let server = MockWebServer::http1().await; + server.enqueue( + MockResponse::new() + .status(StatusCode::TEMPORARY_REDIRECT) + .header("Location", "/next") + .body("redirect"), + ); + server.enqueue(MockResponse::new().body("ok")); + + let client = Client::builder().build().expect("client"); + let request = Form::new() + .text("description", "upload from OpenWire") + .part( + "file", + Part::bytes(Bytes::from_static(b"hello\n")).file_name("hello.txt"), + ) + .into_request(Request::builder().method("POST").uri(server.url("/start"))) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.status(), StatusCode::OK); + let _ = response.into_body().text().await.expect("body"); + + let first = server.take_request().await; + let second = server.take_request().await; + assert_eq!(second.method, Method::POST); + assert_eq!(first.body, second.body); + assert_eq!( + first.headers.get(http::header::CONTENT_TYPE), + second.headers.get(http::header::CONTENT_TYPE) + ); +} + +#[cfg(feature = "multipart")] +#[tokio::test] +async fn multipart_one_shot_308_is_returned() { + use openwire::multipart::{Form, Part}; + + let attempts = Arc::new(AtomicUsize::new(0)); + let server_attempts = attempts.clone(); + let server = spawn_http1(move |request: Request| { + let server_attempts = server_attempts.clone(); + async move { + server_attempts.fetch_add(1, Ordering::SeqCst); + let _ = collect_request_body(request).await; + Response::builder() + .status(StatusCode::PERMANENT_REDIRECT) + .header("location", "/final") + .body(http_body_util::Full::new(Bytes::from_static(b"stop"))) + .expect("redirect") + } + }) + .await; + let client = Client::builder().build().expect("client"); + let request = Form::new() + .part( + "file", + Part::stream(stream::iter(vec![Ok::( + Bytes::from_static(b"one-shot"), + )])), + ) + .into_request( + Request::builder() + .method("POST") + .uri(server.http_url("/one-shot-308")), + ) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.status(), StatusCode::PERMANENT_REDIRECT); + assert_eq!(attempts.load(Ordering::SeqCst), 1); +} + +#[cfg(feature = "multipart")] +#[tokio::test] +async fn multipart_302_get_rewrite_strips_content_type() { + use openwire::multipart::{Form, Part}; + + let server = MockWebServer::http1().await; + server.enqueue( + MockResponse::new() + .status(StatusCode::FOUND) + .header("Location", "/next") + .body("redirect"), + ); + server.enqueue(MockResponse::new().body("ok")); + let client = Client::builder().build().expect("client"); + let request = Form::new() + .text("a", "b") + .part("file", Part::bytes(Bytes::from_static(b"x"))) + .into_request(Request::builder().method("POST").uri(server.url("/start"))) + .expect("request"); + let response = client.execute(request).await.expect("response"); + assert_eq!(response.status(), StatusCode::OK); + let _ = response.into_body().text().await.expect("body"); + let _first = server.take_request().await; + let second = server.take_request().await; + assert_eq!(second.method, Method::GET); + assert!(second.body.is_empty()); + assert!(second.headers.get(http::header::CONTENT_TYPE).is_none()); + assert!(second.headers.get(http::header::CONTENT_LENGTH).is_none()); +} diff --git a/crates/openwire/tests/support/harness.rs b/crates/openwire/tests/support/harness.rs index 78054bb..201492a 100644 --- a/crates/openwire/tests/support/harness.rs +++ b/crates/openwire/tests/support/harness.rs @@ -1404,6 +1404,65 @@ pub async fn spawn_raw_http1_headers_then_stall_body(delay: Duration) -> RawHttp } } +fn raw_http1_request_looks_complete(request: &[u8]) -> bool { + let Some(header_end) = request.windows(4).position(|window| window == b"\r\n\r\n") else { + return false; + }; + let body = &request[header_end + 4..]; + body.windows(3).any(|window| window == b"0\r\n") && body.ends_with(b"\r\n\r\n") +} + +pub async fn spawn_raw_http1_capture_request( + observed_request: Arc>>>, +) -> RawHttpServer { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind raw http listener"); + let addr = listener.local_addr().expect("raw http listener addr"); + let (shutdown_tx, mut shutdown_rx) = oneshot::channel(); + + tokio::spawn(async move { + tokio::select! { + _ = &mut shutdown_rx => {} + accepted = listener.accept() => { + if let Ok((mut stream, _)) = accepted { + let mut request = Vec::new(); + let mut buffer = [0u8; 512]; + let deadline = tokio::time::sleep(Duration::from_millis(500)); + tokio::pin!(deadline); + loop { + tokio::select! { + _ = &mut deadline => break, + read = stream.read(&mut buffer) => { + let Ok(bytes_read) = read else { + break; + }; + if bytes_read == 0 { + break; + } + request.extend_from_slice(&buffer[..bytes_read]); + if raw_http1_request_looks_complete(&request) { + break; + } + } + } + } + *observed_request.lock().expect("observed request") = Some(request); + let _ = stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await; + let _ = stream.shutdown().await; + } + } + } + }); + + RawHttpServer { + addr, + shutdown: Some(shutdown_tx), + } +} + pub async fn spawn_raw_http1_host_guard( observed_request: Arc>>, ) -> RawHttpServer { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 86b3f9b..2a9af48 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -17,12 +17,23 @@ Related roadmap docs: ## 1. Design Priorities +- conform strictly to applicable network protocol RFCs across supported features - keep policy and transport clearly separated - keep platform integrations swappable through trait boundaries - keep connection ownership and release semantics explicit - keep the request execution path observable and predictable - keep the implementation mobile-friendly and cross-platform +RFC requirements constrain protocol behavior; code remains the reference for +what is currently implemented. Protocol changes must identify applicable +sections, endpoint roles, specification updates, and verification evidence. +Existing behavior and dependency acceptance are not proof of conformance. +Applicable mandatory requirements block delivery when violated; optional +choices and supported scope must be explicit. The requirement-to-test workflow +is documented in [testing.md](testing.md#protocol-conformance-evidence). +This is an architectural requirement, not a claim that all existing behavior +has already passed a complete RFC audit. + ## 2. Crate Boundaries ```mermaid @@ -133,6 +144,27 @@ have been returned so `call_failed` still reflects body-phase cancellation. It creates a fresh unexecuted call only when the request body is replayable, and the cloned call re-enters the canonical flow when executed. +Multipart form construction (`openwire::multipart::{Form, Part}`, feature +`multipart`) happens above `Client::execute`. The encoder concatenates DATA-only +`RequestBody` segments and returns the existing request type; it does not add an +interceptor or transport branch. `RequestBody::content_length()` is the +construction-time DATA length and is independent of `try_clone()` / +`replayable_len()`. Known-length one-shot streams use Content-Length without +becoming replayable. Arbitrary `from_body` inputs keep unknown framing length so +trailers are not suppressed. + +Strict-length bodies retain source EOF validation at every composition level. +Outgoing transport bookkeeping uses the final negotiated protocol and request +headers: HTTP/1 fixed-length requests complete when all declared bytes have +been submitted, even if hyper stops polling before source EOF. HTTP/2 continues +to require EOF/END_STREAM. Zero-length HTTP/1 bodies use the same framing rule; +read errors and incomplete sends do not emit a successful body-end event. + +Multipart boundary guards retain unresolved prefixes across any number of +chunks or Pending polls. Safe data stays in shared Bytes slices; only the +bounded unresolved prefix is copied. MIME parameters are parsed independently +of the type/subtype validator so escaped quotes and backslashes round-trip. + `BridgeInterceptor` owns HTTP request/response normalization that is above the transport byte stream but below user-facing application interceptors. That includes `Host`, `User-Agent`, request body framing headers, WebSocket handshake @@ -247,7 +279,7 @@ Default: `tls-rustls`, `platform-verifier`, `compression`, `cookies`. Codec features `gzip`, `deflate`, `brotli`, and `zstd` can be enabled independently. `compression` is the umbrella of all four. `compression-core` is the internal module gate pulled in by any codec; enabling it with no codec compiles and injects no `Accept-Encoding`. Workspace pins follow a minimum-feature policy: `tokio` and `hyper` no longer enable `full`; `tower` is `util` only; `rustls` / `tokio-rustls` keep `std` + `tls12` + `aws_lc_rs` and drop `logging`; `futures-util` keeps `std` + `async-await` and adds `io`/`sink` only where used. Production crates request Tokio `rt`/`net`/`time`/`io-util`/`sync` and hyper `client`/`http1`/`http2`. `openwire-test` additionally enables `hyper/server`. `openwire-cache` depends on `openwire` with `default-features = false`. -The built-in `Jar` is behind `cookies`. Custom `CookieJar` implementations do not need that feature. `json` gates JSON body helpers and `LoggerInterceptor` pretty-print. +The built-in `Jar` is behind `cookies`. Custom `CookieJar` implementations do not need that feature. `json` gates JSON body helpers and `LoggerInterceptor` pretty-print. `multipart` gates the `Form` / `Part` encoder; form construction stays above `Client::execute`. `openwire-cache` is intentionally an application interceptor rather than a transport feature. Fresh cache hits short-circuit before the follow-up @@ -324,11 +356,16 @@ follow-ups (pool reuse, interceptor chain integration). remain caller-visible responses. Default redirect handling follows `301`, `302`, `303`, `307`, and `308` when a valid `Location` is present and policy permits it; `300 Multiple Choices` is returned to the caller without automatic - following. Cross-origin redirects strip `Authorization`, `Cookie`, and common + following. `301` / `302` rewrite POST to GET and drop the body; other methods + keep method and body when replayable. `303` becomes GET retrieval except HEAD, + which stays HEAD. Cross-origin redirects strip `Authorization`, `Cookie`, and common API-token headers (`X-Api-Key`, `X-Auth-Token`, and related) while preserving `Proxy-Authorization` for sticky proxy routing. Preserve-method redirects - (`307` / `308`) require a replayable request body; otherwise the original - redirect response is returned to the caller. + (`307` / `308`, and non-POST `301` / `302`) require a replayable request body; + otherwise the original redirect response is returned to the caller. Retrieval + rewrites strip content-specific fields including `Content-Language`, + `Content-Location`, `Digest`, `Last-Modified`, `Content-Digest`, and + `Repr-Digest`. - The default `Jar` cookie store loads an embedded public suffix list so `Domain=.com`-style cookies are rejected (RFC 6265 §5.3) and honors `Secure`. - Client resource caps (`max_requests_total`, `max_connections_total`) are @@ -389,7 +426,7 @@ Testing layers, harness rules, and how to add cases are in - local integration tests (split by topic under `crates/openwire/tests/`) guard retry/redirect/auth/cookie flow, proxy behavior, and connection lifecycle -- `--all-features` covers optional `websocket` and `json` paths +- `--all-features` covers optional `websocket`, `json`, and `multipart` paths - the live-network suite is opt-in and not part of the required CI gate Primary verification commands: diff --git a/docs/multipart-design.md b/docs/multipart-design.md new file mode 100644 index 0000000..1dbc679 --- /dev/null +++ b/docs/multipart-design.md @@ -0,0 +1,594 @@ +# Add Multipart Form Uploads + +Status: implemented behind the opt-in `multipart` feature. Strict conformance to +applicable RFC requirements remains a design and delivery constraint. Protocol +evidence for the rows below is recorded against named tests; this does not +certify unrelated features or the entire library. + +## Feasibility Assessment + +OpenWire can already transport multipart bytes: `RequestBody::from_stream` and +`RequestBody::from_body` accept incremental payloads +(`crates/openwire-core/src/body.rs`, lines 74–122), and `Client::execute` accepts +`http::Request` (`crates/openwire/src/client.rs`, lines 755–769). +The implementation adds a form encoder, replay-preserving body composition, and +independent length metadata. No connector or protocol replacement is required. +Feasible with caveats: body composition must preserve replay semantics, boundary +validation must be deterministic, and touched HTTP framing/follow-up behavior +must pass independent RFC-derived acceptance tests. + +## Current Surface Inventory + +- `openwire_core::RequestBody::{from_bytes, from_stream, from_stream_with_length, from_body, concat, content_length}` — memory, stream, known-length one-shot, arbitrary HTTP body, and DATA-only composition (`crates/openwire-core/src/body.rs`). +- `openwire_core::RequestBody::{try_clone, replayable_len}` — replayability is cached; `replayable_len()` returns a length only when the body is replayable and its complete length is known. +- `http_body::Body for openwire_core::RequestBody` — DATA/frame polling, remaining `size_hint()`, and end-state, including composite and strict-length streams. +- `openwire::bridge::normalize_body_headers` — frames from `content_length()`; rejects present unknown-length HTTP/1.0 bodies. +- `openwire::multipart::{Form, Part}` — opt-in encoder above `Client::execute`. +- `openwire::Client::execute` and `ClientBuilder` pipeline assembly — unchanged public request type and canonical chain. +- `openwire::policy::follow_up::RequestSnapshot::into_redirect_request` — 301/302 POST-to-GET; PUT/PATCH preserved when replayable; 303 GET except HEAD; 307/308 preserve method. +- `openwire::policy::follow_up::authenticate_response` — authentication follow-ups still require replayability. +- `openwire::transport::body::ObservedOutgoingBody` — uses final HTTP/1 framing length for completion bookkeeping, independently of source EOF; HTTP/2 remains EOF-driven. +- `openwire::logging::capture_request_body` — unchanged; generic body contract feeds its existing behavior. + +## Design + +### RFC conformance contract + +Scope: the client-side form encoder and its HTTP/1.0, HTTP/1.1, HTTP/2, +follow-up, and connection-lifecycle integration. RFCs define protocol +requirements; project choices below select behavior within those requirements. +Code is evidence of current behavior, not a substitute for a normative source. +Use applicable updates and verified errata when implementing each row. + +| ID | Authority / applicable obligation | Role and level | Owner | Required evidence | Status | +| --- | --- | --- | --- | --- | --- | +| MP-1 | [RFC 2046 §5.1.1](https://www.rfc-editor.org/rfc/rfc2046.html#section-5.1.1), [RFC 7578 §4.1](https://www.rfc-editor.org/rfc/rfc7578.html#section-4.1): delimiter syntax, bounded boundary, collision exclusion | sender: required syntax / MUST NOT | encoder and payload guard | exact bytes; collisions across every split | verified: `multipart::tests::encodes_text_and_bytes_with_rfc_shape`, `stream_collision_is_rejected_before_complete_prefix`, `tests/multipart.rs::stream_collision_never_emits_forbidden_sequence`, `boundary_collisions_are_rejected_across_all_three_way_splits`, `safe_stream_payload_is_preserved_across_all_three_way_splits`, `boundary_guard_slices_large_safe_chunks_and_retains_only_candidate_bytes` | +| MP-2 | [RFC 7578 §§4.2–4.3](https://www.rfc-editor.org/rfc/rfc7578.html#section-4.2), [§5.2](https://www.rfc-editor.org/rfc/rfc7578.html#section-5.2): disposition, repeated fields, ordering | sender: MUST / SHOULD | form serializer | required name; duplicate/order fixtures | verified: `keeps_duplicate_fields_in_insertion_order`, `allows_empty_values_and_zero_byte_files` | +| MP-3 | [RFC 7578 §§2, 4.2, 4.5–4.8, 5.1](https://www.rfc-editor.org/rfc/rfc7578.html#section-4.2): filename, charset, permitted part fields | sender: MUST NOT / SHOULD NOT / MAY; choices below | metadata validator | escaping, Unicode, forbidden fields and charset conflicts | verified: `escapes_quotes_and_backslashes_and_encodes_non_ascii_filenames`, `rejects_control_characters_in_names`, `rejects_media_ranges_duplicates_nested_multipart_and_charset_conflicts` | +| MIME-1 | [RFC 2045 §5.1](https://www.rfc-editor.org/rfc/rfc2045.html#section-5.1): media-type/parameter syntax | sender: required syntax | metadata validator | concrete media types; malformed values; controls | verified: `rejects_media_ranges_duplicates_nested_multipart_and_charset_conflicts`, `mime_parameters_support_quoted_pairs_and_reject_incomplete_syntax` | +| HTTP-1 | [RFC 9112 §§6.1–6.3](https://www.rfc-editor.org/rfc/rfc9112.html#section-6.1): valid request framing and unambiguous length | sender: MUST / MUST NOT | bridge | CL/TE exclusion; whole-body byte count; HTTP/1.0 rejection | verified: `http11_upload_matches_encoded_body_and_content_type`, `known_length_one_shot_form_uses_content_length`, `unknown_length_stream_form_uses_http11_chunked`, `http10_unknown_length_form_is_rejected_before_io`, `known_length_one_shot_stream_uses_content_length` | +| HTTP-2 | [RFC 9113 §§8.1–8.2.2](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.1): content length, trailers, prohibited connection fields | sender: MUST / MUST NOT | protocol binding | actual H2 headers and DATA totals; TE restrictions | verified: `http2_upload_omits_transfer_encoding_and_matches_encoded_bytes` | +| POLICY-1 | [RFC 9110 §9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2), [§15.4](https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4): replay is distinct from retry permission; redirect semantics | client: MUST NOT / SHOULD / SHOULD NOT / MAY | follow-up coordinator | independent method/status table; committed POST cases | verified: `redirect_method_and_body_matrix_matches_rfc9110`, `put_301_second_hop_preserves_method_and_body`, `multipart_307_replays_identical_boundary_and_payload`, `replayable_multipart_form_is_authenticated_on_401` | +| LIFE-1 | [RFC 9112 §9.3](https://www.rfc-editor.org/rfc/rfc9112.html#section-9.3), [RFC 9113 §5.4](https://www.rfc-editor.org/rfc/rfc9113.html#section-5.4): safe failure handling and connection/stream disposition | client: required error handling; conservative reuse policy | transport lifecycle | no unsafe H1 reuse after incomplete upload; H2 stream failure | verified: `declared_length_mismatch_does_not_emit_suffix`, `source_read_error_does_not_read_later_parts`, `known_length_one_shot_form_is_not_retried_on_connection_failure`, `coalesced_http2_421_does_not_retry_one_shot_form`, `known_length_composites_emit_body_completion_once`, `http2_waits_for_eof_even_after_declared_data_is_read`, `fixed_length_does_not_turn_source_errors_into_success` | + +Each row must gain named positive/negative tests and recorded command results +before it can become verified. Applicable mandatory violations block delivery. +Passing these rows does not certify unrelated features or the entire library. + +Verified errata relevant to fixtures/terminology include +[RFC 7578 erratum 4676](https://www.rfc-editor.org/errata/eid4676), which corrects +the section 4.6 delimiters, and +[RFC 9113 erratum 7013](https://www.rfc-editor.org/errata/eid7013), which corrects +the DATA frame name in section 6.1. Do not copy the uncorrected examples or +treat merely reported errata as accepted corrections. Recheck the applicable +errata index when implementing each matrix row; this is not a completed audit +of all referenced RFCs. + +### Key design decisions + +1. **Start with `multipart/form-data` behind an opt-in `multipart` feature.** + Support text, binary, and stream parts, including repeated names and explicit + per-part media types. General MIME subtypes and response multipart parsing + are separate work; they do not block uploads. +2. **Put `Form` and `Part` in `openwire::multipart`.** Encode before + `Client::execute`, producing the existing `RequestBody`. A multipart + interceptor or transport branch would put representation rules into the + execution chain and complicate follow-ups. +3. **Add generic DATA-only composition to `openwire-core`.** Concatenate header + bytes, payload bodies, separators, and the closing delimiter without + collecting payloads. A multipart-specific core enum variant would couple + shared body infrastructure to MIME; a general replay factory trait would + introduce unnecessary lifecycle contracts for the first version. +4. **Separate total length from replayability.** A known-length one-shot stream + can use Content-Length while remaining ineligible for replay. Retain the + existing `try_clone()` protocol and `replayable_len()` compatibility API. +5. **Bind Content-Type and body in one request helper.** `Form::into_request` + replaces Content-Type with the generated value; `Form::into_parts` is the + lower-level escape hatch. Adding MIME metadata to every request body or a + new client request-builder hierarchy is unnecessary for this feature. +6. **Accept app-owned streams rather than file paths.** File bytes can be read + incrementally through `Part::stream` or `Part::stream_with_length`. + Runtime-specific file opening, MIME guessing, and reopening mutable files + are outside the encoder; adding filesystem I/O to core would weaken the + runtime boundary. +7. **Validate boundaries rather than relying solely on randomness.** Scan + in-memory payloads before construction and guard one-shot streams while + polling. Keep the scanner in the multipart layer. The first version exposes + text/Bytes/stream inputs, without `Part::body(RequestBody)`; a generic body + transform that preserves replay would require a separate contract. + +### Public interfaces + +**File: `crates/openwire-core/src/body.rs`** — additive APIs; existing +constructors and method signatures remain available. + +```rust +impl RequestBody { + // Complete length at construction, independent of replayability. + pub fn content_length(&self) -> Option; + + // Present, DATA-only composition of fresh, unpolled children. + pub fn concat(bodies: Vec) -> Result; + + // Counts bytes and reports length mismatches while the source is polled. + pub fn from_stream_with_length(stream: S, length: u64) -> Self + where + S: Stream> + Send + Sync + 'static, + E: Into + 'static; +} +``` + +- Store initial content length independently for DATA-only constructors. + `from_body` keeps unknown framing length and remains non-replayable, even + when its underlying `size_hint()` is exact: DATA size alone cannot establish + that a body has no trailers. This preserves existing HTTP/1.1 chunked trailer + behavior. Use the declared-length stream constructor for fixed-length + one-shot DATA inputs; do not infer framing length from arbitrary bodies. +- `replayable_len()` keeps its existing meaning: return a length only when the + body is replayable and its complete length is known. Cache replayability for + composite bodies instead of cloning to answer a metadata query. +- A private composite representation retains the children and a polling cursor. + `try_clone()` rewinds every child, including already-emitted children, and + succeeds only if every child can replay. Preserve all encoded headers and the + original boundary. An error does not change a one-shot body into a replayable + body. +- Track whether a `RequestBody` has been polled; reject started children at + composition time. Otherwise a consumed Bytes child can emit nothing while + its clone emits the original payload. A fresh clone is a valid input. +- Sum known lengths with checked arithmetic; reject overflow. Unknown lengths + produce an unknown total. Empty composition produces a present explicit-empty + body, while an empty form is rejected by the form encoder. +- `Body::size_hint()` describes remaining bytes, while `content_length()` stays + stable. Correct the existing Bytes branch, which currently reports the + original length after emission (`body.rs`, lines 165–170). +- Strict-length streams remain non-replayable. Reaching the declared byte count + does not imply source EOF: `Body::is_end_stream()` keeps the same EOF contract + at the top level and inside any composition. + Reject an oversized chunk before forwarding it and reject early EOF. In a + multipart body this validation must finish before emitting the part suffix. + Validation occurs when polled; standalone consumers can stop at their + advertised length, whereas the multipart suffix requires advancing past the + payload first. +- Report composite completion as soon as the final DATA segment is exhausted, + without requiring another EOF poll. A strict-length child remains incomplete + until source EOF is verified, even when its remaining size is zero. +- Transport observes framing separately from source EOF. After actual protocol + binding, an HTTP/1 request with Content-Length and no Transfer-Encoding can + complete outgoing byte bookkeeping once that length has been submitted, + including zero-length and nested composite bodies. HTTP/2 still waits for + body EOF/END_STREAM. Neither path turns a reported body error into success. +- Concatenation rejects trailers and other non-DATA frames, returns an error + once, then terminates. It must never emit later separators after an error. + A `from_body` child has unknown composition length, regardless of its raw + size hint. Regular `from_body` retains its existing frame-forwarding and + framing behavior outside composition. +- Bound work per poll when skipping empty children/frames. Do not prefetch + subsequent payloads or spawn an upload task. + +**File: `crates/openwire/src/multipart.rs`** — public API sketch, with private +fields and no public dependency on the MIME parser. + +```rust +pub struct Form { /* ordered fields */ } +pub struct Part { /* payload and validated metadata */ } + +impl Form { + pub fn new() -> Self; + pub fn text(self, name: impl Into, value: impl Into) -> Self; + pub fn part(self, name: impl Into, part: Part) -> Self; + pub fn into_parts(self) -> Result<(HeaderValue, RequestBody), WireError>; + pub fn into_request( + self, + builder: http::request::Builder, + ) -> Result, WireError>; +} + +impl Part { + pub fn text(value: impl Into) -> Self; + pub fn bytes(value: impl Into) -> Self; + pub fn stream(stream: S) -> Self + where + S: Stream> + Send + Sync + 'static, + E: Into + 'static; + pub fn stream_with_length(stream: S, length: u64) -> Self + where + S: Stream> + Send + Sync + 'static, + E: Into + 'static; + pub fn file_name(self, name: impl Into) -> Self; + pub fn mime_str(self, value: &str) -> Result; +} +``` + +`Form` also implements `Default`. `file_name` stores a display filename rather +than opening a path. Validate field names and filenames during form conversion; +`mime_str` validates immediately. Use optional `mime = "0.3"` internally for +media-type parsing, without exposing parser types in public signatures. Its +[`Mime` parser](https://docs.rs/mime/0.3.17/mime/struct.Mime.html#impl-FromStr-for-Mime) +validates the type/subtype. Parameters use a complete token/quoted-string parser +with quoted-pair decoding, closing-quote and separator validation, and duplicate +name rejection. This avoids a dependency parser rejecting valid escaped quotes +before the parameter parser runs. Serialization quotes/escapes decoded values +as required; parser acceptance alone is not proof of Content-Type validity. + +**File: `crates/openwire/examples/post_multipart.rs`** — consumer +example, using the existing HTTP request builder. + +```rust +use bytes::Bytes; +use http::Request; +use openwire::{multipart::{Form, Part}, Client}; + +let client = Client::builder().build()?; +let request = Form::new() + .text("description", "upload from OpenWire") + .part( + "file", + Part::bytes(Bytes::from_static(b"hello\n")) + .file_name("hello.txt") + .mime_str("text/plain; charset=utf-8")?, + ) + .into_request( + Request::builder() + .method("POST") + .uri("https://example.com/upload"), + )?; +let response = client.execute(request).await?; +``` + +For large payloads substitute a stream part. The stream stays owned by the +request, follows downstream polling, and drops with the request. A known length +does not authorize reopening or replaying it. + +### Encoding rules and failure behavior + +Normative encoding obligations are tracked in MP-1 through MIME-1 above. +The following project choices implement that supported scope: + +- Keep insertion order and repeated names; multiple files use separate parts + with the same name. Each part has `Content-Disposition: form-data; name=...`. +- Use UTF-8 text and field names; add `text/plain; charset=utf-8` for text parts. + Default binary/stream parts to `application/octet-stream` unless overridden. +- Escape DQUOTE and backslash in quoted parameters; reject CR, LF, NUL, and + other control characters in names/metadata. Do not percent-encode field names + as though they were URL query keys. +- Encode non-ASCII filename bytes with UTF-8 percent encoding; escape quoted + parameters and encode literal percent signs unambiguously. This is the + selected filename policy, not a claim that RFCs forbid other permitted + encodings. Do not generate `filename*`. +- Do not expose arbitrary part headers or generate Content-Transfer-Encoding + or per-part Content-Length. +- Require concrete media types rather than wildcard ranges. Reject duplicate + parameter names and controls; reject nested `multipart/*` as an explicit + first-version scope limit. Parser success is insufficient for these checks. +- Library-created text remains UTF-8: reject conflicting charset declarations + and retain/add `charset=utf-8` when labeling it `text/plain`. Do not mechanically + add charset to unrelated media types. Bytes/streams remain opaque app-owned + content; validation does not prove an arbitrary file's format matches its label. + +Additional implementation choices: + +- Choose boundary candidates during conversion using 24 random bytes and a + token-safe hexadecimal representation, reusing workspace `getrandom`. + Keep the result within the 70-character limit. Scan all Bytes payloads before + committing a candidate; retry collisions under a bounded attempt budget, + then return a construction error if selection fails. Freeze the selected + boundary and header bytes for every replay. No timestamp fallback. +- Store private payload variants for memory Bytes and erased one-shot streams + with optional declared length. Attach a multipart-owned collision guard to + each stream before converting it to `RequestBody::from_stream` or + `from_stream_with_length`. This preserves known DATA length without wrapping + the result in `from_body`; memory payloads remain replayable after scanning. +- The guard checks the start of each payload and every CRLF-started line for + the full dash-boundary prefix. Retain candidate-prefix bytes across chunks + and Pending polls, including arbitrarily many one-byte chunks. Scan retained + bytes and the new chunk as one logical view without copying the new chunk; + release only a proven-safe prefix and preserve a trailing CR. Use Bytes + slices for the safe chunk region and O(boundary length) storage for unresolved + bytes. Reject a collision before emitting its complete prefix, even + when the following bytes are not CRLF or closing dashes. Return a body error, + emit no later separator/closing delimiter, and do not mark encoder/body-write + completion as successful. + Do not pre-read an entire stream or silently change its bytes/boundary. +- Serialize each part as delimiter + headers + blank line + raw DATA + CRLF, + followed by the closing delimiter. Reject zero-part forms; allow empty field + values and zero-byte file payloads. Protocol lines use CRLF with no delimiter + padding. Payload CR/LF bytes are preserved exactly. +- `into_request` uses header insertion to replace all existing Content-Type + values, rather than appending a second value. Clear stale Content-Length and + Transfer-Encoding; bridge computes framing from the resulting body. Reject + a pre-existing Content-Encoding until an explicit encoding transform is + supported, rather than labeling the raw form as already compressed. +- Invalid names, MIME values, started bodies, or length overflow fail before + network I/O as `InvalidRequest`. Entropy failure is an internal construction + error. Payload read/length/collision errors terminate the upload as body errors; + preserve the original read error as the cause. + +### Framing and follow-ups + +| Encoded form | Length | Replay | Framing / follow-up behavior | +| --- | --- | --- | --- | +| Text and Bytes only | exact | yes | Content-Length; existing policy may replay | +| Includes a declared-length one-shot stream | exact | no | Content-Length; no body-preserving replay | +| Includes an unknown-length stream | unknown | no | HTTP/1.1 chunked; HTTP/2 DATA without Transfer-Encoding | + +Change bridge to read `content_length()`. Reject present unknown-length bodies +for HTTP/1.0 before sending; neither connection-close request delimiting nor +HTTP/1.1 chunked coding is a valid substitute. Do not silently buffer or change +the requested protocol. Verify framing at the actual protocol-binding boundary. + +No HTTP/1.1 request may carry both Content-Length and Transfer-Encoding. H2 +must omit prohibited connection fields, with `TE` restricted to `trailers`. +An emitted Content-Length covers all encoded content bytes. Preserve legitimate +outer HTTP trailers for ordinary bodies while rejecting trailers inside parts. + +Use `try_clone()` only to establish replay capability. Retry/redirect/auth +decisions still require the applicable policy and protocol conditions: + +- 307/308 return the original response when a one-shot payload cannot replay. +- For 301/302 choose the permitted POST-to-GET behavior; preserve other methods + and their body when replayable. For 303 choose GET retrieval (retain HEAD for + HEAD). For 307/308 preserve the method. Remove content-specific fields when + switching to retrieval, using a spec-derived list rather than copying the + current implementation's list. +- Origin/proxy authentication follow-ups require replayable bodies. +- Replayable does not mean retryable: preserve the existing limits on retrying + a committed non-idempotent POST. + +The current 301/302 rewrite is broader than this policy. Correct the touched +coordinator path and its independent method/status tests; do not declare it +compliant solely because it predates multipart. Read errors, collisions, and +length failures leave the upload incomplete: close an unsafe H1 connection and +handle H2 failure at the appropriate stream scope without unsafe connection reuse. + +## Phased Implementation + +## Phase 1: Extend Generic Request Bodies + +**File: `crates/openwire-core/src/body.rs`** + +- Add independent total-length metadata, DATA-only `concat`, private composite + state, started-input validation, and strict-length stream construction. +- Preserve existing absent/explicit-empty and clone behavior; correct Bytes + remaining-size reporting. +- Add unit coverage for known-length one-shot bodies, replay after partial and + complete consumption, empty composition, length overflow, trailers, terminal + errors, Pending behavior, and length validation at actual EOF. + +**File: `crates/openwire/src/bridge.rs`** + +- Read `content_length()` for framing. Test a known-length non-replayable body + and preserve normalization of absent, empty, and unknown-length bodies. + Keep arbitrary `from_body` inputs on their existing framing path, including + exact-size inputs that can still emit trailers. +- Reject present unknown-length HTTP/1.0 requests via the existing fallible + normalization path. Do not serialize an undelimited request or chunked 1.0. + +**Files: `crates/openwire/src/transport/body.rs`, `crates/openwire/src/transport/service.rs`** + +- Pass the actual connection protocol to outgoing instrumentation and empty-body + dispatch. Capture final Content-Length only for HTTP/1 without Transfer-Encoding. +- Complete HTTP/1 byte bookkeeping even when a composite source has not received + an EOF poll. Keep HTTP/2 source errors, resets, and cancellation before EOF + distinct from successful completion; preserve arbitrary-body trailers. + +This phase compiles without any multipart feature and establishes the reusable +body behavior independently of MIME. + +## Phase 2: Add the Form Encoder and Public Feature + +**File: `crates/openwire/Cargo.toml`** + +- Add `multipart = ["dep:getrandom", "dep:mime"]` and optional `mime = "0.3"`. + Keep defaults unchanged and declare the multipart example's required feature. + +**File: `Cargo.lock`** + +- Resolve the new optional parser dependency with the repository toolchain; + keep the declared Rust 1.80 minimum in view. + +**File: `crates/openwire/src/lib.rs`** + +- Export `pub mod multipart` under the feature; core remains unaware of MIME. + +**File: `crates/openwire/src/multipart.rs`** + +- Implement `Form`, `Part`, ordered encoding, validation, random boundary + selection with memory scanning, incremental collision guards for one-shot + streams, and the paired header/body conversion methods. +- Construct reusable Bytes header segments and concatenate them with payloads. + Do not wrap the final form with `from_body`, which would discard replay. +- Add deterministic wire fixtures based on RFC examples, plus escaping, + non-ASCII names/filenames, duplicate fields, empty values, and binary payloads. +- Test every boundary split, payload-start/end collisions, prefix-only matches, + Pending polls, candidate regeneration, and terminal collision failure. Check + protocol CRLF/padding separately from byte-for-byte payload preservation. +- Test media ranges, malformed/duplicate parameters, text charset conflicts, + UTF-8 preservation, and rejection of unsupported nested multipart metadata. + +## Phase 3: Correct Touched HTTP Follow-up Behavior + +**File: `crates/openwire/src/policy/follow_up.rs`** + +- Restrict the selected 301/302 POST-to-GET rewrite to POST. Preserve other + methods and require body replay when preserving content; do not silently + replace a one-shot preserved body with an absent body. +- Use the independent RFC 9110 method/status table for 303/307/308 as well. +- Complete content-specific header cleanup on retrieval rewrites, covering + Content-Language, Content-Location, Digest, and Last-Modified in addition to + framing and content-type/encoding fields. Account for newer applicable + field specifications during implementation. +- Correct the in-module tests and comments that currently treat all non-GET/HEAD + 301/302 requests as GET. Expected values come from the RFC plus documented + permitted policy choices, not the old implementation. + +The rest of the existing retry/auth orchestration remains reusable, subject to +the acceptance evidence below. Any newly discovered mandatory violation on +this integration path blocks completion until resolved. + +## Phase 4: Add Examples and Synchronize Documentation + +**File: `crates/openwire/examples/post_multipart.rs`** + +- Provide a complete runnable text/binary form example and show how to replace + the payload with a one-shot stream. State the required feature. + +**File: `README.md`** + +- Document the opt-in feature, request helper, Content-Type ownership, and the + distinction between length and replayability. + +**File: `docs/ARCHITECTURE.md`** + +- Place form construction above `Client::execute`; document generic body + composition and independent length/replay metadata. + +**File: `docs/testing.md`** + +- Add multipart feature verification and deterministic encoding expectations. + +**File: `docs/multipart-design.md`** + +- Update proposal status and reconcile APIs with the implementation as it lands. + +## Phase 5: Verify Wire Behavior and RFC Policy Integration + +**File: `crates/openwire/tests/events.rs`** + +- Cover known-length composites ending in Strict bodies, including zero length, + nonempty prefixes, and nested composition. The local server collects the whole + request before replying; assert matching payload and one start/end event pair. + +**File: `crates/openwire/src/transport/body.rs` (outgoing unit tests)** + +- Cover HTTP/1 framing completion without EOF polling, actual HTTP/2 waiting for + EOF after all DATA, source errors, incomplete sends, zero-length framing, and + Transfer-Encoding excluding fixed-length completion. + +**File: `crates/openwire/tests/multipart.rs`** + +- Exercise HTTP/1.1 and local HTTP/2 uploads using `openwire-test`, with the + feature disabled cleanly gating this target's tests. +- Verify exact encoded body/header agreement, known-length one-shot framing, + unknown-length framing, and application/network interceptor visibility. +- Assert CL/TE exclusion, actual H2 field constraints, exact encoded byte + totals, and early rejection of unknown-length HTTP/1.0 with no upload I/O. +- Test a producer that returns Pending, source read errors, cancellation, and + source drop. Assert no later part is read after failure/cancellation. +- Inject boundary collisions at every chunk split and assert the complete + forbidden sequence and closing boundary are never emitted. Verify H1 + teardown after incomplete upload and appropriate H2 stream cleanup. +- Check too-short/too-long declarations, including declared zero with data and + exactly N bytes followed by another chunk; suffixes must not hide errors. +- Verify request-body events count encoded bytes and complete exactly once, + including the final frame path that receives no extra EOF poll from hyper. + +**File: `crates/openwire/tests/redirect.rs`** + +- Add feature-gated 307/308 replay with byte-identical boundary and payload, + one-shot refusal, and GET rewrites with multipart headers removed. +- Include PUT/PATCH in 301/302 tests, retrieval header cleanup, and one-shot + preserved-body refusal. These supplement feature-independent policy tests. + +**File: `crates/openwire/tests/auth.rs`** + +- Add feature-gated replayable and one-shot form authentication cases. + +**File: `crates/openwire/tests/compression_bridge.rs`** + +- Verify a declared-length DATA-only one-shot stream uses Content-Length + independently of multipart; normalize a caller's stale framing headers. +- Verify an arbitrary body with exact DATA size retains chunked HTTP/1.1 + framing and its declared trailers, including zero DATA bytes. A raw size hint + must not be mistaken for permission to suppress trailing frames. + +**File: `crates/openwire/tests/pool_http2.rs`** + +- Cover a known-length one-shot form failing without automatic body replay. + +Run focused tests first, then the existing workspace gates: + +```bash +cargo test -p openwire-core --lib +cargo test -p openwire --features multipart --test multipart --test redirect --test auth --test compression_bridge --test pool_http2 +cargo check -p openwire --no-default-features --features multipart --lib +cargo fmt --all --check +cargo clippy --workspace --all-targets --all-features -- -D warnings +cargo test --workspace --all-targets +cargo test --workspace --all-targets --all-features +``` + +Use local servers and fixed encoder fixtures, without public-internet tests. +HTTP/2 checks concern headers, payloads, and OpenWire policy rather than +retesting h2 framing. Audit dependency/MSRV compatibility when updating the lock. + +Verification after the multipart review fixes (2026-11-12): + +- `cargo test --workspace --all-targets --quiet` — passed. +- `cargo test --workspace --all-targets --all-features --quiet` — passed. +- `cargo clippy --workspace --all-targets --all-features -- -D warnings` — passed. +- `cargo check -p openwire --no-default-features --features multipart --lib` — passed. +- `cargo fmt --all --check` and `git diff --check` — passed. + +The three reported failure scenarios were reproduced before applying the fixes. The current suite +also checks byte preservation and zero-copy output, rejected malformed MIME +parameters, and unsuccessful completion after source errors or H2 cancellation. + +## Architectural Notes + +- **Compatibility:** body/form APIs are additive and optional. HTTP/1.0 + undelimited uploads become explicit errors; 301/302 method preservation is a + user-visible correction for non-POST methods. No signature migration is + required, but release notes must describe these corrections. Ordinary + arbitrary-body trailer framing remains preserved on applicable protocols. +- **Trait bounds:** retain the current `Send + Sync + 'static` body contract. + No new object-safe replay trait or connector trait changes are needed. +- **Memory and side effects:** the encoder retains metadata and shared Bytes + segments, with memory-payload scanning, bounded boundary-selection attempts, + and one fixed boundary per built form. Stream collision detection uses + O(boundary length) retained prefix bytes and incremental payload polling. + Existing `LogLevel::Body` can still collect an entire replayable form for + logging; the encoder's allocation guarantee does not cover that opt-in + observer. One-shot bodies continue to be omitted from request-body logging. +- **Execution chain:** no bypass of application interceptors, follow-up + coordination, bridge, network interceptors, transport, or connection release. +- **Audited without planned edits:** `crates/openwire/src/client.rs`, + `crates/openwire/src/transport/protocol.rs`, and + `crates/openwire/src/logging.rs`; the generic body contract feeds their + existing behavior. Their existing integration still requires RFC acceptance + evidence; adjust this inventory if that evidence exposes a violation. +- **Dependencies:** only `openwire` gains optional MIME parsing and reuses its + optional randomness dependency. No new core or Tokio/filesystem dependency. +- **Deferred:** file-path convenience, arbitrary RequestBody parts with + replay-preserving guards, replay factories for stable external sources, + general MIME subtypes, and response multipart parsing. They need + separate contracts and are unnecessary for streaming form uploads. +- **Documentation audit:** README describes the implemented feature and API. + ARCHITECTURE also records transport completion versus source EOF and bounded + multipart collision detection. Keep these aligned with the implementation. + +## File Change Summary + +Implementation has landed. Keep this document aligned with the code; RFC rows +above list the named tests that currently provide evidence. + +- `AGENTS.md` -- persist project-wide strict RFC requirements. +- `Cargo.lock` -- resolve the optional MIME parser dependency. +- `crates/openwire-core/src/body.rs` -- length/replay separation, composition, strict-length streams, and unit tests. +- `crates/openwire/Cargo.toml` -- optional multipart feature, dependency, and example gate. +- `crates/openwire/examples/post_multipart.rs` -- text, binary, and stream usage. +- `crates/openwire/src/bridge.rs` -- length-based framing and HTTP/1.0 validation. +- `crates/openwire/src/lib.rs` -- feature-gated public multipart module. +- `crates/openwire/src/multipart.rs` -- form/part API, metadata validation, and collision-safe incremental encoding. +- `crates/openwire/src/policy/follow_up.rs` -- RFC-derived redirect method and header handling. +- `crates/openwire/src/transport/body.rs` -- protocol-specific outgoing completion and failure bookkeeping. +- `crates/openwire/src/transport/service.rs` -- pass the negotiated protocol to instrumentation and dispatch. +- `crates/openwire/tests/auth.rs` -- multipart authentication replay coverage. +- `crates/openwire/tests/compression_bridge.rs` -- known-length one-shot framing and arbitrary-body trailer preservation. +- `crates/openwire/tests/events.rs` -- completion events for zero-length and nested composite uploads. +- `crates/openwire/tests/multipart.rs` -- wire, backpressure, cancellation, and events. +- `crates/openwire/tests/pool_http2.rs` -- one-shot multipart retry constraints. +- `crates/openwire/tests/redirect.rs` -- replay, boundary stability, and GET rewrites. +- `README.md` -- feature and upload usage. +- `docs/ARCHITECTURE.md` -- strict RFC priority, encoding placement, and body capabilities. +- `docs/multipart-design.md` -- keep the design aligned with implementation. +- `docs/testing.md` -- RFC requirement-to-evidence rules and multipart verification entry points. diff --git a/docs/testing.md b/docs/testing.md index 6085089..56c4570 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -17,14 +17,47 @@ to freeze whatever the current code does. Suffix List `tests.txt`, `EventListener` rustdoc, and `ARCHITECTURE.md`. - If a test fails, the implementation is wrong or the spec citation in the test is wrong. Do not “fix” the test by copying the implementation. -- Intentional deviations must be named, cited, and tiny. There is currently - no cookie-store implicit-`*` carve-out: OpenWire applies RFC 6265 §5.3 with - the PSL algorithm, including unknown TLDs. +- Applicable mandatory RFC requirements cannot be waived as compatibility + exceptions. There is currently no cookie-store implicit-`*` carve-out: + OpenWire applies RFC 6265 §5.3 with the PSL algorithm, including unknown TLDs. - Do not mock `Client`. Use table-driven unit tests for policy and `MockWebServer` / `spawn_http1` for the wire. Mockall-style trait mocks are unnecessary for this crate: `StaticDnsResolver`, handler servers, and in-module `RequestSnapshot` tests already isolate seams. +## Protocol conformance evidence + +Strict RFC conformance is required throughout the supported protocol surface. +Use the applicable RFC version, its updates, and verified errata. Interpret +normative language using [BCP 14](https://www.rfc-editor.org/rfc/rfc8174.html); +do not silently promote optional behavior to a mandatory requirement. + +For each protocol change, keep a requirement matrix in its design or topic +documentation. Every row records: + +- RFC and section, sender/recipient role, applicability, and requirement level. +- Observable invariant and the implementation owner responsible for it. +- Independently derived positive, negative, wire, and failure-path cases. +- Explicit status: planned, implemented but unverified, or verified with the + relevant test names and command results. + +Applicable MUST/MUST NOT violations block delivery. Follow SHOULD/SHOULD NOT +by default; an RFC-permitted exception requires its specific rationale and +tests. Record MAY choices and deliberate feature limits separately from +protocol violations. Existing behavior, OkHttp/Fetch compatibility, and a +dependency accepting bytes do not replace RFC-derived expected results. + +Test library-owned integration boundaries as well as pure encoders: framing, +actual negotiated protocol, redirects/retries, error propagation, and connection +reuse after incomplete exchanges. Dependency-owned parsers and codecs need +boundary/interop evidence, rather than a duplicate implementation of their +internal test suite. A feature's passing suite does not establish conformance +for the entire library. Discovered mandatory violations must be fixed or block +delivery of the affected work; do not relabel them as verified behavior. + +The multipart encoder tracks its requirement-to-evidence matrix in +[multipart-design.md](multipart-design.md#rfc-conformance-contract). + ## Layers | Layer | What it proves | Where | Required CI | @@ -52,11 +85,12 @@ cargo check --workspace --all-targets cargo test --workspace --all-targets ``` -Optional features, including `websocket` and `json`: +Optional features, including `websocket`, `json`, and `multipart`: ```bash cargo test --workspace --all-targets --all-features cargo test -p openwire --features websocket --test websocket +cargo test -p openwire --features multipart --test multipart --test redirect --test auth --test compression_bridge --test pool_http2 ``` Required CI runs both default-feature tests and `--all-features`. Default @@ -107,7 +141,7 @@ Concurrent or dispatcher-style peers still use `spawn_http1` closures. A custom - New integration cases go in the matching topic file under `crates/openwire/tests/` (`redirect.rs`, `cookie.rs`, `proxy.rs`, `pool_http2.rs`, `timeout_cancel.rs`, `auth.rs`, `events.rs`, - `compression_bridge.rs`, `scheduler_limits.rs`). Shared helpers live in + `compression_bridge.rs`, `scheduler_limits.rs`, `multipart.rs`). Shared helpers live in `tests/support/`. `integration.rs` is smoke only. - New public-internet tests must be `#[ignore]` and documented as smoke. @@ -117,7 +151,7 @@ Concurrent or dispatcher-style peers still use `spawn_http1` closures. A custom | --- | --- | --- | | `crates/openwire/data/public_suffix_list.dat` | Runtime public suffix list for the cookie jar | vendored | | `crates/openwire/data/psl_tests.txt` | Cookie Domain / eTLD+1 vectors from publicsuffix.org | vendored; `tests/psl_corpus.rs` asserts official expected values | -| RFC 9110 redirect method matrix | Follow vs rewrite vs stop | partial in unit + integration tests | +| RFC 9110 redirect method matrix | Follow vs rewrite vs stop | unit matrix plus `tests/redirect.rs` | | Autobahn Testsuite | RFC 6455 WebSocket | planned, nightly | | http-tests/cache-tests | RFC 9111 behavior oracle | planned, not a 100% gate |