Skip to content

🐛 bug: accept tab OWS in X-Forwarded-For and share one OWS trim helper - #4735

Merged
ReneWerner87 merged 3 commits into
mainfrom
ccr-1dd2efb7-fs6nlk
Oct 3, 2026
Merged

ReneWerner87 merged 3 commits into
mainfrom
ccr-1dd2efb7-fs6nlk

Conversation

@gaby

@gaby gaby commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

Description

With EnableIPValidation on, an X-Forwarded-For chain 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 and c.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 in req.go only 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 through app.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 than utils.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-For trim 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:

  1. aece5e5 🐛 the fix: extractIPsFromHeader and both walks in extractIPFromHeader trim SP and HTAB. Regression tests for each path, plus a wire-level one.
  2. 4bf0485 🧹 trimOWS moves to internal/headerlist as a generic TrimOWS (string or []byte), and parseCacheControlDirectives uses it on sub-slices in place of five index loops. The package doc now names the split between TrimOWS (SP/HTAB only) and utils.TrimSpace, which the list iterators keep; All's doc called both "OWS".
  3. 3dd78c2 🧹 review follow-ups: three headerlist tests asserted aliasing with require.Equal on two *byte, which compares the bytes behind the pointers and so also passes for a copy. They now use require.Same (a copying TrimOWS fails 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/main versions. parseCacheControlDirectives on ~3M inputs gave identical output, including the nil-vs-empty value it hands its callback. The X-Forwarded-For parsers on ~1.3M headers, each in all four validation × trusted-proxy configurations, satisfied new(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, but getOffer trims tabs afterwards, so Accept* negotiate correctly with ,\t), and csrf Sec-Fetch-Site (SP-only, but fasthttp strips HTAB at both ends of a field value, so a tab cannot reach it).

  • Benchmarks: measured on this branch vs origin/main with interleaved builds and benchstat.
    • Benchmark_Ctx_IPs* and Benchmark_Ctx_IP_With_ProxyHeader_Chain, 15 interleaved runs: no significant difference on the four IPs() cases (p ≥ 0.33, geomean −0.4%); the IP() 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 three IPs() cases, which did not reproduce at 15 runs. A TrimOWS variant using a mask test instead of two comparisons was slower (+4% geomean), so the plain loop stays.
    • New Benchmark_parseCacheControlDirectives: 384 → 355 ns (−7%, p < 0.001), 0 allocs before and after.
    • TrimOWS is inlined at all six call sites.
  • Documentation Update: 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.
  • Changelog/What's New: n/a, bug fix.
  • Migration Guide: n/a, no API change (see the behavior note above).
  • API Alignment with Express: n/a, no API change.
  • API Longevity: no new public API; TrimOWS lives in internal/.
  • Examples: n/a.

Type of change

The template has no entry for a bug fix; the fix itself counts as "Code consistency".

  • New feature (non-breaking change which adds functionality)
  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage. (n/a: no new functionality)
  • Conducted a self-review of the code and provided comments for complex or critical parts. A review pass found two minor items (a test that could not fail, a dead branch), both fixed in 3dd78c2.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features (ctx_test.go, internal/headerlist, middleware/cache).
  • Ensured that new and existing unit tests pass locally with the changes. make test (race detector on): 6532 tests, 5 environment skips. make lint: 0 issues. make format and make betteralign: no changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community. None added.
  • Aimed for optimal performance with minimal allocations in the new code. No allocations, inlined at every call site.
  • Provided benchmarks for the new code to analyze and improve upon: Benchmark_TrimOWS, Benchmark_parseCacheControlDirectives.

Note: make generate on main also rewrites one doc comment line in res_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: /generate re-runs the code generators on this branch

claude added 3 commits October 3, 2026 15:52
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
@gaby
gaby requested a review from a team as a code owner October 3, 2026 17:11
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-03T17:13:35.440361Z 3dd78c2 PR opened
🔒 Security Review ✅ Completed 2026-10-03T17:19:51.776522Z 3dd78c2 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (2)
.github/copilot-instructions.md — auto-discovered
AGENTS.md — auto-discovered

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d62ed3d5-5f14-48b1-9f94-bbd6288038d1
📥 Commits

Reviewing files that changed from the base of the PR and between 0923873 and 3dd78c2.

📒 Files selected for processing (7)
  • ctx_test.go
  • docs/api/ctx.md
  • internal/headerlist/headerlist.go
  • internal/headerlist/headerlist_test.go
  • middleware/cache/cache_test.go
  • middleware/cache/cachecontrol.go
  • req.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.


Walkthrough

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

Changes

Optional whitespace handling

Layer / File(s) Summary
SP/HTAB trimming helper
internal/headerlist/headerlist.go, internal/headerlist/headerlist_test.go
Added TrimOWS for strings and byte slices. It trims leading and trailing spaces and tabs, preserves other bytes, and returns a byte-slice alias. Tests and a benchmark cover the helper.
Cache-Control directive parsing
middleware/cache/cachecontrol.go, middleware/cache/cache_test.go
The parser uses TrimOWS and utils.CutByte to process directive keys and values. Tests cover tab trimming, quoted values, and vertical-tab preservation.
Forwarded-IP extraction
req.go, ctx_test.go, docs/api/ctx.md
Forwarded-IP extraction trims spaces and tabs around addresses before validation and trusted-proxy selection. Tests cover trusted-proxy chains and parsed requests. The IPs documentation describes the whitespace behavior.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 3dd78

The whitespace changes appear ready to merge after normal checks.

Security Architecture Review

Security architecture risk: ⚪ Minimal · up to 3dd78

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The affected security scope is forwarded-header identity interpretation in consuming applications and Cache-Control-driven shared-cache decisions. No downstream authorization consumer or deployment-specific exposure is established by the supplied evidence.

Trust Boundaries and Controls

  • observed — IP() consumes the configured proxy header only when IsProxyTrusted() succeeds. That check requires proxy trust to be enabled and the remote peer to match configured trust rules. Validation-enabled selection still validates candidates and scans past trusted proxy addresses. Tab normalization does not grant an untrusted peer authority over IP(); raw-header behavior when validation is disabled predates this change.

Resilience and Maintainability Implications

  • observed — The cache refactor preserves parsed policy inputs to revalidation, stale-serving, terminal-response, storage, and failure-cleanup paths. Inspection found no PR-induced change to transition ordering, eviction rollback, accounting cleanup, or stored-body cleanup.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the bug fix: accepting tab optional whitespace in X-Forwarded-For and sharing an OWS trim helper.
Description check ✅ Passed The description explains the problem, fix, behavior change, tests, benchmarks, documentation updates, and relevant issue. It also addresses the template sections and marks non-applicable items.
Linked Issues check ✅ Passed [#4732] extractIPsFromHeader and both extractIPFromHeader walks now use headerlist.TrimOWS, which trims only surrounding SP and HTAB. Tests cover tab-padded chains, IPs() with validation on an…
Out of Scope Changes check ✅ Passed The shared TrimOWS helper also replaces duplicate SP/HTAB trimming in the Cache-Control parser. Its tests and benchmark verify that reuse; the headerlist aliasing assertions verify the helper’s no…
Full details: Docstring Coverage

Explanation

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

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

A rabbit trims the tabs with care
Around each address in the air
The inner bytes stay as they were
Cache keys and values now concur
The carrot cache is neat and fair

Comment @coderabbitai help to get the list of available commands.

@ReneWerner87 ReneWerner87 added this to the v3 milestone Oct 3, 2026
@ReneWerner87 ReneWerner87 added this to v3 Oct 3, 2026
@codecov

codecov Bot commented Oct 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.01%. Comparing base (28f2aa7) to head (3dd78c2).
⚠️ Report is 2 commits behind head on main.

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     
Flag Coverage Δ
unittests 95.01% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ReneWerner87
ReneWerner87 merged commit 78b8ee9 into main Oct 3, 2026
34 checks passed
@ReneWerner87
ReneWerner87 deleted the ccr-1dd2efb7-fs6nlk branch October 3, 2026 18:26
@github-project-automation github-project-automation Bot moved this to Done in v3 Oct 3, 2026
@ReneWerner87 ReneWerner87 modified the milestones: v3, v3.6.0 Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: X-Forwarded-For IP validation rejects tab OWS

3 participants