Repository navigation
Add configurable Axum buffered JSON body limits - #407
ChristianPavilonis wants to merge 23 commits into
Conversation
dhruv8sh
left a comment
There was a problem hiding this comment.
PR Review
Summary
This adds a configurable 2 MiB ceiling on buffered JSON bodies for Axum, with a 413 status through a new EdgeError::PayloadTooLarge. The runtime logic is sound:
- The size check runs before each chunk is appended, so streamed bodies are never buffered past the cap.
- Overflow handling is sticky, and the source is dropped exactly once.
- The JSON classification is fixed at ingress, and
Json/ValidatedJsonare capped regardless of Content-Type, so the "only capped when JSON" rule can't be bypassed.
I found no runtime bugs. I'm requesting changes for two blocking questions about integration with #275 (the open PR this branch depends on). Both should be settled before this merges.
😃 Praise
- 😃 Careful overflow handling in the body reader, strict and leak-free config validation, and thorough end-to-end boundary tests (see inline).
Findings
Blocking
- ❓ The JSON limit's config surface will clash with #275's
AxumIngressConfig(crates/edgezero-adapter-axum/src/run_options.rs:21, inline) - ❓ The #275 baseline audit is stale, and the docs are still marked provisional (
docs/superpowers/plans/2026-10-06-axum-buffered-json-body-limit.md:25, inline). The same provisional status appears at plan:4and:34, atdocs/superpowers/specs/2026-10-06-axum-buffered-json-body-limit-design.md:4, and atdocs/superpowers/specs/2026-08-22-inbound-body-design.md:28.
Non-blocking
- 🤔 Carrying the policy inside public
Bodyforces a breaking API change (crates/edgezero-core/src/body.rs:42, inline) - 🤔
Body::with_buffered_json_policyis public but only adapters need it (crates/edgezero-core/src/body.rs:124, inline) - 🤔 The JSON classifier reads only the first Content-Type header (
crates/edgezero-adapter-axum/src/request.rs:44, inline) - ♻️
capture_dev_environmentduplicates the key check infrom_env(crates/edgezero-adapter-axum/src/dev_server.rs:741, inline) - 📝 Status-code changes the guide doesn't spell out (
docs/guide/handlers.md:111, inline) - 🌱 Reject early on a declared Content-Length (
crates/edgezero-core/src/context.rs:713): JSON reads could fail immediately when the declaredContent-Lengthis over the effective cap, instead of reading up to the cap first. Not needed now. - ⛏ Machine-specific paths in the new docs (inline on the plan
:21and the design spec:12). The plan also cites/tmp/393-final-*.logfiles as evidence at:362-373; suggest replacing those with commands plus results, or a CI run link. - 📝
Bodygrows by one word, which is why#[expect(clippy::large_enum_variant)]was added incrates/edgezero-core/src/outbound.rsandcrates/edgezero-adapter-fastly/src/outbound.rs. No action needed, and it goes away if theBodyrefactor suggestion is adopted.
📌 Out of Scope
docs/superpowers/specs/2026-10-05-axum-production-startup-lifecycle-design.md:10contains the same/home/pav/...worktree path. It comes from #406, so it should be fixed there.
Dependency on #275
I think #275 should block the merge and the final review of this PR, but not this review. #275 has moved past the audited 950cb81 and now adds its own Axum ingress config plus a large dev_server.rs rework. That affects where this config should live and will cause rebase conflicts. The core body.rs/context.rs logic this PR relies on hasn't changed there. Before merge: rebase onto the accepted #275, redo the audit, and settle the config-naming question.
CI Status
- fmt: PASS
- clippy: PASS
- tests: PASS (1,861 passed). One
edgezero-macrostrybuild failure was environmental (build files vanished mid-build) and passed 9/9 on an isolated rerun. - No GitHub checks ran on this PR, likely because its base isn't
main.
3308041 to
e867c12
Compare
aram356
left a comment
There was a problem hiding this comment.
PR Review
Summary
This adds a configurable Axum ceiling, 2 MiB by default, for framework-managed JSON buffering. The limit is carried as a private policy on Body and re-applied through into_request. The core mechanism and config validation are careful, but four things need to change:
- The new dev-server boundary test is flaky.
- A cached body re-entering pre-dispatch skips the
InputGuard. - The docs and the PR description describe an API that this PR does not ship.
- The CHANGELOG doesn't flag the breaking changes that do ship.
Findings
Blocking
- 🔧 New boundary test is flaky (
dev_server.rs:1965): the 413 races a connection reset. It failed 6/30 runs in isolation and 3/20 in the full suite. - 🔧 Cached re-entry bypasses
InputGuard(context.rs:781): fallback outcomes differ from base. - 🔧 Docs and PR description describe an API that isn't shipped, and the wrong overflow status (
inbound-body-design.md:22). The other locations:- Spec
2026-10-06-axum-buffered-json-body-limit-design.md:- L49, L58, L166, L294, L301–303 and L333–334 state the non-exhaustive
Body/BodyContent/ adapter-migration design as fact. The note at L18–25 says that design was replaced. - L80, L81, L144 and L322 claim overflow returns 400.
- L256 says there is no request-body-too-large variant.
- L49, L58, L166, L294, L301–303 and L333–334 state the non-exhaustive
- Plan
2026-10-06-axum-buffered-json-body-limit.mdhas no supersession note:- L52, L67–111, L134–153 and L356 specify the Managed/BodyContent design.
- L114 marks all four adapters' body consumers as aligned.
- L149, L153, L175, L191 and L193 claim overflow returns 400.
- L398 cites
managed_content_accessors_and_manual_collection_ignore_ingress_ceiling, Body/BodyContent rustdoc fixtures and outbound/response/framing regressions. None of them exist. - The L362–385 evidence was recorded on
3ab2209with "25 changed inputs", not on this 22-file head.
- PR description:
- These parts describe changes that are not in the diff: the Changes-table rows for
body.rs/lib.rs, core outbound/response preparation and "All four adapters", plus the Breaking API paragraph. The description itself also says the obsolete carrier enum is not restored. - The status lines contradict each other: "Ready for review" vs "Keep this PR draft"; "No parent code was merged" vs the merge commits on the branch; "Closes #393" vs spec L387 ("does not close #393").
- The checked "Public source breaks documented" item refers to a break that didn't happen, while the real breaks are undocumented.
- These parts describe changes that are not in the diff: the Changes-table rows for
- Spec
- 🔧 CHANGELOG misses the real breaking changes, and the rustdoc is stale (
CHANGELOG.md:7).
Non-blocking
- 🤔
with_buffered_json_policyis public, unvalidated, and only the first call takes effect (body.rs:76). - 🤔 Rewrapping the body falls back to the looser 8 MiB default (
context.rs:355). - 🤔 JSON classification misses valid media types (
request.rs:156). - ♻️ The policy field grows every
Bodyfrom 40 to 64 bytes (body.rs:27). - ⛏ Blanket
arbitrary_source_item_orderingexpects (body.rs:67,context.rs:338,context.rs:1184). - ⛏ Hex literal for 2 MiB (
run_options.rs:20). - 🌱 No drain before close after an early 413. When the declared
Content-Lengthexceeds the ceiling, the server answers and closes with the body unread, so ordinary clients (reqwest here) often getECONNRESETinstead of the 413. The flaky test above shows it. The docs disclaim client receipt, which is fine for this PR. A later change could read and discard a bounded amount (a few KiB, or a short timeout) before closing, so clients actually see the 413. - 🌱
into_core_requesthas no way to override the limit (request.rs:54).
Earlier review threads
None of the 12 threads from the 2026-10-16 review has a reply. These still apply at this head; please answer them on their threads:
- ❓ JSON limit env-var naming vs
AxumIngressConfig(run_options.rs:22) - ❓ Stale #275 baseline audit and provisional status (
plan:25) - 🤔 Only the first
Content-Typeheader is classified (request.rs:65) - ♻️ Duplicate key check in the dev environment capture (
dev_server.rs:917). It now sharesconfig_path, but still matches the JSON path with its own literal instead offixed_setting. - ⛏ Machine-specific
/home/pav/...paths (spec:12,plan:21)
CI Status
-
fmt: PASS
-
clippy: PASS
-
tests: FAIL on the first run with two failures:
dev_server::tests::router_only_default_json_boundary_for_both_constructors- the pre-existing
connection::tests::pending_chunked_forward_preserves_original_deadlines_over_tcp, which has a 5 ms tolerance and failed 1/20 runs on this head vs 0/20 on base
PASS on rerun.
-
cargo check --workspace --all-targets --features "fastly cloudflare spin": PASS -
cargo check -p edgezero-adapter-spin --target wasm32-wasip2 --features spin: PASS
(cherry picked from commit 9a985c9)
|
For the identity integration branch (#495), I pushed
|
|
For the identity integration branch (#495), I pushed |
Account for reconstructed cached bodies under admission, preserve policy on failed stream conversion, and classify valid JSON media types. Add service, reconstruction and wire coverage and reconcile the documentation with the current stack.
|
The review follow-up is in 64447b46. I updated the PR description and recorded the Linux verification and its limits in the plan. The workspace retry passed 2,834 tests with 2 ignored. The router-only wire test passed 30/30 on Linux; no macOS rerun. On the review-summary items without their own threads: the existing collector already checks declared length early, and the bounded HTTP/1 drain is inherited from #275. #407 adds neither a second collector nor another drain policy. The #406 hosting spec is outside this patch. Still blocks merge: the live #406 branch advanced to |
Carry the selected Axum JSON ceiling through shared service preparation while preserving the hosting lifecycle and both sets of subprocess cases.
Keep the updated Axum startup and shutdown owner, explicit registries, and buffered JSON handling alongside proxy trust, request records, and diagnostics guard ownership. Preserve the production-hosting regressions from both parents.
prk-Jr
left a comment
There was a problem hiding this comment.
PR Review
Summary
Follow-up review at a3ad0428, against the issue-392-396-production-hosting-spec merge base 48097ab1. All four blocking findings from my review at d6f74308 are resolved. I checked each one in the code and in local runs, not only in the replies. The cached re-entry fix reuses the existing input-guard accounting instead of adding a parallel path. The docs and CHANGELOG now describe what the code ships. I found no new blocking issues, so I'm approving. The non-blocking notes below are optional.
😃 Praise
- 😃 The restored-cache fix is small and correct. It routes the
Cachedarm through the sameprepare_protected_bodythe initial drain uses, so the deadline check, fallback max and one-time accounting cannot drift. The fourrestored_cache_*tests cover the exact rows from the earlier probe. - 😃 The service-level source-error and cancellation tests (
managed_json_source_error_releases_partial_body_and_keeps_error_egress,managed_json_cancelled_partial_read_releases_source_without_egress) prove release-once and no-repoll through real dispatch, not just the core collector.
Prior findings status
Prior finding (my review at d6f74308) |
Status at a3ad0428 |
|---|---|
🔧 Flaky over-limit boundary test (dev_server.rs) |
✅ Resolved. router_json_upload (dev_server.rs:1953) now reads while it uploads and accepts a reset only after a complete, framed 413. Locally it passed 30/30 isolated runs on macOS. At d6f74308 the same test failed 18/30. |
🔧 Cached re-entry skips the pre-dispatch InputGuard (context.rs) |
✅ Resolved. The Cached arm now calls prepare_protected_body before check_cached_body (context.rs:404-410). It runs guard.check() and observes the cached length once, while complete is unset. restored_cache_fixed_outcome_is_typed_and_sticky, restored_cache_discard_checks_fallback_limits, restored_cache_read_then_discard_does_not_reaccount and restored_cache_transform_does_not_charge_output cover the three rows (overflow, deadline/discard, transformed output). As a broken control, I removed the new accounting call: three of the four tests fail (the discard test exercises the separate take_body path). |
🔧 Docs and PR description describe an unshipped API (Body::Managed, BodyContent, 400 on overflow) |
✅ Resolved for the API. The spec, plan and inbound-body addendum now describe the private policy on the existing Body struct, an exhaustive BodyPayload and the typed 413. No Managed/BodyContent/into_content references remain. The description's "Merge dependency" section is now stale in the other direction (see the non-blocking note). |
| 🔧 CHANGELOG misses the breaking changes | ✅ Resolved. CHANGELOG.md:7 marks the 8 MiB → 2 MiB default and explicit-cap clamping as Breaking, and notes the Body size and Debug change. The DEFAULT_INBOUND_JSON_BYTES, body_bytes, form_within and json_within rustdoc now mention the native ceiling. with_buffered_json_policy is #[doc(hidden)], so leaving it out of the CHANGELOG is reasonable. |
| Earlier non-blocking threads | All answered on their threads. Declined items (first-field classification, first-call-wins setter, Body layout, into_core_request override) have a stated rationale. I'm fine leaving them as follow-ups. |
Findings
Blocking
None.
Non-blocking
- ⛏ The PR description's "Merge dependency" section is stale: it says the change "has not been integrated with" #406 at
48097ab1and that verification was against merge baseb67e78b9. The heada3ad0428merges48097ab1forward, the merge base is now48097ab1, and the plan has a "Merge-forward integration" section saying exactly that. Please update the description so the squash message doesn't carry the outdated status. - 🌱 The lingering-close bound no longer tracks the JSON limit (
crates/edgezero-adapter-axum/src/header_deadline.rs:27-38, not in this diff).LINGERING_CLOSE_MAX_BYTESis stillDEFAULT_INBOUND_JSON_BYTES(8 MiB), and its doc says it "equals the core's default JSON extractor limit". On Axum that default is now 2 MiB, or whateverJSON_BODY_LIMIT_BYTESselects. With an override above 8 MiB, every declared-length 413 is above the bound, so the connection closes without draining. Clients that write the full body before reading are then likely to see a reset instead of the 413. The docs already disclaim client receipt, and hosted CI plus my local runs pass the 9 MiB + 1 case. A follow-up could derive the bound from the selected ceiling (still capped) and fix the doc comment. - 🤔 The
mimedependency is only used to parse the type/subtype (request.rs:164). The hand-written RFC 9110 parameter parser already does the harder part. Splitting the trimmed essence on/and matchingjsonor a+jsonsuffix would remove the new workspace dependency. This is optional, sincemimeis already a transitive dependency of axum/reqwest.
CI Status
- Hosted checks at
a3ad0428: all PASS (Run Tests including workspace/axum/cli/wasm tests, Run Format including fmt/clippy/docs, Deploy actions smokes, CodeQL). - Local (macOS, Rust 1.98.1, worktree at
a3ad0428):cargo fmt --all -- --check: PASScargo test -p edgezero-core: PASS (1,175 unit tests plus doctests)cargo test -p edgezero-adapter-axum --all-targets --all-features: PASS (366 unit with 1 ignored, 28 contract, 23 production-hosting subprocess tests)cargo +1.98.1 clippy -p edgezero-core -p edgezero-adapter-axum --all-targets --all-features -- -D warnings: PASSrouter_only_json_boundaries_for_both_constructors: 30/30;production_hosting json_*: 10/10 repeated runs- I did not run the full workspace suite or the WASM checks locally; hosted CI covers them at this head.
| BodyState::Cached(bytes) => { | ||
| if let Err(error) = | ||
| prepare_protected_body(self.input_guard.as_deref(), Some(&bytes)) | ||
| { | ||
| *state = BodyState::Poisoned(StoredError::capture(&error)); | ||
| return Err(error); | ||
| } |
There was a problem hiding this comment.
😃 This is the right shape for the cached re-entry fix. It reuses prepare_protected_body, so a restored cache gets the same check() (deadline, declared vs fallback max) and one-time observe as the initial drain. Once complete is set, repeated reads and the later discard skip accounting, so transformed output isn't charged as raw input. With these lines removed, three of the four restored_cache_* tests fail (fixed outcome, read-then-discard, transform). restored_cache_discard_checks_fallback_limits still passes, because discard goes through take_body and its own prepare_protected_body call. So the read path is pinned.
| // Keep reading an early 413 even if the peer stops accepting the upload. | ||
| let (sent, reading) = timeout(Duration::from_secs(5), async { | ||
| tokio::join!( | ||
| async { | ||
| writer.write_all(request_head.as_bytes()).await?; | ||
| writer.write_all(body.as_bytes()).await | ||
| }, |
There was a problem hiding this comment.
😃 Reading concurrently with the upload, and still requiring a complete, Content-Length-framed 413 before a reset is accepted, fixes the earlier race without weakening the assertion. It passed 30/30 isolated runs on macOS at this head, compared with 18/30 failures at d6f74308.
| let cap = 9 * 1024 * 1024; | ||
| let mut launch = command("bare", &roots, addr); | ||
| launch.env("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES", cap.to_string()); | ||
| let mut server = Server::spawn(launch, addr); | ||
| server.ready(); | ||
| assert_upload_status(&upload(&server, "/json", None, exact_json(cap), true), 200); | ||
| assert_upload_status( | ||
| &upload(&server, "/json", None, exact_json(cap + 1), false), | ||
| 413, |
There was a problem hiding this comment.
🌱 This 9 MiB + 1 case is the one path where the early 413 is above LINGERING_CLOSE_MAX_BYTES (8 MiB, header_deadline.rs:38), so the server closes without the bounded drain. The test still requires a complete 413 head, so receipt rests on timing. It passed in hosted CI and locally for me. If it ever flakes, the fix is to derive the linger bound from the selected JSON ceiling rather than to loosen this assertion. Not blocking.
dhruv8sh
left a comment
There was a problem hiding this comment.
PR Review
Summary
This PR adds a configurable Axum JSON buffering limit (JsonBodyLimit). It defaults to 2 MiB and can be set with EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES or the with_json_body_limit_bytes builders. The limit is attached to the ingress Body as a private policy that survives RequestContext reconstruction. JSON helpers always respect it, and generic buffered reads respect it when the original ingress had a JSON Content-Type. The design is careful and tests cover it at the unit, service and subprocess level. I found nothing blocking. The notes below are about API surface and caller expectations.
😃 Praise
- The policy keeps its cache provenance (
IngressBuffer::Cached/Initial) throughinto_transfer/from_transfer, so header and extension edits can't drop the ceiling. The tests also confirm that cached allocations are reused (as_ptrchecks). - Strict config parsing: only ASCII digits are accepted, the value must be non-zero and no larger than
isize::MAX, a non-Unicode value fails at startup before app hooks run, and the error never echoes the raw value. - The wire tests cover Content-Length and chunked framing exactly at the limit and one byte over, in bare, dev and embedding modes.
Findings
Blocking
None.
Non-blocking
- 🤔 Explicit caps are silently clamped:
json_within(n)andbody_bytes(n)on JSON ingress now return the smaller ofnand the adapter ceiling (crates/edgezero-core/src/context.rs:367). The CHANGELOG mentions this, but a handler that asks for 16 MiB gets a 413 at 2 MiB with nothing at the call site to explain it. - 🤔
Body::with_buffered_json_policyis public: it is#[doc(hidden)]but stillpubinedgezero_core(crates/edgezero-core/src/body.rs:363), so it becomes part of the semver surface. - 📝 The non-JSON bypass is intentional: generic reads of non-JSON ingress are not capped, and only the first
Content-Typevalue is used for classification. JSON helpers always apply the ceiling whatever the classification, so a misleadingContent-Typecannot get around the limit forJson/ValidatedJson.
📌 Out of Scope
- Other adapters (Fastly, Cloudflare, Spin) still use the 8 MiB
DEFAULT_INBOUND_JSON_BYTES. Moving to one portable default across providers could be tracked separately.
| requested_max: usize, | ||
| json: bool, | ||
| ) -> Result<bytes::Bytes, EdgeError> { | ||
| let max = self.body_policy.map_or(requested_max, |policy| { |
There was a problem hiding this comment.
🤔 Explicit caps are silently clamped: json_within(max) (and body_bytes(max) on JSON ingress) now uses min(max, ceiling). A handler that calls ctx.json_within(16 * 1024 * 1024) on Axum gets a 413 at 2 MiB, and nothing at the call site explains why. This is in the CHANGELOG, but consider stating it directly in the json_within/body_bytes rustdoc, e.g. "on Axum, values above EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES are clamped". Or log once at debug level when a clamp actually lowers a caller cap, so operators can diagnose unexpected 413s.
| #[doc(hidden)] | ||
| #[must_use] | ||
| #[inline] | ||
| pub fn with_buffered_json_policy( |
There was a problem hiding this comment.
🤔 Hidden but public API: with_buffered_json_policy is #[doc(hidden)] pub, so any downstream crate can call it, and changing its signature later is a semver break. Only adapter crates need it. If cross-crate visibility is required, a sealed or clearly unstable entry point (e.g. a __private module or an adapter-only trait) would make that intent explicit. 'First policy wins' means it can't loosen an existing policy, which limits the risk.
| Some(origin) | ||
| } | ||
|
|
||
| fn has_json_content_type(headers: &HeaderMap) -> bool { |
There was a problem hiding this comment.
📝 Classification only looks at the first Content-Type value, so a request with text/plain followed by application/json is treated as non-JSON for generic reads. That's fine because Json/json_within pass json = true and always apply the ceiling. A short comment saying the generic-read exemption is intentionally lenient would stop future readers from 'fixing' it.
Summary
JsonandValidatedJsondefault to 2 MiB (2,097,152 bytes). JSON helpers apply the ceiling regardless of Content-Type; generic buffered reads clamp only on JSON-classified ingress.Body/BodyPayloadsource migration is needed.Compatibility
Axum routes that buffer more than 2 MiB of JSON need an explicit host override. Set
EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTESfor standalone hosting, or usewith_json_body_limit_bytesonAxumRunOptionsorAxumDevServer. A larger extractor cap alone cannot raise the host ceiling. Invalid supplied settings fail before standalone app configuration. Malformed JSON within the limit still returns 400.Review follow-up and verification
64447b46 restores cached input accounting, keeps the original buffered body on a failed stream conversion, corrects valid media-type classification, and adds managed source failure/cancellation, routed reconstruction above 8 MiB, and configured router-only wire checks.
Local Linux verification against merge base
b67e78b9: workspace tests passed on retry (2,834 passed, 2 ignored), core and all-feature Axum suites passed, and the router-only wire test passed 30/30. Strict Clippy, formatting, the isolated harness, feature and WASM checks, and docs checks passed. Details and the first CLI test failure are recorded in the verification plan. macOS and provider deployments were not requalified.Merge dependency
The live #406 branch has advanced to
48097ab1. A read-only merge check found conflicts in Axum startup/service files, hosting fixtures/tests, and the Axum guide. This change has not been integrated with that revision. Reconcile #406 and rerun affected checks before merge; the accepted #275/#406 audit remains open.Tracks #393, part of #391.