Skip to content

fix(client): ignore trailing whitespace when parsing Content-Length - #6136

Open
zichen0116 wants to merge 1 commit into
nodejs:mainfrom
zichen0116:fix/content-length-trailing-whitespace
Open

zichen0116 wants to merge 1 commit into
nodejs:mainfrom
zichen0116:fix/content-length-trailing-whitespace

Conversation

@zichen0116

Copy link
Copy Markdown

Fixes #6135

A response whose Content-Length value carries trailing whitespace (valid
optional whitespace per RFC 9112 §5, e.g. Content-Length: 5 as sent
by servers that pad the field to a fixed width) fails with
UND_ERR_RES_CONTENT_LENGTH_MISMATCH, even though the body length matches.
This is a regression since #5124: before that change the value went through
parseInt(), which ignores trailing whitespace.

Root cause: in lib/dispatcher/client-h1.js, Parser.onHeaderValue accumulates
the Content-Length digit by digit, folding every byte into the value. A space
(0x20) contributes -16, so 5 followed by spaces becomes a large garbage
number and the body-length check at message completion fails.

Fix: skip SP (0x20) and HTAB (0x09) while accumulating the value. The Milo
parser path is unaffected: it reads Content-Length from its own parsed event,
not from this loop.

Verification:

  • Reproduced on main before the fix: a raw-socket server answering
    Content-Length: 5 with body hello failed for both fetch() and
    request() with UND_ERR_RES_CONTENT_LENGTH_MISMATCH; both pass after.
  • Added test/issue-6135.js: 4 tests covering a single trailing space and
    multiple trailing spaces, through both fetch() and Client.request()
    (raw node:net server, since node:http normalizes header values).
  • Existing test/content-length.js and test/fetch/content-length.js:
    27 passed, 0 failed. ESLint clean on both changed files.

@1AbdullahButt 1AbdullahButt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Checked this against lib/dispatcher/client-h1.js on main. The digit loop in onHeaderValue folds every byte, so a trailing 0x20 becomes (0x20 - 0x30) = -16 and corrupts the value, as described.

Skipping SP/HTAB anywhere in the value is only safe because llhttp has already validated the field. Its Content-Length states accept trailing OWS but raise "Invalid character in Content-Length" for anything after it (e.g. 5 0), and leading OWS never reaches the callback. That's a reasonable thing to rely on, but it's an implicit contract, so I'd suggest:

  1. A short comment next to the continue saying that llhttp rejects interior whitespace, so only trailing OWS can show up here.
  2. A negative test in test/issue-6135.js that pins that contract, e.g. Content-Length: 5 0 should still fail (llhttp parse error, not a silent 50). If a future llhttp upgrade or a lenient flag ever relaxes that, this test would catch the silent miscount.
  3. The code also skips HTAB, but the test table only has ' ' and ' '. Adding ['tab', '\t'] would cover the other branch.

The test setup itself looks right. A raw node:net server is needed because node:http would normalise the header, and the global dispatcher is restored in t.after.

Static review; I didn't run the suite here.

Reviewed with help from Claude Code.

Comment thread lib/dispatcher/client-h1.js Outdated
for (let i = 0; i < buf.length; i++) {
if (buf[i] === 0x20 || buf[i] === 0x09) {
continue
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This seems to ignore also whitespaces in the middle, no?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch — you're right, the first version skipped whitespace anywhere in the loop, so it would have folded 5 0 into 50. I checked what actually reaches the callback: llhttp strips leading OWS and rejects anything after the digits that isn't trailing whitespace (Invalid character in Content-Length), so 5 0 never gets folded — the request fails instead (surfaced as a content-length mismatch, since the parser aborts before the body is read). But relying on that implicitly was fragile, so I restructured it in the latest push: the loop now strips trailing OWS first and then folds digits only, so interior whitespace can't be skipped by construction. There's a comment documenting the llhttp contract, plus a negative test pinning that 5 0 is rejected for both fetch and request.

@codecov-commenter

codecov-commenter commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.66%. Comparing base (489bc9d) to head (b089ede).
⚠️ Report is 34 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6136      +/-   ##
==========================================
- Coverage   91.67%   91.66%   -0.01%     
==========================================
  Files         113      113              
  Lines       44041    44044       +3     
==========================================
+ Hits        40373    40375       +2     
- Misses       3668     3669       +1     

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zichen0116
zichen0116 force-pushed the fix/content-length-trailing-whitespace branch from b089ede to 12b2376 Compare November 8, 2026 13:02
@zichen0116

Copy link
Copy Markdown
Author

Thanks @1AbdullahButt — all three points are addressed in the latest push (rebased onto current main):

  1. Comment added next to the parsing loop documenting the llhttp contract.
  2. Negative test added: Content-Length: 5 0 is rejected for both fetch and request (it surfaces as UND_ERR_RES_CONTENT_LENGTH_MISMATCH — the parser aborts before the body is read, so it can never be silently folded into 50).
  3. On the tab case: I verified that a trailing tab never reaches the callback — llhttp rejects 5\t (and 5\t0) at parse time, so there is no passing acceptance test to add for it. The 0x09 handling stays as defensive OWS handling next to the space.

Also restructured per @mcollina's comment: the loop now strips trailing OWS first and folds digits only, so interior whitespace can't be skipped by construction. test/issue-6135.js 6/6, test/client.js 66 pass / 0 fail, eslint clean.

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.

Content-Length with trailing whitespace fails with UND_ERR_RES_CONTENT_LENGTH_MISMATCH (regression since #5124)

4 participants