Skip to content

Add configurable Axum buffered JSON body limits - #407

Open
ChristianPavilonis wants to merge 23 commits into
issue-392-396-production-hosting-specfrom
issue-393-buffered-body-limit-spec
Open

ChristianPavilonis wants to merge 23 commits into
issue-392-396-production-hosting-specfrom
issue-393-buffered-body-limit-spec

Conversation

@ChristianPavilonis

@ChristianPavilonis ChristianPavilonis commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add a configurable Axum ceiling for framework-managed JSON buffering. Ordinary Json and ValidatedJson default 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.
  • Keep admission before lazy conversion and reuse feat: implement portable outbound HTTP and request lifecycle contracts #275's bounded collector and typed HTTP 413. Taken streams, forwarding, manual collection, and other providers' defaults stay unchanged.
  • Preserve the ceiling, ingress classification, and cache provenance when reconstructing the original body. A reconstructed cache is still subject to the new dispatch's input guard. No Body / BodyPayload source 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_BYTES for standalone hosting, or use with_json_body_limit_bytes on AxumRunOptions or AxumDevServer. 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.

@dhruv8sh dhruv8sh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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/ValidatedJson are 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 :4 and :34, at docs/superpowers/specs/2026-10-06-axum-buffered-json-body-limit-design.md:4, and at docs/superpowers/specs/2026-08-22-inbound-body-design.md:28.

Non-blocking

  • 🤔 Carrying the policy inside public Body forces a breaking API change (crates/edgezero-core/src/body.rs:42, inline)
  • 🤔 Body::with_buffered_json_policy is 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_environment duplicates the key check in from_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 declared Content-Length is 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 :21 and the design spec :12). The plan also cites /tmp/393-final-*.log files as evidence at :362-373; suggest replacing those with commands plus results, or a CI run link.
  • 📝 Body grows by one word, which is why #[expect(clippy::large_enum_variant)] was added in crates/edgezero-core/src/outbound.rs and crates/edgezero-adapter-fastly/src/outbound.rs. No action needed, and it goes away if the Body refactor suggestion is adopted.

📌 Out of Scope

  • docs/superpowers/specs/2026-10-05-axum-production-startup-lifecycle-design.md:10 contains 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-macros trybuild 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.

Comment thread crates/edgezero-core/src/body.rs Resolved
Comment thread crates/edgezero-core/src/body.rs Resolved
Comment thread crates/edgezero-core/src/context.rs Resolved
@ChristianPavilonis
ChristianPavilonis force-pushed the issue-393-buffered-body-limit-spec branch from 3308041 to e867c12 Compare November 10, 2026 19:40

@aram356 aram356 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.
    • Plan 2026-10-06-axum-buffered-json-body-limit.md has 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 3ab2209 with "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.
  • 🔧 CHANGELOG misses the real breaking changes, and the rustdoc is stale (CHANGELOG.md:7).

Non-blocking

  • 🤔 with_buffered_json_policy is 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 Body from 40 to 64 bytes (body.rs:27).
  • ⛏ Blanket arbitrary_source_item_ordering expects (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-Length exceeds the ceiling, the server answers and closes with the body unread, so ordinary clients (reqwest here) often get ECONNRESET instead 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_request has 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-Type header is classified (request.rs:65)
  • ♻️ Duplicate key check in the dev environment capture (dev_server.rs:917). It now shares config_path, but still matches the JSON path with its own literal instead of fixed_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

Comment thread crates/edgezero-core/src/context.rs Resolved
Comment thread CHANGELOG.md Resolved
Comment thread crates/edgezero-core/src/body.rs Resolved
Comment thread crates/edgezero-core/src/body.rs Resolved
Comment thread crates/edgezero-core/src/body.rs Resolved
aram356 added a commit that referenced this pull request Nov 16, 2026
# Conflicts:
#	crates/edgezero-core/src/app.rs
aram356 added a commit that referenced this pull request Nov 16, 2026
Brings #275 at b65e714 and the refreshed heads of #499, #460, #406,
#407, #409, #414, #422 and #439. Each PR merged the one below it, so
this merge has no conflicts. #409 resolved the one conflict on the way
up, in edgezero-core's app.rs imports, by keeping both.
aram356 added a commit that referenced this pull request Nov 17, 2026
Brings #275 at ea2549f and the refreshed heads of #499, #460, #406,
#407, #409, #414, #422 and #439, including #422's stock-celld store
service and its merge into #439. Each PR merged the one below it, with
no conflicts on the way up, so this merge has no conflicts.
@ChristianPavilonis
ChristianPavilonis removed this pull request from stack #501 November 17, 2026 17:14
aram356 and others added 2 commits November 25, 2026 11:46
Bring in main's Fastly SDK 0.13.3 upgrade (#529) with Viceroy 0.22.0
and the Fastly CLI 17.2.0 upgrade (#531), with PR #275's exact pins at
0.13.3 and url 2.5.9, its Viceroy readiness repair on 0.22.0 and its
typed Image Optimizer unavailability check for SDK 0.13.3.
aram356 added a commit that referenced this pull request Nov 25, 2026
Take PR #524's updated tip, which carries main's Fastly SDK 0.13.3
upgrade (#529) with Viceroy 0.22.0 and the Fastly CLI 17.2.0 upgrade
(#531), PR #275's drain of declared uploads before an early-response
HTTP/1 close, and the macOS test fixes from PRs #407 and #414. It
merges without conflicts.
aram356 added a commit that referenced this pull request Nov 25, 2026
Take PR #515's updated tip, which carries main's Fastly SDK 0.13.3
upgrade (#529) with Viceroy 0.22.0 and the Fastly CLI 17.2.0 upgrade
(#531), PR #275's drain of declared uploads before an early-response
HTTP/1 close, and the macOS test fixes from PRs #407 and #414. It
merges without conflicts.
aram356 added a commit that referenced this pull request Nov 25, 2026
Take PR #519's updated tip, which carries main's Fastly SDK 0.13.3
upgrade (#529) with Viceroy 0.22.0 and the Fastly CLI 17.2.0 upgrade
(#531), PR #275's drain of declared uploads before an early-response
HTTP/1 close, and the macOS test fixes from PRs #407 and #414. It
merges without conflicts.
aram356 added a commit that referenced this pull request Nov 25, 2026
Take PR #502's updated tip, which carries main's Fastly SDK 0.13.3
upgrade (#529) with Viceroy 0.22.0 and the Fastly CLI 17.2.0 upgrade
(#531), PR #275's drain of declared uploads before an early-response
HTTP/1 close, and the macOS test fixes from PRs #407 and #414. It
merges without conflicts.
Bring in PR #275's installation of the wasm32-unknown-unknown target
before the Viceroy 0.22.0 readiness repair builds, which the fastly
wasm tests and Portable record contracts (Fastly) jobs need.
@aram356

aram356 commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed eb501d61, 17a0edf8 and d21dcec2.

Bring in PR #275's atomic conditional KV insert in the Viceroy readiness
repair, and the production hosting tests' held port reservations and
spawn-token respawn from PR #406 up, with each later PR's tests reading
the live host's address.
The failed-startup half of
invalid_json_limits_fail_before_application_hooks_in_dev_and_production
now keeps its port reserved, as PR #519's 09b09d9 (prk-Jr) does, so
no other test's host can answer the "nothing answers" check.
@aram356

aram356 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed b0c7f9cf and fa329cad. b0c7f9cf merges #406's new head, which brings #275's atomic conditional KV insert in the Viceroy readiness repair and #406's held port reservations and spawn-token respawn in the production hosting tests; it had no conflicts. fa329cad keeps the port reserved in the failed-startup half of invalid_json_limits_fail_before_application_hooks_in_dev_and_production, as #519's 09b09d9e does, so no other test's host can answer its "nothing answers" check.

Bring in PR #275's batch cutoff test fix, which advances the test clock
when the request arms its own deadline instead of after dispatch.
@aram356

aram356 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed 9750b0e3, a merge of #406's new head that brings #275's 0e2a58ae, which fixes an intermittent failure of the batch cutoff test by advancing its clock when the request arms its deadline timer. It had no conflicts.

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.
@ChristianPavilonis

Copy link
Copy Markdown
Collaborator Author

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 48097ab1, while this patch was tested with merge base b67e78b9. A read-only merge check found conflicts in the Axum startup/service code, hosting fixtures/tests, and guide. Integration and affected reruns remain open, as does the accepted-stack audit in #393. No merge or rebase was performed.

Carry the selected Axum JSON ceiling through shared service preparation while preserving the hosting lifecycle and both sets of subprocess cases.
ChristianPavilonis added a commit that referenced this pull request Nov 30, 2026
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 prk-Jr left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 Cached arm through the same prepare_protected_body the initial drain uses, so the deadline check, fallback max and one-time accounting cannot drift. The four restored_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 48097ab1 and that verification was against merge base b67e78b9. The head a3ad0428 merges 48097ab1 forward, the merge base is now 48097ab1, 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_BYTES is still DEFAULT_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 whatever JSON_BODY_LIMIT_BYTES selects. 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 mime dependency 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 matching json or a +json suffix would remove the new workspace dependency. This is optional, since mime is 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: PASS
    • cargo 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: PASS
    • router_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.

Comment on lines 404 to +410
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);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

😃 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.

Comment on lines +1966 to +1972
// 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
},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

😃 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.

Comment on lines +589 to +597
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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🌱 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 dhruv8sh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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) through into_transfer/from_transfer, so header and extension edits can't drop the ceiling. The tests also confirm that cached allocations are reused (as_ptr checks).
  • 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) and body_bytes(n) on JSON ingress now return the smaller of n and 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_policy is public: it is #[doc(hidden)] but still pub in edgezero_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-Type value is used for classification. JSON helpers always apply the ceiling whatever the classification, so a misleading Content-Type cannot get around the limit for Json/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| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤔 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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤔 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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

📝 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.

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.

Axum: enforce configurable buffered request-body limits

4 participants