Skip to content

payjoin-mailroom: bound request bodies before buffering - #2031

Open
codaMW wants to merge 1 commit into
payjoin:masterfrom
codaMW:fix/mailroom-bound-request-body
Open

codaMW wants to merge 1 commit into
payjoin:masterfrom
codaMW:fix/mailroom-bound-request-body

Conversation

@codaMW

@codaMW codaMW commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes the request-body RAM gap in #941 ("tower_http::limit, remove our custom body size limiter").

Every handler in payjoin-mailroom read the full request body into memory with body.collect() and only then checked its length, so a client could make the server buffer an arbitrarily large body on any route; handle_ohttp_gateway had no size check at all, and the relay's into_forward_req forwarded an unbounded body.

Each read is now bounded with http_body_util::Limited at the largest size that path legitimately accepts, so an oversized body is rejected before it is buffered, and the manual post-buffer checks are removed:

  • OHTTP gateway, direct V1 routes, and the relay forward path: a conservative MAX_REQUEST_BODY_BYTES (64 KiB) ceiling. The encapsulated request is only ~8 KiB, so this bounds memory without rejecting valid traffic.
  • post_mailbox (v2 payload): the tighter MAX_MAILBOX_PAYLOAD_BYTES, preserving the "too large to return through the gateway" rule from Reject mailbox payloads the gateway can't return #1983.

Oversized bodies are rejected with 413 on the gateway, V1 PUT, and relay paths; post_fallback_v1 answers a BIP78 v1 sender with the JSON reject body and 400 instead, as those senders expect. The relay previously answered 400 with the raw error string; it now returns 413 via a new ohttp_relay::Error::PayloadTooLarge, matching the directory.

On approach: axum::extract::DefaultBodyLimit only governs the Bytes/Json extractors, which these raw-body handlers don't use. A router-level RequestBodyLimitLayer does build on axum 0.8 (thanks @Xoulomon for checking), but it only returns 413 up front when Content-Length is set; without that header the overflow reaches the handler wrapped in axum::Error, so a downcast_ref::<LengthLimitError>() misses it unless it walks source(). The per-handler Limited catches the overflow regardless of Content-Length, which is why I kept it. I renamed V1_MAX_BUFFER_SIZE to MAX_REQUEST_BODY_BYTES since it now serves as the general raw-request ceiling.

Tested (payjoin-mailroom, --all-features):

  • request_body_over_limit_is_rejected_at_ingress / request_body_at_limit_passes_ingress: a body one byte over the gateway ceiling returns 413 before buffering; a body at the ceiling passes.
  • relay_rejects_body_over_limit_before_forwarding / relay_forwards_body_at_limit: the relay rejects an over-limit body with 413 and never forwards it; a body at the limit reaches the gateway. Mutating the relay bound to usize::MAX flips the over-limit test (the body reaches the gateway, 200 instead of 413).
  • Existing gateway round-trip and "too large to return" tests still pass.

The V1 put_payjoin_v1 and post_fallback_v1 bounds are defense-in-depth and not independently testable: put_payjoin_v1 only runs on a decapsulated request whose body the gateway has already bounded, and an oversized post_fallback_v1 body is caught by the downstream MAX_MAILBOX_PAYLOAD_BYTES check with the identical 400 + reject JSON.

Tightening the gateway to the exact request size (vs the conservative 64 KiB) needs a request/response size-budget reconciliation, tracked as a follow-up in #2041.

AI disclosure: I used an AI assistant for code navigation, for working through the approach, and to draft this description. I reviewed and understand the change, and ran all tests and the mutation myself.

@coveralls

coveralls commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Report for CI Build 42575855398

Coverage increased (+0.05%) to 87.889%

Details

  • Coverage increased (+0.05%) from the base build.
  • Patch coverage: 6 uncovered changes across 3 files (113 of 119 lines covered, 94.96%).
  • No coverage regressions found.

Uncovered Changes

File Changed Covered %
payjoin-mailroom/src/directory.rs 21 17 80.95%
payjoin-mailroom/src/ohttp_relay/error.rs 2 1 50.0%
payjoin-mailroom/src/ohttp_relay/mod.rs 5 4 80.0%
Total (4 files) 119 113 94.96%

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 18710
Covered Lines: 16444
Line Coverage: 87.89%
Coverage Strength: 312.6 hits per line

💛 - Coveralls

@caarloshenriq caarloshenriq left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK 83fc434

One gap: the relay still buffers unbounded. into_forward_req in ohttp_relay/mod.rs calls body.collect() with no limit, and it’s reachable through any gateway that opts in, in the same process as the directory. Since the commit message says every request handler, could this either cover the relay too, or narrow the message and leave the relay for a follow-up?

/// The largest raw request body any route accepts, a conservative
/// in-memory ceiling so a body is never buffered unbounded. The V2
/// mailbox payload has its own smaller cap in `MAX_MAILBOX_PAYLOAD_BYTES`.
pub(crate) const MAX_REQUEST_BODY_BYTES: usize = 65536;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every OHTTP request payjoin sends is exactly ENCAPSULATED_MESSAGE_BYTES (8192), so the gateway could cap at that instead of 64 KiB. Is there a reason to allow 8x the largest valid request on that route? The V1 routes might still need the larger ceiling

match http_body_util::Limited::new(body, MAX_REQUEST_BODY_BYTES).collect().await {
Ok(collected) => collected.to_bytes(),
Err(_) => return Ok(bad_request_body_res),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This route answers an oversized body with the V1 reject JSON and a 400, not the 413 the description mentions. That seems right for BIP78 senders, which expect the JSON error, but a short comment here would make it clear it’s deliberate rather than a missed collect_within_limit

@codaMW
codaMW force-pushed the fix/mailroom-bound-request-body branch from 83fc434 to 53253be Compare November 4, 2026 19:10
@codaMW

codaMW commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review @caarloshenriq. Addressed in the latest push:

Relay buffering good catch, into_forward_req did buffer unbounded. I bounded it with the same MAX_REQUEST_BODY_BYTES ceiling, so the relay forward path no longer buffers an unbounded body before forwarding, and the commit message now covers it instead of overclaiming.

post_fallback_v1 400 + V1 reject JSON deliberate, as you guessed: a BIP78 v1 sender expects the JSON error, not a 413. Added a comment there so it reads as intentional rather than a missed collect_within_limit.

Capping the gateway at ENCAPSULATED_MESSAGE_BYTES you're right that a real client's request is exactly that size (encapsulate returns [u8; ENCAPSULATED_MESSAGE_BYTES]), so 64 KiB is ~8x. I tried the tight cap first and it surfaced a request-vs-response budget mismatch I'd rather not entangle with this change:

  • The existing largest_mailbox_payload_round_trips_through_gateway test fails under an 8192 cap: its through_gateway helper pads the bhttp to BHTTP_REQ_BYTES (ENCAPSULATED_MESSAGE_BYTES - nonce - tag = 8144, the response-framing budget) rather than the request budget, so it builds an ~8232-byte encapsulated request that only passed because the gateway was unbounded.
  • More fundamentally, MAX_MAILBOX_PAYLOAD_BYTES (8137) already exceeds the request plaintext budget PADDED_BHTTP_REQ_BYTES (ENCAPSULATED_MESSAGE_BYTES - N_ENC - N_T header = 8104) by 33 bytes. The mailbox size constants are response-sized, so a tight request cap on this route means reconciling those constants.

So I kept a single conservative ceiling it bounds memory (the goal) without coupling this PR to the request/response size model. Happy to tighten the gateway to the exact request size as a follow-up that reconciles those budgets and fixes the test helper's padding I can open an issue for it if you think it's worth doing.

@Xoulomon

Xoulomon commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Concept ACK, tACK 53253be with one test request below.

  • Only the gateway and mailbox limits are covered. With the limits on put_payjoin_v1 (directory.rs:319), post_fallback_v1 (directory.rs:349), and into_forward_req (ohttp_relay/mod.rs:326) all set to usize::MAX, the suite still passes (92/92). Could you add an over-limit case for each: 413 for the V1 PUT, the V1 JSON 400 for the fallback POST, and the relay?
  • On the approach: a router-level RequestBodyLimitLayer does type-check here. I added .layer(RequestBodyLimitLayer::new(MAX_REQUEST_BODY_BYTES)) in build_app (tower-http limit feature) and it builds on axum 0.8. It returns 413 up front when Content-Length is set. Without that header, the overflow reaches the handler wrapped in axum::Error, so the downcast_ref::<LengthLimitError>() in collect_within_limit misses it and request_body_over_limit_is_rejected_at_ingress gets 400. So the layer is workable (it is what Payjoin Mailroom Tracking Issue #941 asks for) if the downcast walks source(). Please correct the PR description either way; whether to switch is a maintainer call.
  • nit: the relay maps an oversized body to Error::BadRequest (400, ohttp_relay/mod.rs:329) while the directory returns 413. A PayloadTooLarge variant would keep them consistent.
  • nit: collect_within_limit drops the underlying read error (directory.rs:59); anyhow::anyhow!(e) would keep it in the warn! log.
  • +1 to caarloshenriq on capping the gateway at ENCAPSULATED_MESSAGE_BYTES. Your arithmetic checks out (8137 > 8104), so please open the follow-up issue you offered.

Tested: fmt, clippy (-p payjoin-mailroom --all-targets --all-features), and cargo test -p payjoin-mailroom --all-features --lib (92 pass). Raising the gateway limit by 1 fails request_body_over_limit_is_rejected_at_ingress; raising the mailbox limit fails mailbox_payload_too_large_to_return_is_rejected; unbounding the V1 and relay limits fails nothing.

AI-assisted review; I ran the tests and mutations myself.

Every inbound request read the whole body into memory with
body.collect() before checking its size, so a client could force the
server to buffer an arbitrarily large body on any route. The OHTTP
gateway and the relay forward path had no size check at all.

Cap each read with http_body_util::Limited at the largest size that
path accepts: a conservative MAX_REQUEST_BODY_BYTES ceiling for the
gateway, the relay forward, and the direct V1 routes, and the tighter
MAX_MAILBOX_PAYLOAD_BYTES for the v2 mailbox payload. Oversized
bodies are rejected before they are buffered, and the manual
post-buffer length checks are removed.

Signed-off-by: codaMW <[email protected]>
@codaMW
codaMW force-pushed the fix/mailroom-bound-request-body branch from 7345f57 to 44927a4 Compare November 9, 2026 06:53
@codaMW

codaMW commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Xoulomon, @caarloshenriq. Addressed:

  • Relay 413: now returns 413 via a new Error::PayloadTooLarge (was 400 + raw error), matching the directory.
  • Relay test: added over/at-limit tests on the configured_purposes_reach_the_relay harness; mutating the bound to usize::MAX flips the over-limit one (200 vs 413).
  • V1 bounds: you're right that unbounding them fails nothing. put_payjoin_v1 only sees decapsulated bodies the gateway already bounds (~8 KiB), so its 64 KiB ceiling is unreachable; an oversized post_fallback_v1 body hits the MAX_MAILBOX_PAYLOAD_BYTES check with the same 400 + reject JSON. Both are defense-in-depth I'd rather not add tests that can't fail, but happy to reconsider.
  • Description: corrected RequestBodyLimitLayer does type-check; I kept per-handler Limited because the layer misses the no-Content-Length overflow.
  • nit: collect_within_limit now keeps the underlying error in the log.
  • Gateway exact-size cap: opened Payjoin-mailroom: cap the OHTTP gateway at the exact request size and reconcile request/response size budgets #2041.

AI-assisted, I ran the tests and mutation myself.

@CaptainLevi2k04 CaptainLevi2k04 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good overall, just a question about the V1 limits!!

Comment on lines +350 to +351
let body_bytes =
match http_body_util::Limited::new(body, MAX_REQUEST_BODY_BYTES).collect().await {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if this fired, MAX_MAILBOX_PAYLOAD_BYTES below catches the same body with the same 400...
So this bound is also unreachable...
Same question as put_payjoin_v1

if req.len() > V1_MAX_BUFFER_SIZE {
return Err(HandlerError::PayloadTooLarge);
}
let req = collect_within_limit(body, MAX_REQUEST_BODY_BYTES).await?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This limit can't fire the put_payjoin_v1... this only sees bodies the gateway already capped at ~8 KiB.
It's dead defense-in-depth...
Could be Kept with a comment saying so, or drop it?

@CaptainLevi2k04 CaptainLevi2k04 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested replacement:
"Reject request bodies larger than a route accepts before buffering them, closing an unbounded-memory read on the OHTTP gateway and the relay (#2031)" (or mention the mailbox).

## Unreleased

- Let relay operators accept gateway purposes besides BIP77 with `[ohttp_relay] extra_allowed_purposes` (#2024)
- Reject request bodies larger than a route accepts before buffering them, closing an unbounded-memory read on the OHTTP gateway and the V1 routes (#2031)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the V1 limits are unreachable (as discussed), saying this fixes an unbounded-memory read on 'V1 routes' is misleading. The real fix is for the OHTTP gateway and the relay. Can we reword this?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants