Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/rust-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
106 changes: 96 additions & 10 deletions vendor/tonic-web-wasm-client/VENDORED.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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).

Expand All @@ -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.
14 changes: 14 additions & 0 deletions vendor/tonic-web-wasm-client/src/body_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Bytes>) -> Self {
Self::from_stream(futures_util::stream::iter(chunks.into_iter().map(Ok)))
}

#[cfg(test)]
pub(crate) fn from_stream(stream: impl Stream<Item = Result<Bytes, Error>> + 'static) -> Self {
Self {
body_stream: Box::pin(stream),
_abort: None,
}
}

pub fn empty() -> Self {
let body_stream = empty();

Expand Down
116 changes: 71 additions & 45 deletions vendor/tonic-web-wasm-client/src/response_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<Self, Error> {
Ok(Self {
body_stream: BodyStream::new(body_stream, abort),
body_stream,
buf: EncodedBytes::new(content_type)?,
incomplete_data: BytesMut::new(),
data: None,
Expand Down Expand Up @@ -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 => {
Expand Down Expand Up @@ -244,23 +243,48 @@ 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());

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(()),
}
Expand All @@ -277,49 +301,48 @@ impl Body for ResponseBody {
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<Self::Data>, 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);
}
// 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)));
}
}
}
}
Expand All @@ -342,3 +365,6 @@ impl Default for ResponseBody {
}
}
}

#[cfg(test)]
mod tests;
Binary file not shown.
Binary file not shown.
Loading