diff --git a/.github/workflows/rust-checks.yml b/.github/workflows/rust-checks.yml index 0e08f51..ae7fa02 100644 --- a/.github/workflows/rust-checks.yml +++ b/.github/workflows/rust-checks.yml @@ -37,3 +37,16 @@ jobs: with: command: clippy args: --all --lib -- -D warnings -A deprecated -A unused-variables -A unused-imports + + vendored-tonic-web-wasm-client: + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Install Rust toolchain + uses: ./.github/actions/install-rust-toolchain + + # The vendored crate is excluded from the workspace, so `--all` does not reach it. + - name: Test the vendored tonic-web-wasm-client + run: cargo test --locked -p tonic-web-wasm-client diff --git a/vendor/tonic-web-wasm-client/VENDORED.md b/vendor/tonic-web-wasm-client/VENDORED.md index eaab074..dd58fd2 100644 --- a/vendor/tonic-web-wasm-client/VENDORED.md +++ b/vendor/tonic-web-wasm-client/VENDORED.md @@ -1,10 +1,13 @@ -# Vendored `tonic-web-wasm-client` 0.8.0, with one fix +# Vendored `tonic-web-wasm-client` 0.8.0 This is `tonic-web-wasm-client` 0.8.0 from crates.io (MIT/Apache-2.0, see the licence files) with -the change in `trailers-only.patch`, wired in through `[patch.crates-io]` in the workspace -`Cargo.toml`. +the patches below, wired in through `[patch.crates-io]` in the workspace `Cargo.toml`. +The patches carry the `cfg(test)` hooks. Copy `src/response_body/` from this directory to run +the tests, including Daniel/Konclave's tests and captured fixtures from WebZjs #28. -## Why +## Fix 1: trailers-only responses (`trailers-only.patch`) + +### Why A gRPC server may answer a call that returns no messages with a *trailers-only* response: HTTP 200, `grpc-status` in the HTTP headers, and an empty body. lightwalletd v0.5.4 (the Zcash testnet @@ -14,15 +17,89 @@ every new wallet issues during sync. Mainnet (lightwalletd v0.5.3) sends a body Upstream 0.8.0 (and 0.9.2) reads the empty body as a truncated message and fails with `MalformedResponse`, so a wallet could not sync at all on testnet. -## The change +### The change `ResponseBody` records whether the response headers carried `grpc-status`. If the body ends before any frame header *and* the response was trailers-only, it is treated as an empty body. A body that ends early on any other response is still `MalformedResponse`. +## Fix 2: the trailer frame reaches tonic (`trailers.patch`) + +Crackdevs found, reproduced and first fixed the lost trailer in their browser OHTTP proof +(https://github.com/Crackdevs/zcash-browser-ohttp-proof). Daniel/Konclave prepared the minimal +WebZjs backport in [#28](https://github.com/red-dev-inc/WebZjs/pull/28) using the upstream fixes +credited below. + +### Why + +0.8.0 parses the gRPC-web trailer frame, stores it in a field nothing reads, and ends the body as +soon as it sees the trailer flag. tonic never receives the trailers, and tonic 0.14.3 (the locked +version) treats "HTTP 200, no trailers" as success. So a status sent in the body trailer is lost: +a server-streaming call that fails part-way looks complete, a unary call that returns a message and +then an error status looks successful, and an error with no message at all (for example +`OutOfRange` from `GetBlock` past the tip, which a public mainnet endpoint sends as a body trailer) +becomes an empty successful stream. Errors sent in the HTTP headers are not affected. + +tonic 0.14.6 and later report "HTTP 200, no trailers" as `Unknown: missing grpc-status trailer`, +so without this fix a `cargo update` of tonic would fail every call that has a body. + +### The change + +- After the last data frame the body yields the parsed trailers as one trailers frame. + This is the `src/response_body.rs` part of upstream commit 0f232d33 + (https://github.com/devashishdxt/tonic-web-wasm-client/pull/90, released in 0.9.1). +- The body counts as finished only once the trailer frame has been read in full. A trailer frame + split across chunks is read; a stream that ends inside it is `MalformedResponse` instead of a + clean end. The split case is upstream issue + https://github.com/devashishdxt/tonic-web-wasm-client/issues/97; the open upstream PR + https://github.com/devashishdxt/tonic-web-wasm-client/pull/112 makes the same predicate change + (unmerged). +- A stream that ends between frames with no trailer frame is unchanged: `MalformedResponse`, except + for the trailers-only case of fix 1. + +Behaviour that changes besides the fix: a trailer block that does not parse now fails with +`HeaderParsingError` whether it arrives in one chunk or split (before, the split case ended +silently); and since body trailers now reach tonic, an invalid `grpc-status-details-bin` there hits +the same tonic handling as one in the HTTP headers. + +## Fix 3: validate the body trailer and wait for EOF (`trailers-completion.patch`) + +This follows the decoder behavior from the [Crackdevs proof](https://github.com/Crackdevs/zcash-browser-ohttp-proof/blob/main/continuation-02/wallet.patch) +and the [follow-up proposed by Daniel/Konclave](https://github.com/Crackdevs/zcash-browser-ohttp-proof/issues/1#issuecomment-6898562403). + +- Emit complete data frames as they are read. After parsing the trailer, wait for HTTP body EOF + before yielding it once. Reject buffered or later bytes beyond that frame and surface any stream + error while awaiting EOF. A pending body read uses the ordinary stream waker and the existing + fetch cancellation and deadline behavior. WebZjs currently constructs this client without a request timeout. If a server leaves the response body open after the trailer, the call can remain pending until the body ends, a transport error occurs, or the request is cancelled. +- Require one `grpc-status` field in the body trailer. Reject duplicates after header-name + normalization, missing status and values other than decimal ASCII without leading zeros. Tonic + receives the original value, message and other metadata. Its bytewise status decoder preserves + codes 0–16 and maps unrecognized numeric codes of any length to `Unknown`. +- Keep the headers-only path for empty responses. Header status 0 ends an empty server stream + successfully. An empty unary response still has no message and returns Tonic's missing-message + error. A nonzero HTTP-header status continues to reach the caller. + +Native tests use the workspace lock and exercise Tonic unary and streaming decoding, including +split and truncated frames, delayed EOF, cancellation, trailing bytes, and malformed or unfamiliar +status values. Run `cargo test --locked -p tonic-web-wasm-client` from the workspace root. CI uses +the `vendored-tonic-web-wasm-client` job in `rust-checks.yml`. + +### Existing limitations + +- Tonic 0.14.3 gives HTTP-header status priority and can skip the body entirely. A conflicting + header and body status therefore still follows the header path. Header-only status validation + remains Tonic's responsibility. +- Metadata other than `grpc-status` retains the existing last-value behavior for duplicates. + [Upstream #117](https://github.com/devashishdxt/tonic-web-wasm-client/pull/117) addresses that + separately. Error metadata still uses Tonic's existing decoding, including its panic on + invalid base64 in `grpc-status-details-bin`. +- The checks target binary gRPC-web. The existing text/base64 path has a buffer bug and + compressed body trailers are unsupported. Frames are still buffered individually up to + their announced length. + ## Not bumped to 0.9.2 -0.9.2 has the same behaviour (checked), and requires `js-sys ^0.3.85`, which conflicts with the +0.9.2 has the same trailers-only behaviour (checked), and its `wasm-streams ^0.7` dependency requires `js-sys ^0.3.85`, which conflicts with the workspace's deliberate `wasm-bindgen =0.2.100` / `js-sys =0.3.77` pins (newer versions break the MetaMask Snap sandbox). @@ -32,8 +109,17 @@ Reported upstream as devashishdxt/tonic-web-wasm-client issue #99 (2026-09-25) w (same idea: end the body when the stream ends between frames with nothing buffered; unmerged, no reviews). Release 0.9.2 (2026-09-14) does not include it. Do not send our patch separately. -## To remove +## Reapplying the vendor changes + +From the published `tonic-web-wasm-client` 0.8.0 source root, apply the WebZjs patches in order. +Set `webzjs_vendor` to the absolute path of this directory. + +```sh +patch -p1 < "$webzjs_vendor/trailers-only.patch" +patch -p1 < "$webzjs_vendor/trailers.patch" +patch -p1 < "$webzjs_vendor/trailers-completion.patch" +cp -R "$webzjs_vendor/src/response_body" src/ +``` -Drop this directory, the `[patch.crates-io]` entry and the `exclude` entry once the fix is -released upstream. `trailers-only.patch` is a ready-made upstream change (apply with `patch -p1` -from a `tonic-web-wasm-client` checkout). +Drop this directory, the `[patch.crates-io]` entry, the `exclude` entry and the CI job once these +fixes are in an upstream release the pins allow. diff --git a/vendor/tonic-web-wasm-client/src/body_stream.rs b/vendor/tonic-web-wasm-client/src/body_stream.rs index 81af90c..dcd8c8a 100644 --- a/vendor/tonic-web-wasm-client/src/body_stream.rs +++ b/vendor/tonic-web-wasm-client/src/body_stream.rs @@ -35,6 +35,20 @@ impl BodyStream { } } + /// A body made of in-memory chunks, for unit tests that run without a browser. + #[cfg(test)] + pub(crate) fn from_chunks(chunks: Vec) -> Self { + Self::from_stream(futures_util::stream::iter(chunks.into_iter().map(Ok))) + } + + #[cfg(test)] + pub(crate) fn from_stream(stream: impl Stream> + 'static) -> Self { + Self { + body_stream: Box::pin(stream), + _abort: None, + } + } + pub fn empty() -> Self { let body_stream = empty(); diff --git a/vendor/tonic-web-wasm-client/src/response_body.rs b/vendor/tonic-web-wasm-client/src/response_body.rs index 934c05d..9deaf0f 100644 --- a/vendor/tonic-web-wasm-client/src/response_body.rs +++ b/vendor/tonic-web-wasm-client/src/response_body.rs @@ -93,17 +93,10 @@ pub enum ReadState { Data(u32), TrailerLength, Trailer(u32), + AwaitEof, Done, } -impl ReadState { - fn finished_data(&self) -> bool { - matches!(self, ReadState::TrailerLength) - || matches!(self, ReadState::Trailer(_)) - || matches!(self, ReadState::Done) - } -} - /// Type to handle HTTP response #[pin_project] pub struct ResponseBody { @@ -130,8 +123,20 @@ impl ResponseBody { let body_stream = wasm_streams::ReadableStream::from_raw(body_stream.unchecked_into()).into_stream(); + Self::from_body_stream( + BodyStream::new(body_stream, abort), + content_type, + trailers_only, + ) + } + + fn from_body_stream( + body_stream: BodyStream, + content_type: &str, + trailers_only: bool, + ) -> Result { Ok(Self { - body_stream: BodyStream::new(body_stream, abort), + body_stream, buf: EncodedBytes::new(content_type)?, incomplete_data: BytesMut::new(), data: None, @@ -208,15 +213,9 @@ impl ResponseBody { } else { this.incomplete_data.unsplit(this.buf.take(data_length)); - let new_data = this.incomplete_data.split(); - - if let Some(data) = this.data { - data.unsplit(new_data); - } else { - *this.data = Some(new_data); - } - + *this.data = Some(this.incomplete_data.split()); *this.state = ReadState::CompressionFlag; + return Ok(()); } } ReadState::TrailerLength => { @@ -244,8 +243,14 @@ impl ResponseBody { match httparse::parse_headers(&trailer_bytes, &mut trailers_buf) .map_err(|_| Error::HeaderParsingError)? { - Status::Complete((_, headers)) => Ok(headers), - Status::Partial => Err(Error::HeaderParsingError), + // Accept an existing terminator or the appended newline, but + // never ignore another header after a blank line. + Status::Complete((end, headers)) + if end >= trailer_bytes.len() - 1 => + { + Ok(headers) + } + _ => Err(Error::HeaderParsingError), }?; let mut trailers = HeaderMap::with_capacity(parsed_trailers.len()); @@ -253,14 +258,33 @@ impl ResponseBody { for parsed_trailer in parsed_trailers { let header_name = HeaderName::from_bytes(parsed_trailer.name.as_bytes())?; + if header_name == "grpc-status" { + let status = parsed_trailer.value; + if trailers.contains_key(&header_name) + || status.is_empty() + || !status.iter().all(u8::is_ascii_digit) + || (status.len() > 1 && status[0] == b'0') + { + return Err(Error::MalformedResponse); + } + // tonic maps unfamiliar decimal codes to UNKNOWN without + // parsing an integer. Leave the value and metadata intact. + } let header_value = HeaderValue::from_bytes(parsed_trailer.value)?; trailers.insert(header_name, header_value); } - + if !trailers.contains_key("grpc-status") { + return Err(Error::MalformedResponse); + } *this.trailer = Some(trailers); - - *this.state = ReadState::Done; + *this.state = ReadState::AwaitEof; + } + } + ReadState::AwaitEof => { + if !this.buf.is_empty() || !this.buf.raw_buf.is_empty() { + return Err(Error::MalformedResponse); } + return Ok(()); } ReadState::Done => return Ok(()), } @@ -277,42 +301,36 @@ impl Body for ResponseBody { mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll, Self::Error>>> { - // Check if there's already some data in buffer and return that - if self.data.is_some() { - let data = self.data.take().unwrap(); - - return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); - } - - // If reading data is finished return `None` - if self.state.finished_data() { + if self.state == ReadState::Done { return Poll::Ready(None); } loop { - // Read bytes from stream - if let Err(e) = ready!(self.as_mut().read_stream(cx)) { - return Poll::Ready(Some(Err(e))); - } - - // Step the state machine + // Drain buffered frames before waiting for the next chunk or EOF. if let Err(e) = self.as_mut().step() { + self.state = ReadState::Done; + self.trailer = None; return Poll::Ready(Some(Err(e))); } - if self.data.is_some() { - // If data is available in buffer, return that - let data = self.data.take().unwrap(); + if let Some(data) = self.data.take() { return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); - } else if self.state.finished_data() { - // If we finished reading data continue return `None` - return Poll::Ready(None); - } else if self.finished_stream { + } + if self.finished_stream { + let state = std::mem::replace(&mut self.state, ReadState::Done); + if state == ReadState::AwaitEof { + return Poll::Ready( + self.trailer + .take() + .map(|t| Ok(http_body::Frame::trailers(t))), + ); + } // A trailers-only response carries its status in the HTTP headers and has an empty // body: the stream legitimately ends before any frame header. if self.trailers_only - && self.state == ReadState::CompressionFlag + && state == ReadState::CompressionFlag && self.buf.is_empty() + && self.buf.raw_buf.is_empty() && self.incomplete_data.is_empty() { return Poll::Ready(None); @@ -320,6 +338,11 @@ impl Body for ResponseBody { // If stream is finished but data is not finished return error return Poll::Ready(Some(Err(Error::MalformedResponse))); } + if let Err(e) = ready!(self.as_mut().read_stream(cx)) { + self.state = ReadState::Done; + self.trailer = None; + return Poll::Ready(Some(Err(e))); + } } } } @@ -342,3 +365,6 @@ impl Default for ResponseBody { } } } + +#[cfg(test)] +mod tests; diff --git a/vendor/tonic-web-wasm-client/src/response_body/fixtures/body-trailer-error.bin b/vendor/tonic-web-wasm-client/src/response_body/fixtures/body-trailer-error.bin new file mode 100644 index 0000000..8d29a14 Binary files /dev/null and b/vendor/tonic-web-wasm-client/src/response_body/fixtures/body-trailer-error.bin differ diff --git a/vendor/tonic-web-wasm-client/src/response_body/fixtures/data-then-trailer-ok.bin b/vendor/tonic-web-wasm-client/src/response_body/fixtures/data-then-trailer-ok.bin new file mode 100644 index 0000000..b7af0de Binary files /dev/null and b/vendor/tonic-web-wasm-client/src/response_body/fixtures/data-then-trailer-ok.bin differ diff --git a/vendor/tonic-web-wasm-client/src/response_body/tests.rs b/vendor/tonic-web-wasm-client/src/response_body/tests.rs new file mode 100644 index 0000000..4d4012d --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/response_body/tests.rs @@ -0,0 +1,673 @@ +//! Native unit tests for the gRPC-web response body: the trailer frame must reach tonic. +//! +//! The body is fed from in-memory chunks, so these run with `cargo test` on the host, without a +//! browser. Frames are built by hand: one flag byte (`0x00` data, `0x80` trailer), a 4-byte +//! big-endian length, then the payload. + +use std::{ + future::Future, + pin::{pin, Pin}, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, Mutex, + }, + task::{Context, Poll, Wake, Waker}, +}; + +use bytes::{Buf, BufMut, Bytes}; +use futures_util::{stream, Stream, StreamExt}; +use http::{uri::PathAndQuery, HeaderMap, StatusCode}; +use http_body::Body; +use tonic::{ + codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder, Streaming}, + Code, Status, +}; + +use super::ResponseBody; +use crate::{body_stream::BodyStream, Error}; + +const CONTENT_TYPE: &str = "application/grpc-web+proto"; +const STATUS_13: &[u8] = b"grpc-status: 13\r\ngrpc-message: boom\r\n"; +const STATUS_5: &[u8] = b"grpc-status: 5\r\ngrpc-message: not found\r\n"; +const STATUS_0: &[u8] = b"grpc-status: 0\r\n"; + +/// A real body captured from a public gRPC-web endpoint (2026-11-15): HTTP 200, no `grpc-status` +/// in the headers, and one trailer frame carrying `grpc-status: 11` for a block past the tip. +const CAPTURED_BODY_TRAILER_ERROR: &[u8] = include_bytes!("fixtures/body-trailer-error.bin"); +/// A real successful unary body (2026-11-15): one data frame, then a trailer frame with status 0. +const CAPTURED_DATA_THEN_TRAILER_OK: &[u8] = include_bytes!("fixtures/data-then-trailer-ok.bin"); + +fn frame(flag: u8, payload: &[u8]) -> Vec { + let mut out = Vec::with_capacity(5 + payload.len()); + out.push(flag); + out.put_u32(payload.len() as u32); + out.extend_from_slice(payload); + out +} + +fn data_frame(payload: &[u8]) -> Vec { + frame(0x00, payload) +} + +fn trailer_frame(payload: &[u8]) -> Vec { + frame(0x80, payload) +} + +fn body(chunks: Vec>, trailers_only: bool) -> ResponseBody { + let chunks = chunks.into_iter().map(Bytes::from).collect(); + ResponseBody::from_body_stream(BodyStream::from_chunks(chunks), CONTENT_TYPE, trailers_only) + .expect("binary content type is accepted") +} + +/// Drives a future that never waits on I/O (every body here is in memory). +fn run(future: F) -> F::Output { + let mut future = pin!(future); + let mut cx = Context::from_waker(Waker::noop()); + match future.as_mut().poll(&mut cx) { + Poll::Ready(output) => output, + Poll::Pending => panic!("an in-memory body never returns Pending"), + } +} + +#[derive(Debug, PartialEq)] +enum Item { + Data(Bytes), + Trailers(HeaderMap), + Malformed, + OtherError(String), +} + +/// Every frame the body yields, up to the end or the first error. +fn frames(mut body: ResponseBody) -> Vec { + let mut items = Vec::new(); + let mut cx = Context::from_waker(Waker::noop()); + loop { + match std::pin::Pin::new(&mut body).poll_frame(&mut cx) { + Poll::Pending => panic!("an in-memory body never returns Pending"), + Poll::Ready(None) => return items, + Poll::Ready(Some(Err(Error::MalformedResponse))) => { + items.push(Item::Malformed); + return items; + } + Poll::Ready(Some(Err(e))) => { + items.push(Item::OtherError(e.to_string())); + return items; + } + Poll::Ready(Some(Ok(frame))) => match frame.into_data() { + Ok(data) => items.push(Item::Data(data)), + Err(frame) => items.push(Item::Trailers( + frame.into_trailers().expect("a frame is data or trailers"), + )), + }, + } + } +} + +fn status_of(item: &Item) -> Option<&str> { + match item { + Item::Trailers(map) => map.get("grpc-status").and_then(|v| v.to_str().ok()), + _ => None, + } +} + +/// Every way to cut `bytes` into two chunks, plus one byte per chunk. +fn splits(bytes: &[u8]) -> Vec>> { + let mut all: Vec>> = (1..bytes.len()) + .map(|at| vec![bytes[..at].to_vec(), bytes[at..].to_vec()]) + .collect(); + all.push(bytes.iter().map(|b| vec![*b]).collect()); + all +} + +/// A codec that passes message bytes through unchanged. +#[derive(Default)] +struct RawCodec; + +impl Codec for RawCodec { + type Encode = Bytes; + type Decode = Bytes; + type Encoder = RawCodec; + type Decoder = RawCodec; + + fn encoder(&mut self) -> Self::Encoder { + RawCodec + } + + fn decoder(&mut self) -> Self::Decoder { + RawCodec + } +} + +impl Encoder for RawCodec { + type Item = Bytes; + type Error = Status; + + fn encode(&mut self, item: Bytes, dst: &mut EncodeBuf<'_>) -> Result<(), Status> { + dst.put(item); + Ok(()) + } +} + +impl Decoder for RawCodec { + type Item = Bytes; + type Error = Status; + + fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result, Status> { + Ok(Some(src.copy_to_bytes(src.remaining()))) + } +} + +/// What tonic's streaming decoder reports for a body: each message, then the final outcome. +fn through_tonic_stream(body: ResponseBody) -> (Vec, Result<(), Status>) { + let mut stream = Streaming::new_response(RawCodec, body, StatusCode::OK, None, None); + let mut messages = Vec::new(); + loop { + match run(stream.message()) { + Ok(Some(message)) => messages.push(message), + Ok(None) => return (messages, Ok(())), + Err(status) => return (messages, Err(status)), + } + } +} + +/// A gRPC service that answers every call with a fixed gRPC-web body and HTTP 200. +struct FixedResponse(Option, HeaderMap); + +impl tower_service::Service> for FixedResponse { + type Response = http::Response; + type Error = Error; + type Future = std::future::Ready>; + + fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, _: http::Request) -> Self::Future { + let body = self.0.take().expect("one call per test"); + let mut response = http::Response::builder() + .status(StatusCode::OK) + .header(http::header::CONTENT_TYPE, CONTENT_TYPE) + .body(body) + .expect("static response parts are valid"); + response.headers_mut().extend(std::mem::take(&mut self.1)); + std::future::ready(Ok(response)) + } +} + +fn through_tonic_unary(body: ResponseBody) -> Result { + let mut grpc = tonic::client::Grpc::new(FixedResponse(Some(body), HeaderMap::new())); + let path = http::uri::PathAndQuery::from_static("/test.Service/Unary"); + run(grpc.unary(tonic::Request::new(Bytes::new()), path, RawCodec)).map(|r| r.into_inner()) +} + +// T1 +#[test] +fn trailer_after_data_is_yielded_as_a_trailers_frame() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + let items = frames(body(vec![bytes], false)); + + assert_eq!(items.len(), 2, "{items:?}"); + assert_eq!(items[0], Item::Data(Bytes::from(data_frame(b"hello")))); + assert_eq!(status_of(&items[1]), Some("13"), "{items:?}"); +} + +// T2 +#[test] +fn trailer_is_yielded_whatever_the_chunk_boundaries() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + for chunks in splits(&bytes) { + let shape: Vec = chunks.iter().map(Vec::len).collect(); + let items = frames(body(chunks, false)); + let data: Vec = items + .iter() + .filter_map(|i| match i { + Item::Data(d) => Some(d.to_vec()), + _ => None, + }) + .flatten() + .collect(); + assert_eq!(data, data_frame(b"hello"), "chunks {shape:?}: {items:?}"); + assert_eq!( + items.last().and_then(status_of), + Some("13"), + "chunks {shape:?}: {items:?}" + ); + } +} + +// T3 +#[test] +fn trailer_frame_alone_is_yielded() { + let items = frames(body(vec![trailer_frame(STATUS_5)], false)); + + assert_eq!(items.len(), 1, "{items:?}"); + assert_eq!(status_of(&items[0]), Some("5")); +} + +// T4 +#[test] +fn stream_that_ends_inside_the_trailer_frame_is_malformed() { + let mut bytes = data_frame(b"hello"); + let data_len = bytes.len(); + bytes.extend(trailer_frame(STATUS_13)); + + // Cut after the trailer flag, inside and after its length, and inside its payload. + for cut in [ + data_len + 1, + data_len + 3, + data_len + 5, + data_len + 8, + bytes.len() - 1, + ] { + let items = frames(body(vec![bytes[..cut].to_vec()], false)); + assert_eq!( + items.last(), + Some(&Item::Malformed), + "cut at {cut}: {items:?}" + ); + } +} + +// T5 +#[test] +fn tonic_stream_reports_the_status_sent_in_the_body_trailer() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + for chunks in splits(&bytes) { + let (messages, outcome) = through_tonic_stream(body(chunks, false)); + assert_eq!(messages, vec![Bytes::from_static(b"hello")]); + let status = outcome.expect_err("status 13 must reach the caller"); + assert_eq!(status.code(), Code::Internal); + assert_eq!(status.message(), "boom"); + } +} + +// T5, unary +#[test] +fn tonic_unary_call_reports_the_status_sent_after_its_message() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + let status = through_tonic_unary(body(vec![bytes], false)) + .expect_err("a message followed by status 13 is a failed call"); + assert_eq!(status.code(), Code::Internal); + assert_eq!(status.message(), "boom"); +} + +// T5, a captured body +#[test] +fn tonic_reports_the_status_of_a_captured_body_trailer() { + for chunks in splits(CAPTURED_BODY_TRAILER_ERROR) { + let (messages, outcome) = through_tonic_stream(body(chunks, false)); + assert!(messages.is_empty()); + let status = outcome.expect_err("status 11 must reach the caller"); + assert_eq!(status.code(), Code::OutOfRange); + assert!(status.message().contains("newer than the latest block")); + } +} + +// T6 +#[test] +fn ok_trailer_is_yielded_and_ends_the_call_cleanly() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_0)); + + let items = frames(body(vec![bytes.clone()], false)); + assert_eq!(items.len(), 2, "{items:?}"); + assert_eq!(status_of(&items[1]), Some("0")); + + let (messages, outcome) = through_tonic_stream(body(vec![bytes], false)); + assert_eq!(messages, vec![Bytes::from_static(b"hello")]); + assert!(outcome.is_ok(), "{outcome:?}"); +} + +// T6, a captured body +#[test] +fn captured_successful_unary_body_still_succeeds() { + for chunks in splits(CAPTURED_DATA_THEN_TRAILER_OK) { + let message = through_tonic_unary(body(chunks, false)).expect("status 0 is success"); + assert!(!message.is_empty()); + } +} + +// G1 +#[test] +fn trailers_only_response_with_an_empty_body_ends_cleanly() { + assert_eq!(frames(body(vec![], true)), vec![]); +} + +// G1, the exception is narrow +#[test] +fn trailers_only_response_with_a_truncated_body_is_still_malformed() { + let bytes = data_frame(b"hello"); + for cut in [1, 3, bytes.len() - 1] { + let items = frames(body(vec![bytes[..cut].to_vec()], true)); + assert_eq!(items, vec![Item::Malformed], "cut at {cut}"); + } +} + +// G2 +#[test] +fn data_without_any_trailer_is_malformed() { + let items = frames(body(vec![data_frame(b"hello")], false)); + assert_eq!(items.last(), Some(&Item::Malformed), "{items:?}"); +} + +// G3 +#[test] +fn stream_that_ends_inside_a_data_frame_is_malformed() { + let bytes = data_frame(b"hello"); + let items = frames(body(vec![bytes[..bytes.len() - 2].to_vec()], false)); + assert_eq!(items, vec![Item::Malformed]); +} + +#[test] +fn nothing_is_yielded_after_the_trailers() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_0)); + let mut body = body(vec![bytes], false); + let mut cx = Context::from_waker(Waker::noop()); + + let mut seen = 0; + while let Poll::Ready(Some(_)) = std::pin::Pin::new(&mut body).poll_frame(&mut cx) { + seen += 1; + assert!(seen <= 2, "at most one data and one trailers frame"); + } + for _ in 0..3 { + assert!(matches!( + std::pin::Pin::new(&mut body).poll_frame(&mut cx), + Poll::Ready(None) + )); + } +} + +fn data_then_trailer(trailer: &[u8]) -> Vec { + [data_frame(b"hello"), trailer_frame(trailer)].concat() +} + +fn assert_protocol_error(status: Status) { + assert_eq!(status.code(), Code::Unknown); + assert!( + status.message().contains("malformed response") + || status.message().contains("failed to parse headers"), + "{status:?}" + ); +} + +#[test] +fn invalid_body_status_fails_both_tonic_paths() { + for trailers in [ + &b"x-meta: present\r\n"[..], + b"grpc-status: 13\r\ngrpc-status: 0\r\n", + b"grpc-status: 0\r\nGrpc-Status: 0\r\n", + b"grpc-status: 0\r\n\r\nGrpc-Status: 13\r\n", + b"grpc-status:\r\n", + b"grpc-status: +0\r\n", + b"grpc-status: -1\r\n", + b"grpc-status: 0, 0\r\n", + b"grpc-status: 13junk\r\n", + b"grpc-status: 00\r\n", + ] { + let bytes = data_then_trailer(trailers); + let (messages, result) = through_tonic_stream(body(vec![bytes.clone()], false)); + assert_eq!(messages, [Bytes::from_static(b"hello")]); + assert_protocol_error(result.expect_err("invalid body status ended the stream cleanly")); + assert_protocol_error( + through_tonic_unary(body(vec![bytes], false)) + .expect_err("invalid body status produced a unary response"), + ); + } +} + +#[test] +fn tonic_preserves_all_recognized_body_status_codes() { + for code in 0..=16 { + let trailers = format!("grpc-status: {code}\r\n"); + let bytes = data_then_trailer(trailers.as_bytes()); + let result = through_tonic_unary(body(vec![bytes], false)); + if code == 0 { + assert_eq!(result.unwrap(), Bytes::from_static(b"hello")); + } else { + assert_eq!(result.unwrap_err().code(), Code::from_i32(code)); + } + } +} + +#[test] +fn unfamiliar_body_status_maps_to_unknown_with_server_metadata() { + let oversized = "9".repeat(128); + for code in ["17", "4294967296", &oversized] { + let trailers = format!( + "grpc-status: {code}\r\ngrpc-message: newer%20code\r\n\ + grpc-status-details-bin: AQID\r\nx-proof: retained\r\n" + ); + let bytes = data_then_trailer(trailers.as_bytes()); + let (messages, result) = through_tonic_stream(body(vec![bytes.clone()], false)); + assert_eq!(messages, [Bytes::from_static(b"hello")]); + for status in [ + result.unwrap_err(), + through_tonic_unary(body(vec![bytes], false)).unwrap_err(), + ] { + assert_eq!(status.code(), Code::Unknown); + assert_eq!(status.message(), "newer code"); + assert_eq!(status.details(), [1, 2, 3]); + assert_eq!(status.metadata().get("x-proof").unwrap(), "retained"); + } + } +} + +#[test] +fn bytes_after_body_trailer_fail_even_after_an_ok_status() { + let initial = data_then_trailer(STATUS_0); + for tail in [vec![0xff], data_frame(b"extra"), trailer_frame(STATUS_5)] { + for chunks in [ + vec![[initial.clone(), tail.clone()].concat()], + vec![initial.clone(), tail], + ] { + let (messages, result) = through_tonic_stream(body(chunks.clone(), false)); + assert_eq!(messages, [Bytes::from_static(b"hello")]); + assert_protocol_error(result.expect_err("trailing bytes ended the stream cleanly")); + assert_protocol_error( + through_tonic_unary(body(chunks, false)) + .expect_err("trailing bytes produced a unary response"), + ); + } + } +} + +#[test] +fn truncated_data_or_trailer_does_not_erase_preceding_message() { + for next in [data_frame(b"more"), trailer_frame(STATUS_0)] { + for cut in [1, 4, 5, next.len() - 1] { + let bytes = [data_frame(b"hello"), next[..cut].to_vec()].concat(); + let (messages, result) = through_tonic_stream(body(vec![bytes], false)); + assert_eq!(messages, [Bytes::from_static(b"hello")]); + assert_protocol_error(result.expect_err("truncation ended the stream cleanly")); + } + } +} + +#[derive(Default)] +struct TailState { + completion: Option>, + waker: Option, + polls: usize, + dropped: bool, +} + +struct ControlledTail(Arc>); + +impl Stream for ControlledTail { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut state = self.0.lock().unwrap(); + state.polls += 1; + match state.completion.take() { + Some(Ok(())) => Poll::Ready(None), + Some(Err(error)) => Poll::Ready(Some(Err(error))), + None => { + state.waker = Some(cx.waker().clone()); + Poll::Pending + } + } + } +} + +impl Drop for ControlledTail { + fn drop(&mut self) { + self.0.lock().unwrap().dropped = true; + } +} + +fn body_with_controlled_tail() -> (ResponseBody, Arc>) { + let state = Arc::new(Mutex::new(TailState::default())); + let first = Ok(Bytes::from(data_then_trailer(STATUS_0))); + let source = stream::iter([first]).chain(ControlledTail(state.clone())); + let body = ResponseBody::from_body_stream(BodyStream::from_stream(source), CONTENT_TYPE, false) + .unwrap(); + (body, state) +} + +fn complete_tail(state: &Mutex, result: Result<(), Error>) { + let waker = { + let mut state = state.lock().unwrap(); + state.completion = Some(result); + state.waker.take().expect("the body is waiting on its tail") + }; + waker.wake(); +} + +#[derive(Default)] +struct WakeCount(AtomicUsize); + +impl Wake for WakeCount { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::Relaxed); + } +} + +#[test] +fn streaming_message_arrives_before_eof_but_final_success_waits() { + let (body, tail) = body_with_controlled_tail(); + let mut stream = Streaming::new_response(RawCodec, body, StatusCode::OK, None, None); + assert_eq!( + run(stream.message()).unwrap(), + Some(Bytes::from_static(b"hello")) + ); + assert_eq!(tail.lock().unwrap().polls, 0); + + let count = Arc::new(WakeCount::default()); + let waker = Waker::from(count.clone()); + let mut cx = Context::from_waker(&waker); + let mut completion = pin!(stream.message()); + assert!(completion.as_mut().poll(&mut cx).is_pending()); + assert_eq!(tail.lock().unwrap().polls, 1); + assert_eq!(count.0.load(Ordering::Relaxed), 0); + + complete_tail(&tail, Ok(())); + assert_eq!(count.0.load(Ordering::Relaxed), 1); + assert!(matches!( + completion.as_mut().poll(&mut cx), + Poll::Ready(Ok(None)) + )); +} + +#[test] +fn unary_result_waits_for_eof() { + let (body, tail) = body_with_controlled_tail(); + let mut grpc = tonic::client::Grpc::new(FixedResponse(Some(body), HeaderMap::new())); + let path = PathAndQuery::from_static("/test.Service/Unary"); + let mut result = pin!(grpc.unary(tonic::Request::new(Bytes::new()), path, RawCodec)); + let mut cx = Context::from_waker(Waker::noop()); + assert!(result.as_mut().poll(&mut cx).is_pending()); + complete_tail(&tail, Ok(())); + let Poll::Ready(Ok(response)) = result.as_mut().poll(&mut cx) else { + panic!("clean EOF should finish the unary call"); + }; + assert_eq!(response.into_inner(), Bytes::from_static(b"hello")); +} + +#[test] +fn transport_error_after_complete_trailer_reaches_tonic() { + let initial = Bytes::from(data_then_trailer(STATUS_0)); + let failure = || { + Err(Error::JsError( + "connection closed while reading body".into(), + )) + }; + let make_body = || { + ResponseBody::from_body_stream( + BodyStream::from_stream(stream::iter([Ok(initial.clone()), failure()])), + CONTENT_TYPE, + false, + ) + .unwrap() + }; + let (messages, result) = through_tonic_stream(make_body()); + assert_eq!(messages, [Bytes::from_static(b"hello")]); + for status in [ + result.unwrap_err(), + through_tonic_unary(make_body()).unwrap_err(), + ] { + assert!( + status + .message() + .contains("connection closed while reading body"), + "{status:?}" + ); + } +} + +#[test] +fn cancelling_while_waiting_for_eof_drops_the_source() { + let (body, tail) = body_with_controlled_tail(); + let mut stream = Streaming::new_response(RawCodec, body, StatusCode::OK, None, None); + assert!(run(stream.message()).unwrap().is_some()); + let mut cx = Context::from_waker(Waker::noop()); + { + let mut completion = pin!(stream.message()); + assert!(completion.as_mut().poll(&mut cx).is_pending()); + assert!(!tail.lock().unwrap().dropped); + } + drop(stream); + let state = tail.lock().unwrap(); + assert!(state.dropped); + assert_eq!(state.polls, 1); +} + +#[test] +fn tonic_handles_headers_only_without_an_extra_body_trailer() { + let request = || tonic::Request::new(Bytes::new()); + let path = PathAndQuery::from_static("/test.Service/Call"); + for (value, code) in [("0", Code::Ok), ("5", Code::NotFound)] { + let client = || { + let mut headers = HeaderMap::new(); + headers.insert("grpc-status", http::HeaderValue::from_static(value)); + headers.insert( + "grpc-message", + http::HeaderValue::from_static("header%20status"), + ); + tonic::client::Grpc::new(FixedResponse(Some(body(vec![], true)), headers)) + }; + let streaming = run(client().server_streaming(request(), path.clone(), RawCodec)); + let unary = run(client().unary(request(), path.clone(), RawCodec)).unwrap_err(); + if code == Code::Ok { + let mut stream = streaming.unwrap().into_inner(); + assert_eq!(run(stream.message()).unwrap(), None); + assert_eq!(unary.code(), Code::Internal); + assert_eq!(unary.message(), "Missing response message."); + } else { + let status = streaming.unwrap_err(); + assert_eq!(status.code(), code); + assert_eq!(status.message(), "header status"); + assert_eq!(unary.code(), code); + assert_eq!(unary.message(), "header status"); + } + } +} diff --git a/vendor/tonic-web-wasm-client/trailers-completion.patch b/vendor/tonic-web-wasm-client/trailers-completion.patch new file mode 100644 index 0000000..8f07e63 --- /dev/null +++ b/vendor/tonic-web-wasm-client/trailers-completion.patch @@ -0,0 +1,195 @@ +diff --git a/src/body_stream.rs b/src/body_stream.rs +index 55a4811..dcd8c8a 100644 +--- a/src/body_stream.rs ++++ b/src/body_stream.rs +@@ -38,8 +38,13 @@ impl BodyStream { + /// A body made of in-memory chunks, for unit tests that run without a browser. + #[cfg(test)] + pub(crate) fn from_chunks(chunks: Vec) -> Self { ++ Self::from_stream(futures_util::stream::iter(chunks.into_iter().map(Ok))) ++ } ++ ++ #[cfg(test)] ++ pub(crate) fn from_stream(stream: impl Stream> + 'static) -> Self { + Self { +- body_stream: Box::pin(futures_util::stream::iter(chunks.into_iter().map(Ok))), ++ body_stream: Box::pin(stream), + _abort: None, + } + } +diff --git a/src/response_body.rs b/src/response_body.rs +index 282827c..9deaf0f 100644 +--- a/src/response_body.rs ++++ b/src/response_body.rs +@@ -93,17 +93,10 @@ pub enum ReadState { + Data(u32), + TrailerLength, + Trailer(u32), ++ AwaitEof, + Done, + } + +-impl ReadState { +- /// The body is complete only once the trailer frame has been read in full. Seeing the trailer +- /// flag is not enough: the rest of the frame may still be on its way, or never arrive. +- fn finished_data(&self) -> bool { +- matches!(self, ReadState::Done) +- } +-} +- + /// Type to handle HTTP response + #[pin_project] + pub struct ResponseBody { +@@ -220,15 +213,9 @@ impl ResponseBody { + } else { + this.incomplete_data.unsplit(this.buf.take(data_length)); + +- let new_data = this.incomplete_data.split(); +- +- if let Some(data) = this.data { +- data.unsplit(new_data); +- } else { +- *this.data = Some(new_data); +- } +- ++ *this.data = Some(this.incomplete_data.split()); + *this.state = ReadState::CompressionFlag; ++ return Ok(()); + } + } + ReadState::TrailerLength => { +@@ -256,8 +243,14 @@ impl ResponseBody { + match httparse::parse_headers(&trailer_bytes, &mut trailers_buf) + .map_err(|_| Error::HeaderParsingError)? + { +- Status::Complete((_, headers)) => Ok(headers), +- Status::Partial => Err(Error::HeaderParsingError), ++ // Accept an existing terminator or the appended newline, but ++ // never ignore another header after a blank line. ++ Status::Complete((end, headers)) ++ if end >= trailer_bytes.len() - 1 => ++ { ++ Ok(headers) ++ } ++ _ => Err(Error::HeaderParsingError), + }?; + + let mut trailers = HeaderMap::with_capacity(parsed_trailers.len()); +@@ -265,14 +258,33 @@ impl ResponseBody { + for parsed_trailer in parsed_trailers { + let header_name = + HeaderName::from_bytes(parsed_trailer.name.as_bytes())?; ++ if header_name == "grpc-status" { ++ let status = parsed_trailer.value; ++ if trailers.contains_key(&header_name) ++ || status.is_empty() ++ || !status.iter().all(u8::is_ascii_digit) ++ || (status.len() > 1 && status[0] == b'0') ++ { ++ return Err(Error::MalformedResponse); ++ } ++ // tonic maps unfamiliar decimal codes to UNKNOWN without ++ // parsing an integer. Leave the value and metadata intact. ++ } + let header_value = HeaderValue::from_bytes(parsed_trailer.value)?; + trailers.insert(header_name, header_value); + } +- ++ if !trailers.contains_key("grpc-status") { ++ return Err(Error::MalformedResponse); ++ } + *this.trailer = Some(trailers); +- +- *this.state = ReadState::Done; ++ *this.state = ReadState::AwaitEof; ++ } ++ } ++ ReadState::AwaitEof => { ++ if !this.buf.is_empty() || !this.buf.raw_buf.is_empty() { ++ return Err(Error::MalformedResponse); + } ++ return Ok(()); + } + ReadState::Done => return Ok(()), + } +@@ -289,50 +301,36 @@ impl Body for ResponseBody { + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { +- // Check if there's already some data in buffer and return that +- if self.data.is_some() { +- let data = self.data.take().unwrap(); +- +- return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); +- } +- +- // Once the body is complete, hand the trailers to the caller (once), then end +- if self.state.finished_data() { +- return Poll::Ready( +- self.trailer +- .take() +- .map(|t| Ok(http_body::Frame::trailers(t))), +- ); ++ if self.state == ReadState::Done { ++ return Poll::Ready(None); + } + + loop { +- // Read bytes from stream +- if let Err(e) = ready!(self.as_mut().read_stream(cx)) { +- return Poll::Ready(Some(Err(e))); +- } +- +- // Step the state machine ++ // Drain buffered frames before waiting for the next chunk or EOF. + if let Err(e) = self.as_mut().step() { ++ self.state = ReadState::Done; ++ self.trailer = None; + return Poll::Ready(Some(Err(e))); + } + +- if self.data.is_some() { +- // If data is available in buffer, return that +- let data = self.data.take().unwrap(); ++ if let Some(data) = self.data.take() { + return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); +- } else if self.state.finished_data() { +- // The body is complete: hand the trailers to the caller (once), then end +- return Poll::Ready( +- self.trailer +- .take() +- .map(|t| Ok(http_body::Frame::trailers(t))), +- ); +- } else if self.finished_stream { ++ } ++ if self.finished_stream { ++ let state = std::mem::replace(&mut self.state, ReadState::Done); ++ if state == ReadState::AwaitEof { ++ return Poll::Ready( ++ self.trailer ++ .take() ++ .map(|t| Ok(http_body::Frame::trailers(t))), ++ ); ++ } + // A trailers-only response carries its status in the HTTP headers and has an empty + // body: the stream legitimately ends before any frame header. + if self.trailers_only +- && self.state == ReadState::CompressionFlag ++ && state == ReadState::CompressionFlag + && self.buf.is_empty() ++ && self.buf.raw_buf.is_empty() + && self.incomplete_data.is_empty() + { + return Poll::Ready(None); +@@ -340,6 +338,11 @@ impl Body for ResponseBody { + // If stream is finished but data is not finished return error + return Poll::Ready(Some(Err(Error::MalformedResponse))); + } ++ if let Err(e) = ready!(self.as_mut().read_stream(cx)) { ++ self.state = ReadState::Done; ++ self.trailer = None; ++ return Poll::Ready(Some(Err(e))); ++ } + } + } + } diff --git a/vendor/tonic-web-wasm-client/trailers.patch b/vendor/tonic-web-wasm-client/trailers.patch new file mode 100644 index 0000000..b8cf4a4 --- /dev/null +++ b/vendor/tonic-web-wasm-client/trailers.patch @@ -0,0 +1,98 @@ +diff --git a/src/body_stream.rs b/src/body_stream.rs +index 81af90c..55a4811 100644 +--- a/src/body_stream.rs ++++ b/src/body_stream.rs +@@ -35,6 +35,15 @@ impl BodyStream { + } + } + ++ /// A body made of in-memory chunks, for unit tests that run without a browser. ++ #[cfg(test)] ++ pub(crate) fn from_chunks(chunks: Vec) -> Self { ++ Self { ++ body_stream: Box::pin(futures_util::stream::iter(chunks.into_iter().map(Ok))), ++ _abort: None, ++ } ++ } ++ + pub fn empty() -> Self { + let body_stream = empty(); + +diff --git a/src/response_body.rs b/src/response_body.rs +index 934c05d..282827c 100644 +--- a/src/response_body.rs ++++ b/src/response_body.rs +@@ -97,10 +97,10 @@ pub enum ReadState { + } + + impl ReadState { ++ /// The body is complete only once the trailer frame has been read in full. Seeing the trailer ++ /// flag is not enough: the rest of the frame may still be on its way, or never arrive. + fn finished_data(&self) -> bool { +- matches!(self, ReadState::TrailerLength) +- || matches!(self, ReadState::Trailer(_)) +- || matches!(self, ReadState::Done) ++ matches!(self, ReadState::Done) + } + } + +@@ -130,8 +130,20 @@ impl ResponseBody { + let body_stream = + wasm_streams::ReadableStream::from_raw(body_stream.unchecked_into()).into_stream(); + ++ Self::from_body_stream( ++ BodyStream::new(body_stream, abort), ++ content_type, ++ trailers_only, ++ ) ++ } ++ ++ fn from_body_stream( ++ body_stream: BodyStream, ++ content_type: &str, ++ trailers_only: bool, ++ ) -> Result { + Ok(Self { +- body_stream: BodyStream::new(body_stream, abort), ++ body_stream, + buf: EncodedBytes::new(content_type)?, + incomplete_data: BytesMut::new(), + data: None, +@@ -284,9 +296,13 @@ impl Body for ResponseBody { + return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); + } + +- // If reading data is finished return `None` ++ // Once the body is complete, hand the trailers to the caller (once), then end + if self.state.finished_data() { +- return Poll::Ready(None); ++ return Poll::Ready( ++ self.trailer ++ .take() ++ .map(|t| Ok(http_body::Frame::trailers(t))), ++ ); + } + + loop { +@@ -305,8 +321,12 @@ impl Body for ResponseBody { + let data = self.data.take().unwrap(); + return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); + } else if self.state.finished_data() { +- // If we finished reading data continue return `None` +- return Poll::Ready(None); ++ // The body is complete: hand the trailers to the caller (once), then end ++ return Poll::Ready( ++ self.trailer ++ .take() ++ .map(|t| Ok(http_body::Frame::trailers(t))), ++ ); + } else if self.finished_stream { + // A trailers-only response carries its status in the HTTP headers and has an empty + // body: the stream legitimately ends before any frame header. +@@ -342,3 +362,6 @@ impl Default for ResponseBody { + } + } + } ++ ++#[cfg(test)] ++mod tests;