Skip to content

split_host_and_port: reject ports above 65535 with HTTPInputError#3658

Open
HrachShah wants to merge 1 commit into
tornadoweb:masterfrom
HrachShah:fix/split-host-and-port-validate-range
Open

split_host_and_port: reject ports above 65535 with HTTPInputError#3658
HrachShah wants to merge 1 commit into
tornadoweb:masterfrom
HrachShah:fix/split-host-and-port-validate-range

Conversation

@HrachShah

Copy link
Copy Markdown

What

tornado.httputil.split_host_and_port parses host:port strings via a
regex that accepts any number of digits in the port slot, so
split_host_and_port('example.com:70000') silently returns
('example.com', 70000). That out-of-range port then surfaces in the
request handling stack as a confusing OSError from socket creation or a
garbled HTTP request instead of a clean validation error.

Fix

Add an explicit range check that raises HTTPInputError for any port
above 65535, matching what the rest of the option/address parsers in the
project do for invalid host:port inputs.

match = _netloc_re.match(netloc)
if match:
    host = match.group(1)
    port: int | None = int(match.group(2))
    if port < 0 or port > 65535:
        raise HTTPInputError("Invalid port number %r" % port)

Negative ports are already filtered out by the regex (\d+ only matches
digits), so the only runtime check needed is the upper bound.

Tests

Added SplitHostAndPortTest in tornado/test/httputil_test.py:

  • test_host_onlyexample.com -> ('example.com', None)
  • test_host_and_portexample.com:8080 -> ('example.com', 8080)
  • test_port_above_max_raisesexample.com:70000 -> HTTPInputError
  • test_port_at_upper_boundexample.com:65535 -> accepted
  • test_port_at_lower_boundexample.com:0 -> accepted

All 61 httputil_test tests pass. The new test_port_above_max_raises
fails on the pre-fix code (returns the out-of-range port without raising).

The current regex accepts any number of digits, so 'example.com:70000' parses
without complaint and surfaces as an out-of-range port deeper in the stack.
Add an explicit range check that raises HTTPInputError for any port above
65535, matching what the rest of the option/address parsers in the project
already do for invalid host:port inputs.
@bdarnell

bdarnell commented Jul 4, 2026

Copy link
Copy Markdown
Member

LGTM except for the lint failure

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.

2 participants