Trim whitespace in forwarded host parsing#7291
Conversation
Ap-0007
left a comment
There was a problem hiding this comment.
Looks solid! Changing trimRight() to trim() in the comma-separated case ensures we handle leading whitespace from poorly formatted headers, and falling back to trim() for the single value case provides excellent robustness. The added regression tests look very clear as well. Great work!
notadev99
left a comment
There was a problem hiding this comment.
Agree the trimRight() -> trim() swap is correct; the old code kept leading whitespace on the comma case. Two things on top of the existing review:
The new single-value branch isn't tested. The added test uses a header with a comma (' example.com , malicious.example.com'), so it exercises the indexOf(',') !== -1 path. The new else { val = val.trim() } single-value case never runs — worth a second case with a plain X-Forwarded-Host: ' example.com ' (no comma) so both new paths are covered.
Consistency with the direct Host header. This trims only the forwarded path. If a raw Host header arrives with surrounding whitespace, does it get the same treatment, or is it guaranteed clean upstream? If the goal is consistent host parsing, worth confirming both paths agree.
Could also assert that the second value (malicious.example.com) is dropped, to make the "only the first value, fully trimmed" contract explicit in the test.
Summary
Fix
req.hostto consistently trim whitespace from X-Forwarded-Host when trust proxy is enabled.Changes
lib/request.js: trimX-Forwarded-Hostin both comma-separated and single-value cases.test/req.host.js: add regression test for spaced host header.Validation
npm test -- test/req.host.jsnpx mocha --require test/support/env test/req.host.js