Repository navigation
🐛 bug: accept tab OWS in X-Forwarded-For and share one OWS trim helper - #4735
Conversation
RFC 9110 Section 5.6.3 defines the optional whitespace around list members as SP or HTAB, but the X-Forwarded-For parsers only trimmed SP. fasthttp strips OWS at either end of a field value, not around the commas inside it, so a chain such as "203.0.113.50\t,\t10.0.0.1" kept its tabs. With EnableIPValidation every element then failed validation: IPs() returned an empty slice and IP() fell back to the proxy address. Without validation IPs() returned the elements with the tabs attached. extractIPsFromHeader and both walks in extractIPFromHeader now trim through one trimOWS helper. It strips SP and HTAB only, narrower than utils.TrimSpace on purpose: a tab inside an address, or CR/LF/VT/FF next to one, still fails validation. Fixes #4732 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0134pG8jksk1PPnMby7oaDn8
The X-Forwarded-For parsers in req.go and the Cache-Control parser in the cache middleware each trimmed RFC 9110 OWS (SP and HTAB) by hand: a local helper with three callers, and five index loops in parseCacheControlDirectives. Both now use headerlist.TrimOWS, generic over string and []byte so the byte-slice parser needs no conversion. TrimOWS stays narrower than utils.TrimSpace, which All and its siblings keep using. The package doc now names that split; All's doc called both OWS. parseCacheControlDirectives now works on sub-slices instead of indices. That drops two trims that could never fire (the key's leading side and the value's trailing side were already trimmed) and splits at '=' with utils.CutByte. Output is unchanged, including the nil value for a directive without '=': a differential fuzz run against the previous implementation found no difference across ~3M inputs. Its new benchmark runs ~10% faster with no allocations; the IP and cache middleware benchmarks are unchanged. Refs #4604 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0134pG8jksk1PPnMby7oaDn8
Three headerlist tests checked that a result aliases its input by passing two *byte to require.Equal. That falls through to reflect.DeepEqual, which compares the bytes behind the pointers, so a copying implementation passed as well: the zero-copy contract the tests name was never enforced. require.Same compares the addresses; a copying TrimOWS now fails Test_TrimOWS_AliasesInput. parseCacheControlDirectives skipped an element that trimmed to nothing, but none can: the skip loop leaves cc[start] as neither OWS nor a comma, the scan steps over it, and TrimOWS keeps it. A comment states the invariant in place of the branch. Fuzzing against the previous parser found no output difference. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0134pG8jksk1PPnMby7oaDn8
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 🧰 Additional context used📚 Code guidelines (2)No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (7)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. WalkthroughThe change adds an SP/HTAB trimming helper and uses it in Cache-Control parsing and forwarded-IP extraction. Tests cover trimming at list-item boundaries and preserving whitespace inside values. ChangesOptional whitespace handling
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Bug fix · Severity of issue fixed: Medium Merge Risk: ⚪ Minimal · up to The whitespace changes appear ready to merge after normal checks. Security Architecture ReviewSecurity architecture risk: ⚪ Minimal · up to Tab padding now behaves like space padding when forwarded IPs are parsed. Proxy trust checks and address validation remain enforced, and cache privacy and storage decisions retain their existing behavior. No material security risk introduced or worsened by this change was identified. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 45.45% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 6 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. A rabbit trims the tabs with care Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #4735 +/- ##
==========================================
+ Coverage 94.98% 95.01% +0.02%
==========================================
Files 141 141
Lines 17580 17559 -21
==========================================
- Hits 16698 16683 -15
+ Misses 554 551 -3
+ Partials 328 325 -3
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Description
With
EnableIPValidationon, anX-Forwarded-Forchain padded with tabs, such as\t203.0.113.50\t,\t10.0.0.1\t, was rejected element by element:c.IPs()returned an empty slice andc.IP()fell back to the proxy's address. RFC 9110 §5.6.3 defines the optional whitespace around list members as SP or HTAB, but the three trim sites inreq.goonly stripped spaces. fasthttp removes OWS at the two ends of a field value but keeps it around the commas inside one, so this is reachable from the wire and not only from a hand-built header (there is a wire-level test throughapp.Test). With validation off,IPs()returned the same elements with the tabs still attached.The fix trims SP and HTAB through one helper,
headerlist.TrimOWS, deliberately narrower thanutils.TrimSpace: a tab inside an address, or CR/LF/VT/FF next to one, still fails validation, as the issue asks. The cache middleware's Cache-Control parser carried five hand-written SP/HTAB trims of its own and now uses the same helper.Fixes #4732
Related to #4604 (cluster 8: the per-element
X-Forwarded-Fortrim existed three times). This PR does not complete that cluster.Behavior change: a tab now counts as whitespace exactly where a space already did. With validation on, tab-padded chains are accepted as space-padded ones always were. With validation off,
IPs()returns tab-padded entries trimmed instead of with the tabs attached;IP()without validation still returns the raw header, as documented. Input without tabs behaves byte for byte as before. A tab can do nothing a space could not already do, so this opens nothing to a client that could not already pad with spaces.Changes introduced
Three commits:
aece5e5🐛 the fix:extractIPsFromHeaderand both walks inextractIPFromHeadertrim SP and HTAB. Regression tests for each path, plus a wire-level one.4bf0485🧹trimOWSmoves tointernal/headerlistas a genericTrimOWS(string or[]byte), andparseCacheControlDirectivesuses it on sub-slices in place of five index loops. The package doc now names the split betweenTrimOWS(SP/HTAB only) andutils.TrimSpace, which the list iterators keep;All's doc called both "OWS".3dd78c2🧹 review follow-ups: threeheaderlisttests asserted aliasing withrequire.Equalon two*byte, which compares the bytes behind the pointers and so also passes for a copy. They now userequire.Same(a copyingTrimOWSfails it). One unreachable branch is also removed from the parser.Equivalence checks (throwaway harnesses, not part of this PR): both rewritten parsers were fuzzed against a verbatim copy of their
origin/mainversions.parseCacheControlDirectiveson ~3M inputs gave identical output, including the nil-vs-emptyvalueit hands its callback. TheX-Forwarded-Forparsers on ~1.3M headers, each in all four validation × trusted-proxy configurations, satisfiednew(x) == old(x with tabs turned into spaces): a tab behaves exactly like a space, and tab-free input is unchanged.Looked at and left alone, because they do not have this bug:
internal/mediatype(already treats SP and HTAB alike),forEachMediaRange(skips only SP on the left, butgetOffertrims tabs afterwards, soAccept*negotiate correctly with,\t), and csrfSec-Fetch-Site(SP-only, but fasthttp strips HTAB at both ends of a field value, so a tab cannot reach it).origin/mainwith interleaved builds andbenchstat.Benchmark_Ctx_IPs*andBenchmark_Ctx_IP_With_ProxyHeader_Chain, 15 interleaved runs: no significant difference on the fourIPs()cases (p ≥ 0.33, geomean −0.4%); theIP()chain case went 311 → 297 ns (−4.6%, p = 0.03). Allocations identical. Noise on the test machine is about ±4%: an earlier 10-run comparison showed +2–4% on threeIPs()cases, which did not reproduce at 15 runs. ATrimOWSvariant using a mask test instead of two comparisons was slower (+4% geomean), so the plain loop stays.Benchmark_parseCacheControlDirectives: 384 → 355 ns (−7%, p < 0.001), 0 allocs before and after.TrimOWSis inlined at all six call sites.docs/api/ctx.md(IPs) now says the spaces and tabs around each address are trimmed and that whitespace inside an address makes it invalid.TrimOWSlives ininternal/.Type of change
The template has no entry for a bug fix; the fix itself counts as "Code consistency".
Checklist
3dd78c2./docs/directory for Fiber's documentation.ctx_test.go,internal/headerlist,middleware/cache).make test(race detector on): 6532 tests, 5 environment skips.make lint: 0 issues.make formatandmake betteralign: no changes.Benchmark_TrimOWS,Benchmark_parseCacheControlDirectives.Note:
make generateonmainalso rewrites one doc comment line inres_interface_gen.go(Vary). That predates this branch and is left out of it.🤖 Generated with Claude Code
https://claude.ai/code/session_0134pG8jksk1PPnMby7oaDn8
Generated by Claude Code
🤖 Maintainers:
/generatere-runs the code generators on this branch