Skip to content

Commit

Permalink
wrap IPv6 SERVER_NAME in [] (#2997)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism authored Nov 7, 2024
2 parents ea93b54 + d99f72d commit ba15683
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ Unreleased
``list``, ``tuple``, or ``set`` when passing multiple values. It had been
changed to accept any ``Collection``, but this matched types that should be
treated as single values, such as ``bytes``. :issue:`2994`
- When the ``Host`` header is not set and ``Request.host`` falls back to the
WSGI ``SERVER_NAME`` value, if that value is an IPv6 address it is wrapped
in ``[]`` to match the ``Host`` header. :issue:`2993`


Version 3.1.2
Expand Down
8 changes: 8 additions & 0 deletions src/werkzeug/sansio/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ def get_host(
:return: Host, with port if necessary.
:raise ~werkzeug.exceptions.SecurityError: If the host is not
trusted.
.. versionchanged:: 3.1.3
If ``SERVER_NAME`` is IPv6, it is wrapped in ``[]``.
"""
host = ""

Expand All @@ -79,6 +82,11 @@ def get_host(
elif server is not None:
host = server[0]

# If SERVER_NAME is IPv6, wrap it in [] to match Host header.
# Check for : because domain or IPv4 can't have that.
if ":" in host and host[0] != "[":
host = f"[{host}]"

if server[1] is not None:
host = f"{host}:{server[1]}"

Expand Down
4 changes: 4 additions & 0 deletions tests/sansio/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,16 @@
("https", "spam", None, "spam"),
("https", "spam:443", None, "spam"),
("http", "spam:8080", None, "spam:8080"),
("http", "127.0.0.1:8080", None, "127.0.0.1:8080"),
("http", "[::1]:8080", None, "[::1]:8080"),
("ws", "spam", None, "spam"),
("ws", "spam:80", None, "spam"),
("wss", "spam", None, "spam"),
("wss", "spam:443", None, "spam"),
("http", None, ("spam", 80), "spam"),
("http", None, ("spam", 8080), "spam:8080"),
("http", None, ("127.0.0.1", 8080), "127.0.0.1:8080"),
("http", None, ("::1", 8080), "[::1]:8080"),
("http", None, ("unix/socket", None), "unix/socket"),
("http", "spam", ("eggs", 80), "spam"),
],
Expand Down

0 comments on commit ba15683

Please sign in to comment.