From 1532975bc629e0afeb0df95ac52e47282fcceb16 Mon Sep 17 00:00:00 2001 From: Daniel Gorgonha Date: Sat, 14 Nov 2026 23:07:36 -0300 Subject: [PATCH 1/7] test(vendor): unit tests for the gRPC-web trailer frame in tonic-web-wasm-client The response body can now be fed from in-memory chunks, so the tests run natively, without a browser: `ResponseBody::new` delegates to a private `from_body_stream` (no change in behaviour), and a `cfg(test)` `BodyStream::from_chunks` builds the stream. Eight of the tests fail on this commit: the trailer frame is parsed but never handed to tonic, so a status sent in the body trailer is lost. Co-Authored-By: Claude --- .../tonic-web-wasm-client/src/body_stream.rs | 9 + .../src/response_body.rs | 17 +- .../fixtures/body-trailer-error.bin | Bin 0 -> 131 bytes .../fixtures/data-then-trailer-ok.bin | Bin 0 -> 79 bytes .../src/response_body/tests.rs | 380 ++++++++++++++++++ 5 files changed, 405 insertions(+), 1 deletion(-) create mode 100644 vendor/tonic-web-wasm-client/src/response_body/fixtures/body-trailer-error.bin create mode 100644 vendor/tonic-web-wasm-client/src/response_body/fixtures/data-then-trailer-ok.bin create mode 100644 vendor/tonic-web-wasm-client/src/response_body/tests.rs diff --git a/vendor/tonic-web-wasm-client/src/body_stream.rs b/vendor/tonic-web-wasm-client/src/body_stream.rs index 81af90c..55a4811 100644 --- a/vendor/tonic-web-wasm-client/src/body_stream.rs +++ b/vendor/tonic-web-wasm-client/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/vendor/tonic-web-wasm-client/src/response_body.rs b/vendor/tonic-web-wasm-client/src/response_body.rs index 934c05d..87b8309 100644 --- a/vendor/tonic-web-wasm-client/src/response_body.rs +++ b/vendor/tonic-web-wasm-client/src/response_body.rs @@ -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, @@ -342,3 +354,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 0000000000000000000000000000000000000000..8d29a14cdbd3d6a69fe07246691e87c4cb2f6cf2 GIT binary patch literal 131 zcmZo*U|^_ANi0dVQV1^1(@`)qRq)F%Q!p|xGE*=xvH~JQLj`x=5MHkIqJm`I+|=UY z#B`uy_tX-noc!c$D}^KwrC+^csThMqmaU(FBN~!9ABwp_**x(@9w+pt9ER6PdVtI 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); + +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"); + std::future::ready(Ok(http::Response::builder() + .status(StatusCode::OK) + .header(http::header::CONTENT_TYPE, CONTENT_TYPE) + .body(body) + .expect("static response parts are valid"))) + } +} + +fn through_tonic_unary(body: ResponseBody) -> Result { + let mut grpc = tonic::client::Grpc::new(FixedResponse(Some(body))); + 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) + )); + } +} From 95ac80924b4daeec0cbddd60ea6f8282931ba7a2 Mon Sep 17 00:00:00 2001 From: Daniel Gorgonha Date: Sat, 14 Nov 2026 23:08:35 -0300 Subject: [PATCH 2/7] fix(vendor): forward the gRPC-web trailer frame to tonic tonic-web-wasm-client 0.8.0 parsed the trailer frame, stored it in a field nothing read, and ended the body as soon as it saw the trailer flag. tonic never got the trailers, and with HTTP 200 and no trailers it reports success, so a status sent in the body trailer (an error after some messages, or after a unary message) was lost. The body now yields the parsed trailers as a trailers frame, once, after the last data frame. It only counts as finished once the trailer frame has been read in full, so a trailer split across chunks is read and a stream that ends inside the trailer frame is MalformedResponse instead of a clean end. The first part is the response_body.rs change of upstream 0f232d33 (devashishdxt/tonic-web-wasm-client#90, released in 0.9.1). Co-Authored-By: Claude --- .../src/response_body.rs | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/vendor/tonic-web-wasm-client/src/response_body.rs b/vendor/tonic-web-wasm-client/src/response_body.rs index 87b8309..282827c 100644 --- a/vendor/tonic-web-wasm-client/src/response_body.rs +++ b/vendor/tonic-web-wasm-client/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) } } @@ -296,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 { @@ -317,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. From a83238a2ed06e95f391830ae4555c16762cd475b Mon Sep 17 00:00:00 2001 From: Daniel Gorgonha Date: Sat, 14 Nov 2026 23:09:18 -0300 Subject: [PATCH 3/7] docs(vendor): describe the trailer fix, add its patch file and a CI job for the vendored tests trailers.patch applies on top of trailers-only.patch and reproduces src/ from crates.io 0.8.0, apart from the test files: it carries their two cfg(test) hooks but not src/response_body/. The vendored crate is excluded from the workspace, so a separate job runs its tests against the workspace lock. Co-Authored-By: Claude --- .github/workflows/rust-checks.yml | 13 +++ vendor/tonic-web-wasm-client/VENDORED.md | 70 +++++++++++++-- vendor/tonic-web-wasm-client/trailers.patch | 98 +++++++++++++++++++++ 3 files changed, 172 insertions(+), 9 deletions(-) create mode 100644 vendor/tonic-web-wasm-client/trailers.patch 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..2283843 100644 --- a/vendor/tonic-web-wasm-client/VENDORED.md +++ b/vendor/tonic-web-wasm-client/VENDORED.md @@ -1,10 +1,15 @@ -# Vendored `tonic-web-wasm-client` 0.8.0, with one fix +# Vendored `tonic-web-wasm-client` 0.8.0, with two fixes 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 changes in `trailers-only.patch` and then `trailers.patch`, wired in through +`[patch.crates-io]` in the workspace `Cargo.toml`. The unit tests in `src/response_body/` are ours. +`trailers.patch` carries only their two `cfg(test)` hooks (`mod tests;` and +`BodyStream::from_chunks`), not the test files, so on a plain upstream checkout the patched crate +builds but `cargo test` needs `src/response_body/` copied too. -## 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 +19,61 @@ 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`) + +Found and reproduced by Crackdevs (https://github.com/Crackdevs/zcash-browser-ohttp-proof). + +### 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, then ends. + 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. + +Known and not changed: a response with `grpc-status: 0` in the headers and an error in a body +trailer still reports success (tonic does not read the body then); repeated trailer keys keep only +the last value (upstream issue 103); bytes after the trailer frame are ignored; like a data frame, +a trailer frame is buffered until its announced length has arrived. + +### Tests + +`cargo test --locked -p tonic-web-wasm-client` from the workspace root runs them natively against +the workspace lock (CI: the `vendored-tonic-web-wasm-client` job in `rust-checks.yml`). + ## 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). @@ -34,6 +85,7 @@ reviews). Release 0.9.2 (2026-09-14) does not include it. Do not send our patch ## To remove -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 both +fixes are in an upstream release the pins allow. `trailers-only.patch` is a ready-made upstream +change (apply with `patch -p1` from a `tonic-web-wasm-client` checkout); `trailers.patch` applies +on top of it. 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; From e9da345b58654b2853bf5666d1087cbe933d59b9 Mon Sep 17 00:00:00 2001 From: Daniel Gorgonha Date: Sun, 15 Nov 2026 11:55:20 -0300 Subject: [PATCH 4/7] docs(vendor): credit Crackdevs for fixing the trailer loss first Their browser OHTTP proof had already fixed it in its own patch, not only found it. Co-Authored-By: Claude --- vendor/tonic-web-wasm-client/VENDORED.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/vendor/tonic-web-wasm-client/VENDORED.md b/vendor/tonic-web-wasm-client/VENDORED.md index 2283843..bf438b2 100644 --- a/vendor/tonic-web-wasm-client/VENDORED.md +++ b/vendor/tonic-web-wasm-client/VENDORED.md @@ -27,7 +27,9 @@ ends early on any other response is still `MalformedResponse`. ## Fix 2: the trailer frame reaches tonic (`trailers.patch`) -Found and reproduced by Crackdevs (https://github.com/Crackdevs/zcash-browser-ohttp-proof). +Found, reproduced and first fixed by Crackdevs in their browser OHTTP proof +(https://github.com/Crackdevs/zcash-browser-ohttp-proof). That repository has no licence file, so +none of their code is used here; this fix was written separately. ### Why From a1891413e5caa33bf3747ab478b9f65cbe0561a1 Mon Sep 17 00:00:00 2001 From: Daniel Gorgonha Date: Sun, 15 Nov 2026 13:58:13 -0300 Subject: [PATCH 5/7] chore: credit Crackdevs as co-author of the trailer fix They found the lost trailer status, reproduced it and fixed it first in their browser OHTTP proof (https://github.com/Crackdevs/zcash-browser-ohttp-proof). Co-authored-by: Crackdevs Co-Authored-By: Claude From b0fd0006ee6cd9fd80a9be61d025b93f86c0ced4 Mon Sep 17 00:00:00 2001 From: Crackdevs Date: Tue, 17 Nov 2026 15:41:17 +0000 Subject: [PATCH 6/7] fix(vendor): validate gRPC-web body trailers before completion --- vendor/tonic-web-wasm-client/VENDORED.md | 80 +++-- .../tonic-web-wasm-client/src/body_stream.rs | 7 +- .../src/response_body.rs | 109 ++++--- .../src/response_body/tests.rs | 307 +++++++++++++++++- .../trailers-completion.patch | 195 +++++++++++ 5 files changed, 613 insertions(+), 85 deletions(-) create mode 100644 vendor/tonic-web-wasm-client/trailers-completion.patch diff --git a/vendor/tonic-web-wasm-client/VENDORED.md b/vendor/tonic-web-wasm-client/VENDORED.md index bf438b2..0f92ab3 100644 --- a/vendor/tonic-web-wasm-client/VENDORED.md +++ b/vendor/tonic-web-wasm-client/VENDORED.md @@ -1,11 +1,9 @@ -# Vendored `tonic-web-wasm-client` 0.8.0, with two fixes +# 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 changes in `trailers-only.patch` and then `trailers.patch`, wired in through -`[patch.crates-io]` in the workspace `Cargo.toml`. The unit tests in `src/response_body/` are ours. -`trailers.patch` carries only their two `cfg(test)` hooks (`mod tests;` and -`BodyStream::from_chunks`), not the test files, so on a plain upstream checkout the patched crate -builds but `cargo test` needs `src/response_body/` copied too. +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. ## Fix 1: trailers-only responses (`trailers-only.patch`) @@ -27,9 +25,10 @@ ends early on any other response is still `MalformedResponse`. ## Fix 2: the trailer frame reaches tonic (`trailers.patch`) -Found, reproduced and first fixed by Crackdevs in their browser OHTTP proof -(https://github.com/Crackdevs/zcash-browser-ohttp-proof). That repository has no licence file, so -none of their code is used here; this fix was written separately. +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 @@ -46,7 +45,7 @@ so without this fix a `cargo update` of tonic would fail every call that has a b ### The change -- After the last data frame the body yields the parsed trailers as one trailers frame, then ends. +- 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 @@ -63,15 +62,40 @@ Behaviour that changes besides the fix: a trailer block that does not parse now 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. -Known and not changed: a response with `grpc-status: 0` in the headers and an error in a body -trailer still reports success (tonic does not read the body then); repeated trailer keys keep only -the last value (upstream issue 103); bytes after the trailer frame are ignored; like a data frame, -a trailer frame is buffered until its announced length has arrived. - -### Tests - -`cargo test --locked -p tonic-web-wasm-client` from the workspace root runs them natively against -the workspace lock (CI: the `vendored-tonic-web-wasm-client` job in `rust-checks.yml`). +## 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. +- 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 @@ -85,9 +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, the `exclude` entry and the CI job once both -fixes are in an upstream release the pins allow. `trailers-only.patch` is a ready-made upstream -change (apply with `patch -p1` from a `tonic-web-wasm-client` checkout); `trailers.patch` applies -on top of it. +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 55a4811..dcd8c8a 100644 --- a/vendor/tonic-web-wasm-client/src/body_stream.rs +++ b/vendor/tonic-web-wasm-client/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/vendor/tonic-web-wasm-client/src/response_body.rs b/vendor/tonic-web-wasm-client/src/response_body.rs index 282827c..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 { - /// 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/src/response_body/tests.rs b/vendor/tonic-web-wasm-client/src/response_body/tests.rs index 3ce9635..4d4012d 100644 --- a/vendor/tonic-web-wasm-client/src/response_body/tests.rs +++ b/vendor/tonic-web-wasm-client/src/response_body/tests.rs @@ -6,12 +6,17 @@ use std::{ future::Future, - pin::pin, - task::{Context, Poll, Waker}, + pin::{pin, Pin}, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, Mutex, + }, + task::{Context, Poll, Wake, Waker}, }; use bytes::{Buf, BufMut, Bytes}; -use http::{HeaderMap, StatusCode}; +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}, @@ -166,7 +171,7 @@ fn through_tonic_stream(body: ResponseBody) -> (Vec, Result<(), Status>) } /// A gRPC service that answers every call with a fixed gRPC-web body and HTTP 200. -struct FixedResponse(Option); +struct FixedResponse(Option, HeaderMap); impl tower_service::Service> for FixedResponse { type Response = http::Response; @@ -179,16 +184,18 @@ impl tower_service::Service> for FixedResponse fn call(&mut self, _: http::Request) -> Self::Future { let body = self.0.take().expect("one call per test"); - std::future::ready(Ok(http::Response::builder() + let mut response = http::Response::builder() .status(StatusCode::OK) .header(http::header::CONTENT_TYPE, CONTENT_TYPE) .body(body) - .expect("static response parts are valid"))) + .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))); + 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()) } @@ -378,3 +385,289 @@ fn nothing_is_yielded_after_the_trailers() { )); } } + +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))); ++ } + } + } + } From 5cf2f1b890f050138e39ad77cb8a6453e6ce33c1 Mon Sep 17 00:00:00 2001 From: Crackdevs Date: Tue, 17 Nov 2026 14:18:57 -0500 Subject: [PATCH 7/7] Update VENDORED.md --- vendor/tonic-web-wasm-client/VENDORED.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/tonic-web-wasm-client/VENDORED.md b/vendor/tonic-web-wasm-client/VENDORED.md index 0f92ab3..dd58fd2 100644 --- a/vendor/tonic-web-wasm-client/VENDORED.md +++ b/vendor/tonic-web-wasm-client/VENDORED.md @@ -70,7 +70,7 @@ and the [follow-up proposed by Daniel/Konclave](https://github.com/Crackdevs/zca - 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. + 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