Skip to content

fix(util): validate the port in parse_host() - #2793

Closed
tony1233200 wants to merge 3 commits into
falconry:masterfrom
tony1233200:fix/2756-parse-host-port-validation
Closed

tony1233200 wants to merge 3 commits into
falconry:masterfrom
tony1233200:fix/2756-parse-host-port-validation

Conversation

@tony1233200

Copy link
Copy Markdown

Summary of Changes

falcon.uri.parse_host() converted the port substring with a bare int():

  • a malformed port such as example.com:abc raised a generic ValueError: invalid literal for int()... that never mentions the port;
  • forms that int() happens to accept slipped through although they are not valid ports per RFC 3986 (port = *DIGIT, ASCII only): 1_000, -1, +80, a leading space, and non-ASCII digits (e.g. Arabic-Indic ٨٠, which int() parses as 80);
  • an empty port (example.com:) raised ValueError, although RFC 3986 allows an empty port subcomponent, equivalent to an absent port.

This PR routes both port conversions in parse_host() (domain/IPv4 and bracketed IPv6) through a small _parse_port() helper in falcon/util/uri.py:

  • an empty port falls back to default_port;
  • a port that does not consist of ASCII digits only raises a descriptive ValueError, e.g. 'abc' is not a valid port (only ASCII digits are allowed);
  • anything else is converted with int() exactly as before.

The exception type stays ValueError and no public API changes; the only behavioural changes are the rejected int()-accepted forms above, and the empty-port handling.

Decisions taken (this issue is tagged needs-decision)

I went with the fix suggested in the issue itself and the direction the discussion converged on, and deliberately kept the change minimal:

  1. ASCII digits only. This answers the question raised in the issue thread: values previously accepted by the virtue of int() parsing (1_000, negative numbers, +80, whitespace, non-ASCII digits) are now rejected. Happy to narrow this if you prefer a softer transition.
  2. Empty port means "no port". RFC 3986 defines port = *DIGIT, so an empty port is syntactically valid and equivalent to omitting it; it now falls back to the default port instead of raising.
  3. Deliberately left out (flagged in my issue comment; easy follow-ups if you want them):
    • converting this into a 400 at the Request layer (e.g. via HTTPInvalidHeader): req.port / req.host still surface the ValueError when application code accesses them, the same mechanism as today, just with a message that names the port;
    • leniency in access_route for RFC 7239 obfuscated ports (for="1.2.3.4:_hidden"): a malformed port in a Forwarded hop raises the same ValueError as before this change;
    • numeric range validation: an all-digit port such as 99999 is returned as-is, exactly as before.

Tests

  • New test_parse_host_malformed_port in tests/test_utils.py: empty port (domain with/without default_port, bracketed IPv6) plus nine malformed forms asserted to raise ValueError mentioning ASCII digits (abc, 1_000, -1, +80, leading space, Arabic-Indic digits, superscript two, [::1]:abc, [::1]:-1).
  • pytest tests/test_utils.py — 405 passed.
  • pytest tests/test_request_access_route.py tests/test_request_attrs.py tests/asgi/test_request_asgi.py — 308 passed (covers the WSGI and ASGI call sites of parse_host()).
  • ruff check and ruff format --check on the changed files — clean.
  • The full tox gate was not run in my environment; the focused runs above were used instead.

Disclosure

In line with the "Use of LLMs" section of the contributing guide: an LLM-based coding assistant helped draft this changeset. The change was reviewed line by line and tested as described above before submission, and no LLM is credited as a commit author.

Related Issues

Closes #2756.

Pull Request Checklist

  • Applied changes to both WSGI and ASGI code paths and interfaces (where applicable). (The change is in the shared falcon.util.uri.parse_host(), used by both flavours.)
  • Added tests for changed code.
  • Performed automated tests and code quality checks by running tox. (Full tox gate not run; focused pytest files and ruff were run instead — see Tests above.)
  • Prefixed code comments with GitHub nick and an appropriate prefix. (No new tagged comments were added.)
  • Coding style is consistent with the rest of the framework.
  • Updated documentation for changed code.
    • Added docstrings for any new classes, functions, or modules.
    • Updated docstrings for any modifications to existing code.
    • Updated both WSGI and ASGI docs (where applicable). (Shared utility; nothing flavour-specific to update.)
    • Added references to new classes, functions, or modules to the relevant RST file under docs/. (The new helper is module-private; the public parse_host() docstring was updated instead.)
    • Updated all relevant supporting documentation files under docs/.
    • A copyright notice is included at the top of any new modules. (No new modules.)
    • Changed/added classes/methods/functions have appropriate versionadded, versionchanged, or deprecated directives. (Added .. versionchanged:: 4.5 to parse_host().)
  • Changes (and possible deprecations) have towncrier news fragments under docs/_newsfragments/, with the file name format {issue_number}.{fragment_type}.rst. (Added 2756.bugfix.rst.)
  • LLM output, if any, has been carefully reviewed and tested by a human developer. (See the Disclosure section above.)

tony1233200 and others added 2 commits November 7, 2026 09:45
parse_host() converted the port substring with a bare int(), so a
malformed port raised a generic ValueError that never mentioned the
port, while forms int() happens to accept (such as 1_000, -1, or
non-ASCII digits) slipped through even though RFC 3986 only allows
ASCII digits in the port subcomponent.

Validate the port through a small helper: an empty port is treated as
absent (RFC 3986) and falls back to the default port, a port that is
not composed of ASCII digits only raises a descriptive ValueError,
and anything else is converted with int() as before.
@codecov

codecov Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (cc39813) to head (c999a9a).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #2793   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           64        64           
  Lines         8121      8127    +6     
  Branches      1131      1133    +2     
=========================================
+ Hits          8121      8127    +6     

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

@vytas7 vytas7 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.

Thanks for the PR @tony1233200, looks good for most it.

Do we have a test checking how an IPv6 address without a port is handled (should get a default port)?

See also the inline comment about the Sphinx and intersphinx links.

Edit: you do need to run a full tox gate too. Now you happened to miss typing issues, could you also take a look at these?

Comment thread docs/_newsfragments/2756.bugfix.rst Resolved
- tests: cover IPv6 addresses without a port, expecting the
  default port (bracketed address with and without a trailing
  colon).
- fix(typing): move _parse_port() below parse_host() so the
  @overload variants are immediately followed by their
  implementation; mypy previously reported no-overload-impl
  and no-redef for falcon/util/uri.py.
- docs: link parse_host() and ValueError in the 2756
  newsfragment with Sphinx cross-references instead of
  double backticks.
@tony1233200

This comment was marked as low quality.

@vytas7 vytas7 closed this Nov 14, 2026
@vytas7 vytas7 added the ai-slop label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

falcon.uri.parse_host() can raise a generic error on malformed port

2 participants