Repository navigation
feat(axum): add safe diagnostics and trusted proxy metadata - #409
ChristianPavilonis wants to merge 26 commits into
Conversation
66a05e2 to
9fa1666
Compare
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. examples/app-demo/Cargo.lock is merged by package entry. This PR's getrandom 0.4.2 and wasip3 0.4.0 still need wasip2 1.0.4 and wit-bindgen 0.51.0/0.57.1, so those entries stay beside fastly-sys 0.13.3's wasip2 2.0.1 and wit-bindgen 0.62.0/0.63.0. The result equals a targeted `cargo update -p fastly --precise 0.13.3` of this PR's lock.
|
For the identity integration branch (#495), I pushed
|
These tests reused the address they reserved before spawning the host. After a respawn on a fresh port that address belongs to whichever listener took it, so requests through raw_request, LocalProxy and the family checks now use server.addr().
|
For the identity integration branch (#495), I pushed
|
Keep failed trusted chains from substituting the socket peer for the client and use safe managed extractor errors without changing their status. Preserve typed stream failures, clock and cancellation semantics, and verify the native host and proxy fixtures.
|
Review follow-up:
Local Linux verification passed: 2,904 workspace tests, 33 hosting tests, 675 harness tests, strict Clippy, formatting, workspace feature compilation, Spin WASM, the Axum demo build, and docs format, lint, and build. macOS and deployed ingress were not run. Stack dependency: #407 has since advanced to |
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.
aram356
left a comment
There was a problem hiding this comment.
PR Review
Summary
Found while reviewing the rc/identity integration branch (#495) and traced to this PR. Each finding was re-checked at this head (3f6d0da6); line numbers refer to it.
One non-blocking portability finding.
Findings
Non-blocking
- 🤔
ForwardedHostis checked only on managed Axum. Seeextractor.rs:247.
CI Status
- GitHub checks at
3f6d0da6: 29 of 29 pass.
| impl FromRequest for ForwardedHost { | ||
| #[inline] | ||
| async fn from_request(ctx: &RequestContext) -> Result<Self, EdgeError> { | ||
| if let Some(checked) = ctx.extensions().get::<CheckedEffectiveHost>() { |
There was a problem hiding this comment.
🤔 ForwardedHost is checked only on managed Axum; elsewhere it still returns the raw client X-Forwarded-Host
Only the Axum adapter inserts CheckedEffectiveHost. On Fastly, Cloudflare and Spin this falls through to the legacy branch (:250-257) and returns whatever X-Forwarded-Host the client sent. A portable app that uses ForwardedHost for redirects, cache keys or tenant routing gets a trust-checked value on Axum and a client-controlled one on the other three. Document the split on the extractor and in each adapter guide, or have the other adapters insert CheckedEffectiveHost from their own trusted host source.
There was a problem hiding this comment.
Addressed in 381eb66 with docs. The extractor doc comment now says only the managed Axum host checks the value, through CheckedEffectiveHost. On Fastly, Cloudflare, Spin and the low-level Axum converter it reads X-Forwarded-Host, then Host, which the client controls, so it must not drive redirects, cache keys or tenant routing unless a proxy you control sets or strips the header. The Fastly, Cloudflare and Spin guides have the same note. docs/guide/handlers.md (around line 205) still recommends ForwardedHost behind a proxy without this caveat; I left that page alone.
prk-Jr
left a comment
There was a problem hiding this comment.
PR Review (follow-up)
Summary
Re-reviewed head 3f6d0da6 against stack base a3ad0428. The fix commit d37a57b8 addresses every item from my previous review, and I checked each one in the code rather than relying on the replies. One trust-boundary problem remains in the same area as the original trust-walk finding. Identity no longer collapses to the proxy, but a visitor who controls the leftmost part of the chain can still make EdgeZero discard the trusted proxy's host and scheme. One earlier doc question is also only half closed. I'm requesting changes for those two items.
😃 Praise
- Failing closed on a malformed or unresolved trusted chain (
effective_client() == None,Unavailableprovenance,direct_peer()kept separately) is the right shape. The CHANGELOG entry makes the behavior change visible to upgraders. - The
PendingValidationdrop guard and the lazy record construction inRequestGuard::emitare small, focused fixes for the cancellation and allocation concerns. - The macOS proxy fixtures now skip with an actionable
ifconfig lo0 aliasmessage instead of failing with a misleadingresponse head, and relay errors are no longer swallowed.
Prior findings status (my review at 31f46bde)
- ✅ Trust walk collapses the client to the proxy's address (
trusted_proxy.rs:413-438):MalformedandUnresolvedChainnow cleareffective_clientand setclient_source = Unavailable. Covered bydirect_fallback/assert_client_unavailableand the service matrix atservice.rs:3223-3240. A follow-on consequence for host/scheme is raised below as a new finding. - ✅ Duplicate
Hostbecomes the checked direct host (trusted_proxy.rs:361-369): only a singletonHost(or a URI authority) yields a direct authority;duplicate_host_is_not_a_checked_direct_authoritycovers it. - ✅ Post-commit body-source failure category dropped (
diagnostics.rs:563-565):NativeRequestRecord::source_failureis populated from the report and printed assource_failure=. The precommit zero-length path still retains the category throughattempt.record_source_error(response.rs:672-675), and the wire test asserts the category. - ✅ Managed path/query/form/
Validated*errors echo input (context.rs:808-814, 997-1001;extractor.rs): gated onFrameworkErrorDetail::CategoryOnly, which only the managed Axum service passes (service.rs:270-274). The dispatch tests cover both default and custom renderers in both modes. - 🔧 Unmanaged JSON redaction contradicts the guide: partially fixed.
axum-diagnostics.mdnow says the low-level converter also uses fixed JSON text, andlow_level_converter_keeps_native_fixed_json_parse_textpins it.docs/guide/adapters/axum.md:202-205still says "Legacy/unmanaged JSON errors ... retain their existing behavior". See the inline comment. - ✅ Proxy/TLS hosting tests fail on macOS (
production_hosting.rs:620-643,native_proxy.rs): the tests probe their source addresses and skip only on macOSAddrNotAvailable, panicking anywhere else. Relay errors now propagate through the workerJoinHandle<io::Result<()>>. I reran the axum suite locally on macOS without aliases; see CI Status. - ✅ (non-blocking) Guide omits the received-head preparer: the flowchart now has step
P, and the text says the preparer sees unchecked headers (axum-diagnostics.md:89-104).
Findings
Blocking
- 🔧 A visitor can still make EdgeZero discard the trusted proxy's host and scheme (
trusted_proxy.rs:413,:708). See the inline comment. - 🔧
adapters/axum.mdstill contradicts the low-level converter's JSON redaction (docs/guide/adapters/axum.md:202-205). This is the remainder of the earlier ❓, and the fix is a one-paragraph doc change. See the inline comment.
Non-blocking
- ⛏ Stale "falls back to the direct peer" sentence (
axum-diagnostics.md:222-223). See the inline comment. - 🤔 Malformed forwarding is logged at WARN and the visitor can trigger it. Combined with the finding above, any client can produce one WARN record per request by sending a junk
X-Forwarded-For. That is acceptable if WARN means "look at your proxy config", but consider INFO when the malformed slot lies beyond the trusted suffix, once the parser can tell the difference. - 📝 aram356's later 🤔 on
ForwardedHostportability (extractor.rs:247) still applies. I'm not repeating it here.
CI Status
- Hosted checks at
3f6d0da6: 29/29 pass (Run Tests, Run Format, CodeQL, Deploy actions). - Local, Rust 1.98.1 on macOS:
cargo fmt --all -- --checkPASS;cargo clippy -p edgezero-adapter-axum -p edgezero-core --all-targets --all-features -- -D warningsPASS;cargo test -p edgezero-corePASS (1,224 passed);cargo test -p edgezero-adapter-axum --all-targets --all-featuresPASS (435 lib, 28 contract, 40 hosting). - On macOS without loopback aliases, the four proxy/TLS hosting cases now print their skip notice instead of failing. They were not exercised here; Linux CI runs them.
- Not rerun locally: the full workspace, feature check and WASM checks (hosted CI covers them).
| ), | ||
| None => return metadata, | ||
| }; | ||
| let Ok(parsed) = parse_result else { |
There was a problem hiding this comment.
🔧 A visitor can still make EdgeZero discard the trusted proxy's host and scheme
The identity collapse is fixed, but the whole-family check still covers the part of the chain the visitor wrote. Take the guide's own Cloudflare → LB topology. The visitor sends X-Forwarded-For: junk. Cloudflare and the LB append, and EdgeZero receives this from the trusted LB:
X-Forwarded-For: junk, 203.0.113.7, 198.51.100.10
X-Forwarded-Host: app.example.com
X-Forwarded-Proto: httpsparse_node("junk") fails at line 708, the whole family becomes Malformed, and we return here with effective_scheme() == Http and effective_host() set to the direct Host. The LB-verified X-Forwarded-Proto: https and X-Forwarded-Host are thrown away. A 65th slot, an empty member, a 16 KiB prefix, or (for appending Forwarded proxies) an earlier element with proto=ftp does the same. whole_family_validation_includes_unselected_prefix_and_by_nodes and xff_empty_members_invalidate_even_good_host_and_proto currently pin this behavior.
Why it matters: the visitor chooses whether the trusted proxy's assertions apply. An app that builds absolute URLs from the checked scheme, or redirects when effective_scheme() != Https, will send that visitor an http:// link or a redirect back to the same HTTPS URL. The guide places a shared cache (Cloudflare) in front, and X-Forwarded-For is not part of the cache key. One request can therefore cache a redirect loop or http:// links for everyone (cache-poisoning DoS). It is also inconsistent: an unknown or obfuscated hop (UnresolvedChain) keeps the final-proxy host/scheme, but a junk hop further left drops them.
Fix (either one):
- Preferred: validate only what the right-to-left walk consumes. Split the list into raw slots under the existing byte/slot bounds, then parse slots from the right and stop at the first untrusted or unknown node. A malformed slot to the left of that boundary is never interpreted. Host/proto (
X-Forwarded-Host/-Protosingletons, or the finalForwardedelement) are validated on their own. - Minimal: when the only defect is in the client-address chain, treat it like
UnresolvedChain. The client is unavailable, the final-proxy host/scheme are kept, andMalformedis reserved for defects in the fields the final proxy owns.
Either way, please update the two tests above, the spec's "Malformed whole-set fallback" row, and the guide sentence "a present-empty value or empty member invalidates the complete selected family, including otherwise-valid host/proto". Then add a case asserting that a junk prefix behind a trusted suffix keeps https and the forwarded host.
| load balancer is trusted, it stops at the Cloudflare address. If every represented address is | ||
| trusted, it falls back to the direct peer as unresolved. |
There was a problem hiding this comment.
⛏ This sentence describes the old behavior
After d37a57b8, a chain where every address is trusted gives UnresolvedChain with effective_client() == None and client_source() == Unavailable (trusted_proxy.rs:419-438). It no longer falls back to the direct peer. Read literally, this line tells operators that the LB address becomes the client, which is exactly what the fix removed.
| load balancer is trusted, it stops at the Cloudflare address. If every represented address is | |
| trusted, it falls back to the direct peer as unresolved. | |
| load balancer is trusted, it stops at the Cloudflare address. If every represented address is | |
| trusted, the chain is unresolved and the effective client is unavailable; `direct_peer()` still | |
| reports the load balancer. |
| Native-managed JSON deserialization failures return HTTP 400 with the fixed text | ||
| `invalid JSON payload`. Custom renderers receive that same fixed error, not serde detail. | ||
| Legacy/unmanaged JSON errors and application-authored `EdgeError` messages retain their | ||
| existing behavior. See [privacy limits](/guide/axum-diagnostics#timing-failures-and-privacy-limits). |
There was a problem hiding this comment.
🔧 Still contradicts the low-level converter behavior (prior ❓ on unmanaged JSON detail, only partly resolved)
axum-diagnostics.md was corrected to say the low-level into_core_request converter attaches the native buffering policy and therefore also returns invalid JSON payload. low_level_converter_keeps_native_fixed_json_parse_text pins that. This paragraph still says unmanaged JSON errors keep their existing behavior, and that converter is the unmanaged path. Please align it:
| Native-managed JSON deserialization failures return HTTP 400 with the fixed text | |
| `invalid JSON payload`. Custom renderers receive that same fixed error, not serde detail. | |
| Legacy/unmanaged JSON errors and application-authored `EdgeError` messages retain their | |
| existing behavior. See [privacy limits](/guide/axum-diagnostics#timing-failures-and-privacy-limits). | |
| Axum JSON deserialization failures on bodies carrying the native buffering policy return HTTP 400 | |
| with the fixed text `invalid JSON payload`. This includes the managed host and the low-level | |
| `into_core_request` converter. Custom renderers receive that same fixed error, not serde detail. | |
| Bodies without that policy, and application-authored `EdgeError` messages, retain their | |
| existing behavior. See [privacy limits](/guide/axum-diagnostics#timing-failures-and-privacy-limits). |
| let direct_authority = if let Some(authority) = parts.uri.authority() { | ||
| parse_authority(authority.as_str().as_bytes()).ok() | ||
| } else { | ||
| let mut hosts = parts.headers.get_all(HOST).iter(); |
There was a problem hiding this comment.
😃 Nice, tight fix. The singleton-Host check now matches inbound_origin, URI authority still wins, and the test also covers a forwarded host being accepted while the direct authority is unavailable.
|
|
||
| // Only this preparation step can suspend before selecting a response. If it is | ||
| // dropped, settle the begun attempt without claiming a status or starting a fallback. | ||
| struct PendingValidation<'attempt> { |
There was a problem hiding this comment.
😃 Good call to settle the begun attempt as RequestCancelled when this future is dropped, instead of letting the Initial-state drop report ConversionError. cancelled_zero_length_validation_records_no_selected_status proves it end to end: there is no invented status, one record, and the source drops.
Fastly, Cloudflare, Spin and the low-level Axum converter supply no checked host, so the extractor returns the client's raw X-Forwarded-Host there.
Current review readiness — 2026-11-10
Ready for review at the publication head below. The required workspace and test aggregate have now passed in run42916832735; all 29 latest checks pass. Reviewers:
aram356,prk-Jr,dhruv8sh.Review transitions are independent of TS work and the combined integration audit; #462 remains draft. This current status supersedes historical draft-only prerequisites below without claiming unexecuted deployment/manual acceptance complete. All three reviewers are requested. Stack465 is the current grouping; #453 is excluded.
Current review-stack checkpoint
Publication head:
5bbff2bf6d6d853b470f76e7293b7ecfa55476f5. This cleanup preserves the existing feature unit and PR identity. The additional change is the completed generated-native build correction: image-only code now follows the scaffold's existing Fastly-example selection, with no request-policy change. Its focused generator/native proof is retained; fresh per-branch hosted checks are not assumed green.Review order: #275 → #406 → #407 → #409 → #414 → #422 → #439 → #454. Draft integration checkpoint: #462. New SDK/group/codec/phase development and unrelated TS work are not prerequisites or additions to this PR. Earlier notes below retain their original tested revisions and limits; they are not a whole-tree pass for this new head.
Earlier implementation and proof notes
RC refresh checkpoint, 2026-11-10
Current head:
3b52b804e5570564cc95cdaaf4b9efc6307875ae.Checked forwarding trusts the actual socket peer, validates the selected family and preserves original normalized-head accounting before stripping assertions and entering application callbacks. Diagnostics retain the existing terminal owner/time and redact raw values. Independent source review found no unresolved correctness defect.
The CLI-only diagnostics gate is fixed, with 57 CLI-only tests passing. Native ingress trust is now under
edgezero_adapter_axum::trusted_proxy, leaving the current outbound legacy-API guard unchanged. Parent namespace proof passes 370 Axum unit, 28 contract and 32 production-hosting tests plus axum-only strict Clippy. Nested demo resolution matches existing exact workspace getrandom0.4.2/ipnet2.12.0 requirements; no manifest pin was relaxed.This layer does not strip a future protected-CloudFront credential or prove a Geo reader identity.
Draft pending fresh hosted checks and the combined RC audit. Two unchanged native default-parallel deadline misses remain recorded and unclassified; serial passes and untouched-foundation parallel passes do not clear them. No timing bound was relaxed. No deployment, main merge, security-alert dismissal or review-thread resolution occurred. Historical design/review context follows.
Summary
Changes
edgezero-adapter-axumedgezero-core.2/.3relays, verified test TLS with wrong-name control, 32 production-hosting cases, callback/panic/privacy/counter checks and defensive fallback testsThe approved JSON extension retains HTTP 400 and unmanaged serde detail. Custom renderers still own their response, but native framework JSON-deserialization errors now reach them as
invalid JSON payload. Application-authored EdgeErrors are not globally sanitized. Managed raw-forwarding-header removal is documented as a compatibility change; the low-level converter remains a trust-policy bypass.Dependency changes are four direct Axum edges to existing locked packages. Rustls and Tokio Rustls are dev-only. The published TLS private key is an explicitly public test asset, never a deployment credential.
Closes
Closes #397.
Stack and acceptance
Part of #391. This PR remains draft until the required integration and acceptance gates are satisfied.
Stacked above #407 using
gh stack, at base3308041b910b648af746c15e809ee86b96adc2e9. The user authorized implementation on this open stack. That exception does not satisfy accepted #275/#393 integration or authorize bypassing #394/#395 upload experiments. Accepted-stack, final-image and deployed-ingress acceptance remain deferred.Test plan
Local checks passed for implementation commit
66a05e2:cargo test --workspace --all-targets— 1,938 passed, one existing ignored generated-workspace compile smokecargo clippy --workspace --all-targets --all-features -- -D warningscargo fmt --all -- --checkandgit diff --checkcargo check --workspace --all-targets --features "fastly cloudflare spin"wasm32-wasip1, Cloudflarewasm32-unknown-unknown, Spinwasm32-wasip2cargo test -p edgezero-adapter-axum --all-targets --all-features— 255 library, 13 contract and 32 hosting casescargo test -p edgezero-core— 731 library tests plus integrations/doctests; 13 existing ignored doc examplesexamples/app-demoworkspacedocs/superpowers/plans/2026-10-06-axum-diagnostics-trusted-proxy.mdrecords commands, timings, historical failures, source fingerprints, all 22 specification rows and proof boundaries. Final runtime-input manifest SHA256:ac40934b17bb6c521951f15090e2accf3059abcb4d386c6da74a69d95de8c9d7.Local wire tests directly prove owned proxy peers, consumer agreement, verified TLS, selected 200 plus failure after an observed head/prefix, hook/cardinality preservation and graceful/grace-forced work release. Missing-peer, exhaustive parser/identity bounds, precise injected timing and defensive fallback branches remain service/unit evidence. Environment-derived secret/config error privacy is tested; declared-store/backend and actual outbound-origin experiments are not claimed. Explicit diagnostic stop fixtures do not prove the convenience second-signal-plus-native-snapshot combination. The existing supported convenience second-signal test is retained.
Independent source reviews found and resolved lost Abort failure classification and formatting drift. A maintenance-only duplicated IPv6 bracket split remains unchanged; node and authority port grammars differ. Docs installation reports seven existing audit vulnerabilities, two moderate and five high; no docs package changes were made.
Checklist
CLAUDE.md; shared Cargo/global formatting centrally scheduledTS cutover follow-up, November 11
Native hosting invokes application head preparation after structural validation and before stripping forwarding fields. Protected Geo paths also capture facts before credential sanitation; invalid heads still skip application preparation.
Current head:
3708ffa418778b8ec3499daad132b1a3f9c7962f.Local combined-RC qualification at
36f8e9c9c2c93661aaa73f2ca956cec3bc9e4c92: workspace tests 2,947 passed / 6 ignored; all-feature Axum 568 passed, including 36 production-hosting, 6 AWS startup and 4 celld startup cases; core doctests 19 passed / 13 ignored; strict workspace Clippy, formatting, feature compilation and Spin WASM check passed under Rust 1.98.1. Narrow TS consumer proof under Node 24.20.0: all four real proxy tests and typed prepared config/secrets/router startup passed. This is not final TS-stack/image/deployment qualification. Fresh hosted checks are still required.Owned follow-up review checkpoint
b8c65667e643f77dfa1cd61b79cee5bd7a95f552. Source treea461a3dfd5ffa17698d452c034c935f59f365beais byte-identical to previous head31f46bde222ce3e942c1c801966ecc053a0305c9.