Skip to content

httputil: separate HTTPHeaders decoding from validation - #3922

Open
anishpentyala wants to merge 16 commits into
tornadoweb:masterfrom
anishpentyala:header-decoding-validation
Open

anishpentyala wants to merge 16 commits into
tornadoweb:masterfrom
anishpentyala:header-decoding-validation

Conversation

@anishpentyala

@anishpentyala anishpentyala commented Nov 23, 2026 •

Copy link
Copy Markdown

Fixes #3900.

Reworked after review and merged current master (73823eda) into the existing branch without rewriting history.

  • HTTPHeaders.with_parse_mode(...) accepts HTTPHeaderParseMode.HTTP or HTTPHeaderParseMode.MULTIPART and creates an empty object with a persistent validation mode. HTTPHeaders.parse(text, parse_mode=...) uses that factory.
  • The mode applies to parsing, additions, item assignment and mapping updates, and survives copies. Dict-style constructor keywords remain header names.
  • Removed _chars_are_bytes entirely. Parsing still takes str; decoding stays with callers. Multipart keeps its bounded UTF-8 header decoding. HTTP/1 and curl decoding are unchanged.
  • Preserved current master's ValueError for invalid constructed headers and HTTPInputError for malformed parsed headers.

Tests explicitly preserve all non-ASCII Latin-1 values (0x80 through 0xFF) in both modes through parsing and mutations. Tests also cover controls and token names, copy/cache behavior, constructor compatibility, caller decoding and subclass factories. API snapshot and mypy client are updated.

Local Linux validation:

  • Python 3.13: 286 focused HTTP/header/curl/API tests passed, three existing skips. The latest full optional-dependency run completed 1,727 tests with the known request-target property-test error and 15 skips noted below.
  • Python 3.11 and 3.15: 202 focused header/HTTP1/server tests passed on each. Optimized Python 3.13: the same 202 passed.
  • Before the enum-only follow-up, 20,000 seeded text-parsing comparisons and 4,000 direct-add comparisons matched fresh master with the old internal flag mapped to the new mode.
  • All 17 project benchmark scenarios passed the comparison budgets locally. No speedup claim.
  • Pinned Black, flake8, strict Sphinx, API snapshot and mypy client checks passed. Full-project mypy reported 11 optional-module diagnostics, identical to a clean checkout of 73823eda in this environment.

Environment-specific caveat: a separate property-test run generated request target # and failed; a clean 73823eda full run in the same environment also generated that failing example. This was not reproduced on a separate review environment. This patch does not change request-line parsing.

Windows and macOS runtime testing has not been run locally. Hosted checks on the final updated head are being verified.

@bdarnell bdarnell left a comment

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.

There are some merge conflicts (sorry about the timing)

We should remove _chars_are_bytes; this was never meant for public use.

Comment thread tornado/httputil.py Outdated
name: str,
value: str,
*,
strict_http: bool | None = None,

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.

strict_http feels like it might grow beyond a bool: it's really a choice between parse_mode=PARSE_HTTP_HEADERS and parse_mode=PARSE_MULTIPART_HEADERS, and there could be more modes in the future.

Really this argument is properly scoped to the HTTPHeaders object itself, rather than the name/value pair being added. Could we add this to the constructor instead of this method? It may be tricky since the dict constructor is very broad. But we could consider a static factory method instead of adding more special cases to the constructor (we don't generally use the full generality of the dict constructor internally, although it is public for third-party use)

Comment thread tornado/httputil.py Outdated
instead of 7.0 as previously documented.
"""
if isinstance(line, bytes):
line = line.decode(encoding)

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.

If the encoding argument is just to do a .decode(encoding) at the entry point to the method, maybe it shouldn't be there and we should just require str input and the caller can decode.

@anishpentyala

Copy link
Copy Markdown
Author

Thanks for the review. I'll rework this against current master: remove _chars_are_bytes, move the parsing mode to the HTTPHeaders object without taking over dict-style constructor keywords, and keep parsing inputs as str with decoding at the caller. I'll also preserve the new distinction between ValueError for constructed headers and HTTPInputError for parsed input, then rerun the tests and benchmark comparison before updating the branch.

Use a factory without reserving dict constructor keywords. Keep caller-side decoding and current master error semantics; remove the internal compatibility flag.
Replace encoding/alias tests with str input, caller decoding and persistent-mode coverage.
Record factory and parse mode keyword, remove private flag and experimental encoding arguments.
Exercise factory, parsed modes, mutations and unchanged dict constructor keywords.
Restore the exact generated snapshot bytes after web editor normalization.

with self.subTest(mode=mode, method=method):
if mode == "multipart":
mutate("名")

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.

I think we also need to test that non-ascii characters from latin1 are still allowed (in both http and multipart modes)

Comment thread tornado/httputil.py Outdated
) -> None:
@classmethod
def with_parse_mode(
cls, parse_mode: typing.Literal["http", "multipart"]

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.

Let's make an enum for these, so we don't have to have the list of possible values repeated in type declarations in lots of places.

@anishpentyala

Copy link
Copy Markdown
Author

Thanks for the review. Keeping decoding separate from validation while preserving valid HTTP byte values is what interests me in this cleanup.

Updated the branch with HTTPHeaderParseMode.HTTP and .MULTIPART, used by the factory, parse method and multipart caller. The added regression checks every non-ASCII Latin-1 character (0x80 through 0xFF) in both modes, through parsing and the mutation methods, including characters at value boundaries.

The focused header/HTTP/curl/API checks pass (286 tests, three existing skips), along with Black, flake8, the type client, strict docs and all 17 benchmark budgets. The full local run still hits the previously noted request-target # property-test error, also reproduced on clean master; the full mypy diagnostics match the same baseline. Hosted checks on the final head are being verified.

@bdarnell bdarnell left a comment

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.

I'm not sure "separating decoding from validation" is a good description of what's happening here. Really we're just cleaning up the same behavior we've had, replacing the hacky _chars_are_bytes flag with something that better describes the differences.

# Keep the entire Latin-1 non-ASCII range so neither mode can silently
# become ASCII-only or apply Unicode control-category filtering.
for mode in HTTPHeaderParseMode:
for codepoint in range(0x80, 0x100):

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.

Testing every code point is excessive. We just need one latin1 char to represent the category. I was expecting you to add this to test_object_parse_modes_validate_all_mutations just so we don't have to repeat the list of mutations.

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.

httputil: HTTPHeaders cleanup _chars_are_bytes

2 participants