From b958016d7ff19e1d7033eee6fca591f010174255 Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Sun, 29 Nov 2026 05:45:20 -0500 Subject: [PATCH 1/7] 4.1.2: stricter proxy header handling; deprecate legacy engine --- .gitignore | 5 +- CHANGELOG.md | 8 ++ README.md | 24 +++--- python_ipware/__version__.py | 2 +- python_ipware/legacy/README.md | 2 + python_ipware/legacy/__init__.py | 52 +++++++++++- python_ipware/modern/engine.py | 47 ++++++++--- python_ipware/modern/parsers.py | 59 ++++++++++---- python_ipware/router.py | 8 +- tests/legacy/run_against_legacy.py | 4 + tests/tests_modern_config.py | 126 ++++++++++++++++++++++++++++- tests/tests_modern_matrix.py | 61 ++++++++++---- tests/tests_router.py | 39 ++++++++- 13 files changed, 374 insertions(+), 63 deletions(-) diff --git a/.gitignore b/.gitignore index 757d294..827550d 100644 --- a/.gitignore +++ b/.gitignore @@ -57,4 +57,7 @@ docs/_build/ target/ .DS_Store -.ruff_cache \ No newline at end of file +.ruff_cache +/.dojo/ +/.dojo-d/ +/temp/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a77bd2..6f75519 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## 4.1.2 + +Reported by Sang Nguyen. + +- Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 4.1.2+ +- Deprecate the legacy engine (`algorithm="legacy"` / `LegacyIpWare`). It now emits a `DeprecationWarning` + and will be removed in a future major release; move to the default `IpWare()`. + ## 4.1.1 Reported privately by David Gilman. diff --git a/README.md b/README.md index 1f9f56e..8ad06ee 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,9 @@ Python 3.9+ is supported (tested on 3.9 – 3.14), with no upper version cap. No On a newer Python that isn't in the test matrix yet? It should just work — if it doesn't, [open an issue](https://github.com/un33k/python-ipware/issues) and we'll fix it. -> **Legacy:** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`. -> See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md). +> **Legacy (deprecated):** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`, +> but it emits a `DeprecationWarning` and will be removed in a future major release. Move to the default +> `IpWare()`. See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md). ## What it's used for @@ -101,7 +102,9 @@ ip, trusted_route = ipw.get_client_ip(meta, strict=False) ### Selection rules -Headers are checked in precedence order. Every address is ranked: +Without `proxy_count` / `proxy_list`, headers are checked in precedence order. With either set, +the first header present decides on its own; lower headers are not consulted, and the result is +`(None, False)` if that header does not validate. Every address is ranked: | Rank | Addresses | | --- | --- | @@ -117,6 +120,8 @@ wins a tie. Within one header, the client entry depends on your proxy settings: - **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, exactly as in v3. + Entries that are not IPs (`unknown`, `for=_hidden`) still count as positions, so they never shift + which entry is the client. - **Neither set:** the first public entry in the chain, not only the first entry. So `10.0.0.1, 177.139.233.139` yields `177.139.233.139` (v3 returned `10.0.0.1`). With `leftmost=False` the chain is scanned from the right. That public entry may be an upstream proxy @@ -132,12 +137,13 @@ flowchart TD A["Request headers (...)"] --> B["Take the next header in precedence order"] B --> C{"Header present?"} C -->|no| B - C -->|yes| D["Split the chain: client, proxy1, proxy2"] - D --> E{"Matches proxy_count and proxy_list?"} - E -->|no| B - E -->|yes| F["Pick the client entry"] - F --> G{"Public IP?"} - G -->|yes| H["Return (ip, trusted_route)"] + C -->|yes| K{"proxy_count or proxy_list set?"} + K -->|yes| E{"Matches proxy_count and proxy_list?"} + E -->|no| N["Return (None, False)"] + E -->|yes| F["Return the entry before the trusted proxies, True"] + K -->|no| D["Split the chain"] + D --> G{"Public IP in it?"} + G -->|yes| H["Return (ip, False)"] G -->|no| I["Keep if it outranks the current fallback"] I --> B B -->|no headers left| J["Return the best fallback, else None"] diff --git a/python_ipware/__version__.py b/python_ipware/__version__.py index 72aa758..13ffcf4 100644 --- a/python_ipware/__version__.py +++ b/python_ipware/__version__.py @@ -1 +1 @@ -__version__ = "4.1.1" +__version__ = "4.1.2" diff --git a/python_ipware/legacy/README.md b/python_ipware/legacy/README.md index b420f6f..1bc3cc3 100644 --- a/python_ipware/legacy/README.md +++ b/python_ipware/legacy/README.md @@ -1,5 +1,7 @@ # Legacy engine (v3) — how to use +> **Deprecated.** The legacy engine emits a `DeprecationWarning` and will be removed in a future major release. Use the default `IpWare()` instead. +> > This is the original python-ipware 3.x guide, kept for reference. The legacy engine is frozen and only runs when requested explicitly with `IpWare(algorithm="legacy")`. For current usage see the [main README](../../README.md). ```python diff --git a/python_ipware/legacy/__init__.py b/python_ipware/legacy/__init__.py index dc8ebdf..7d7f7f0 100644 --- a/python_ipware/legacy/__init__.py +++ b/python_ipware/legacy/__init__.py @@ -1,12 +1,58 @@ -"""Frozen v3 algorithm. +"""Frozen v3 algorithm (deprecated). This subpackage preserves the exact behavior of python-ipware 3.x. It is kept byte-for-byte stable so that projects upgrading to 4.x can pin ``algorithm="legacy"`` and get identical results to what they had before. +The legacy engine is deprecated and will be removed in a future major release. +Constructing it emits a ``DeprecationWarning``; the frozen ``engine`` module +itself is untouched. + Do not "improve" this module. New behavior belongs in ``python_ipware.modern``. """ -from .engine import IpWare as LegacyIpWare +import os +import sys +import warnings +from types import FrameType +from typing import TYPE_CHECKING, Any, Optional + +from .engine import IpWare as _V3IpWare + +if TYPE_CHECKING: + from typing_extensions import deprecated +else: + + def deprecated(_msg): # runtime no-op; the warning is issued in __init__ + return lambda obj: obj + + +LEGACY_DEPRECATION_MESSAGE = ( + "The legacy engine (algorithm='legacy' / LegacyIpWare) is deprecated and will be " + "removed in a future major release. Use the default engine: IpWare()." +) + +_PACKAGE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.sep + + +def _warn_deprecated() -> None: + # Point the warning at the first caller outside python_ipware, so it is + # attributed to user code whether it came via IpWare(...) or LegacyIpWare(). + frame: Optional[FrameType] = sys._getframe(0) + level = 1 + while frame is not None and os.path.abspath(frame.f_code.co_filename).startswith(_PACKAGE_DIR): + frame = frame.f_back + level += 1 + warnings.warn(LEGACY_DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=level) + + +@deprecated(LEGACY_DEPRECATION_MESSAGE) +class LegacyIpWare(_V3IpWare): + """The frozen v3 engine. Deprecated: use ``IpWare()`` (modern).""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _warn_deprecated() + super().__init__(*args, **kwargs) + -__all__ = ["LegacyIpWare"] +__all__ = ["LEGACY_DEPRECATION_MESSAGE", "LegacyIpWare"] diff --git a/python_ipware/modern/engine.py b/python_ipware/modern/engine.py index 7556caa..00ded44 100644 --- a/python_ipware/modern/engine.py +++ b/python_ipware/modern/engine.py @@ -33,6 +33,7 @@ IpNetworkType, ip_tier, split_proxy_chain, + split_proxy_chain_positions, unwrap_ipv4, unwrap_ipv4_network, ) @@ -179,7 +180,7 @@ def _get_meta_values(self, meta: Optional[Mapping[Any, Any]]) -> list[str]: # -- validation --------------------------------------------------------- - def _proxy_count_valid(self, chain: list[IpAddressType], strict: bool) -> bool: + def _proxy_count_valid(self, chain: list[OptionalIp], strict: bool) -> bool: if self.proxy_count is None: return True proxies = len(chain) - 1 @@ -187,7 +188,7 @@ def _proxy_count_valid(self, chain: list[IpAddressType], strict: bool) -> bool: return proxies == self.proxy_count return proxies >= self.proxy_count - def _proxy_list_valid(self, chain: list[IpAddressType], strict: bool) -> bool: + def _proxy_list_valid(self, chain: list[OptionalIp], strict: bool) -> bool: if not self.proxy_list: return True count = len(self.proxy_list) @@ -197,18 +198,19 @@ def _proxy_list_valid(self, chain: list[IpAddressType], strict: bool) -> bool: return False # Compare the trailing proxies against the trusted entries in order. return all( - _proxy_matches(ip, matcher) + ip is not None and _proxy_matches(ip, matcher) for ip, matcher in zip(chain[-count:], self._proxy_matchers) ) # -- selection ---------------------------------------------------------- + def _pinned_from_chain(self, chain: list[OptionalIp]) -> OptionalIp: + """Client slot fixed by proxy_list / proxy_count; None if that slot is invalid.""" + count = len(self.proxy_list) if self.proxy_list else (self.proxy_count or 0) + return chain[-(count + 1)] + def _best_from_chain(self, chain: list[IpAddressType]) -> tuple[OptionalIp, bool]: # ``chain`` is already client-first (see get_client_ip) and non-empty. - if self.proxy_list: - return chain[-(len(self.proxy_list) + 1)], True - if self.proxy_count is not None: - return chain[-(self.proxy_count + 1)], True # No trusted-proxy config, so no position in the chain is verified. # Take the first globally routable hop; otherwise the best-ranked hop, # earliest on ties. This never picks a worse address than v3's chain[0]. @@ -231,6 +233,9 @@ def get_client_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool = False) fallback_tier = TIER_REJECT fallback_trusted = False + if self.proxy_list or self.proxy_count is not None: + return self._get_pinned_ip(meta, strict) + for raw in self._get_meta_values(meta): chain = split_proxy_chain(raw, strict) if not chain: @@ -239,10 +244,6 @@ def get_client_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool = False) # the proxy checks and the client pick look at the same end. if not self.leftmost: chain.reverse() - if not self._proxy_count_valid(chain, strict): - continue - if not self._proxy_list_valid(chain, strict): - continue ip, trusted = self._best_from_chain(chain) if ip is None: @@ -254,3 +255,27 @@ def get_client_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool = False) fallback, fallback_tier, fallback_trusted = ip, tier, trusted return fallback, fallback_trusted + + def _get_pinned_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool) -> tuple[OptionalIp, bool]: + """Resolve with proxy_count / proxy_list: the first header present decides. + + Lower-precedence headers are never consulted once a header is present, + whether it validates or not and whatever the client's tier. Invalid + hops keep their position, so they can never shift the client slot. + """ + values = self._get_meta_values(meta) + if not values: + return None, False + chain = split_proxy_chain_positions(values[0], strict) + if not chain: + return None, False + # Client-first order ONCE, before validation, so the proxy checks and + # the client pick look at the same end. + if not self.leftmost: + chain.reverse() + if not (self._proxy_count_valid(chain, strict) and self._proxy_list_valid(chain, strict)): + return None, False + ip = self._pinned_from_chain(chain) + if ip is None or ip_tier(ip) == TIER_REJECT: + return None, False + return ip, True diff --git a/python_ipware/modern/parsers.py b/python_ipware/modern/parsers.py index be94db6..85a4a62 100644 --- a/python_ipware/modern/parsers.py +++ b/python_ipware/modern/parsers.py @@ -115,13 +115,28 @@ def strip_port(value: str) -> str: return value # bare IPv6 or bare IPv4 +def _has_unclosed_quote(value: str) -> bool: + """True when a double-quoted string in ``value`` is never closed.""" + if '"' not in value: + return False + quoted = escaped = False + for ch in value: + if escaped: + escaped = False + elif quoted and ch == "\\": + escaped = True + elif ch == '"': + quoted = not quoted + return quoted + + def split_unquoted(value: str, sep: str) -> list[str]: """Split ``value`` on ``sep``, ignoring separators inside double quotes. RFC 7239 values may be quoted strings (``by="a,b"``), and a separator inside one must not start a new hop or parameter. Backslash escapes inside - quotes are honoured. An unclosed quote swallows the rest of the value, so - that token fails to parse instead of leaking a fragment as a fake hop. + quotes are honoured. An unclosed quote swallows the rest of the value; + ``split_proxy_chain`` rejects such values before splitting. """ if '"' not in value: return value.split(sep) @@ -206,25 +221,41 @@ def unwrap_ipv4_network(net: IpNetworkType) -> IpNetworkType: return net -def split_proxy_chain(raw: Optional[str], strict: bool = False) -> Optional[list[IpAddressType]]: - """Split a comma-separated proxy chain into ordered ``ip_address`` objects. +def split_proxy_chain_positions(raw: Optional[str], strict: bool = False) -> Optional[list[Optional[IpAddressType]]]: + """Split a proxy chain, keeping a ``None`` placeholder for each invalid hop. - Order is preserved left-to-right as it appears in the header. Tokens in - RFC 7239 form (``for=...;proto=...``) are reduced to their ``for`` value; - obfuscated identifiers such as ``for=unknown`` or ``for=_hidden`` are not - IPs and count as invalid. In strict mode, any invalid or empty token makes - the whole chain invalid (returns None), since a malformed header should not - be trusted. Otherwise invalid and empty tokens are skipped. + Like ``split_proxy_chain`` but positional: an invalid or empty token keeps + its slot, so counting hops from either end stays aligned with the header. + Strict mode and an unclosed double quote still reject the whole chain. """ if not raw: return [] - result: list[IpAddressType] = [] + if _has_unclosed_quote(raw): + return None + result: list[Optional[IpAddressType]] = [] for token in split_unquoted(raw, ","): # No plain IP token contains "=", only RFC 7239 Forwarded elements do. candidate = forwarded_for(token) if "=" in token else token ip = parse_ip(candidate) - if ip is not None: - result.append(ip) - elif strict: + if ip is None and strict: return None + result.append(ip) return result + + +def split_proxy_chain(raw: Optional[str], strict: bool = False) -> Optional[list[IpAddressType]]: + """Split a comma-separated proxy chain into ordered ``ip_address`` objects. + + Order is preserved left-to-right as it appears in the header. Tokens in + RFC 7239 form (``for=...;proto=...``) are reduced to their ``for`` value; + obfuscated identifiers such as ``for=unknown`` or ``for=_hidden`` are not + IPs and count as invalid. In strict mode, any invalid or empty token makes + the whole chain invalid (returns None), since a malformed header should not + be trusted. Otherwise invalid and empty tokens are skipped. + + An unclosed double quote makes the chain invalid in both modes. + """ + chain = split_proxy_chain_positions(raw, strict) + if chain is None: + return None + return [ip for ip in chain if ip is not None] diff --git a/python_ipware/router.py b/python_ipware/router.py index ed76b3f..a499ea3 100644 --- a/python_ipware/router.py +++ b/python_ipware/router.py @@ -12,14 +12,15 @@ hop behind a private first hop, no multicast / unspecified results, and ``trusted_route`` for private clients behind trusted proxies (see CHANGELOG). ``legacy`` remains available as an explicit escape hatch for projects that -need byte-for-byte v3 behavior. There is no silent runtime fallback, so -behavior stays predictable. +need byte-for-byte v3 behavior, but it is deprecated: selecting it emits a +``DeprecationWarning``, and it will be removed in a future major release. +There is no silent runtime fallback, so behavior stays predictable. from python_ipware import IpWare IpWare() # auto -> modern (the forward-moving default) IpWare(algorithm="modern") # explicit modern - IpWare(algorithm="legacy") # frozen v3 behavior (escape hatch) + IpWare(algorithm="legacy") # frozen v3 behavior (deprecated escape hatch) """ from typing import Literal, Optional @@ -52,6 +53,7 @@ def __init__( resolved = "modern" if algorithm == "auto" else algorithm self.resolved_algorithm = resolved + self._impl: "LegacyIpWare | ModernIpWare" if resolved == "legacy": self._impl = LegacyIpWare( precedence=precedence, diff --git a/tests/legacy/run_against_legacy.py b/tests/legacy/run_against_legacy.py index e384426..ac1ecb1 100644 --- a/tests/legacy/run_against_legacy.py +++ b/tests/legacy/run_against_legacy.py @@ -16,6 +16,7 @@ import functools import sys import unittest +import warnings from python_ipware import IpWare @@ -23,6 +24,9 @@ LegacyBound = functools.partial(IpWare, algorithm="legacy") +# The legacy engine is deprecated; this runner exercises it on purpose. +warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning) + def build_suite() -> unittest.TestSuite: # Rebind the IpWare symbol the untouched test modules use. diff --git a/tests/tests_modern_config.py b/tests/tests_modern_config.py index 35ed70b..9bc530b 100644 --- a/tests/tests_modern_config.py +++ b/tests/tests_modern_config.py @@ -4,15 +4,28 @@ import ipaddress import unittest +import warnings from typing import ClassVar from python_ipware import IpWare -from python_ipware.modern.parsers import TIER_PRIVATE, TIER_REJECT, ip_tier, split_proxy_chain, split_unquoted +from python_ipware.modern.parsers import ( + TIER_PRIVATE, + TIER_REJECT, + _has_unclosed_quote, + ip_tier, + split_proxy_chain, + split_unquoted, +) ip = ipaddress.ip_address CLIENT = ip("8.8.8.8") +def setUpModule(): + # Legacy is deprecated; the few comparisons against it here are on purpose. + warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning) + + def trusted_via(proxy_entry, hop, strict=True): """Resolve ``8.8.8.8, `` with a single trusted proxy entry.""" meta = {"HTTP_X_FORWARDED_FOR": f"8.8.8.8, {hop}"} @@ -224,9 +237,9 @@ def test_quoted_comma_cannot_fake_proxy_hop(self): meta = {"HTTP_FORWARDED": 'for=8.8.4.4;by="_a,9.9.9.9"'} self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (None, False)) - def test_unclosed_quote_swallows_the_rest(self): + def test_unclosed_quote_rejects_the_header(self): meta = {"HTTP_FORWARDED": 'for=8.8.8.8, for="6.6.6.6, for=9.9.9.9'} - self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False)) + self.assertEqual(IpWare().get_client_ip(meta), (None, False)) self.assertEqual(IpWare().get_client_ip(meta, strict=True), (None, False)) def test_split_unquoted_helper(self): @@ -234,6 +247,113 @@ def test_split_unquoted_helper(self): self.assertEqual(split_unquoted('a,"b,c",d', ","), ["a", '"b,c"', "d"]) self.assertEqual(split_unquoted('"a\\",b",c', ","), ['"a\\",b"', "c"]) self.assertEqual(split_unquoted("", ","), [""]) + self.assertEqual(split_unquoted('a,"b,c', ","), ["a", '"b,c']) # unchanged helper contract + + def test_unclosed_quote_detection(self): + self.assertTrue(_has_unclosed_quote('a,"b,c')) + self.assertTrue(_has_unclosed_quote('a,"b\\"')) # escaped quote does not close + self.assertFalse(_has_unclosed_quote('a,"b,c",d')) + self.assertFalse(_has_unclosed_quote("a,b")) + + def test_split_proxy_chain_rejects_unclosed_quote(self): + for strict in (False, True): + with self.subTest(strict=strict): + self.assertIsNone(split_proxy_chain('9.9.9.9, ", 8.8.8.8', strict)) + + +class TestMalformedQuoting(unittest.TestCase): + """Malformed quoting in a client-supplied prefix is rejected, not repaired.""" + + REAL = "203.0.113.7" # true client, appended by the edge proxy + HOP = "198.51.100.10" # trusted proxy, appended by the inner proxy + + def resolve(self, prefix, strict=False, header="HTTP_X_FORWARDED_FOR", **kw): + meta = {header: f"{prefix}, {self.REAL}, {self.HOP}"} + return IpWare(**kw).get_client_ip(meta, strict=strict) + + def test_control_forged_prefix_is_ignored(self): + self.assertEqual(self.resolve("9.9.9.9", proxy_count=1), (ip(self.REAL), True)) + self.assertEqual(self.resolve("9.9.9.9", proxy_list=[self.HOP]), (ip(self.REAL), True)) + + def test_unclosed_quote_proxy_count(self): + for strict in (False, True): + with self.subTest(strict=strict): + self.assertEqual(self.resolve('9.9.9.9, 7.7.7.7, "', strict, proxy_count=1), (None, False)) + + def test_unclosed_quote_proxy_list(self): + prefix = f'9.9.9.9, {self.HOP}, "' + for strict in (False, True): + with self.subTest(strict=strict): + self.assertEqual(self.resolve(prefix, strict, proxy_list=[self.HOP]), (None, False)) + + def test_unclosed_quote_rightmost(self): + self.assertEqual(self.resolve('9.9.9.9, 7.7.7.7, "', proxy_count=1, leftmost=False), (None, False)) + + def test_unclosed_quote_forwarded_header(self): + meta = {"HTTP_FORWARDED": f'for=9.9.9.9, for=7.7.7.7, for=", for={self.REAL}, for="[2001:db8::1]:4711"'} + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (None, False)) + + def test_falls_back_to_next_header(self): + meta = {"HTTP_X_FORWARDED_FOR": f'9.9.9.9, ", {self.REAL}', "REMOTE_ADDR": self.REAL} + self.assertEqual(IpWare().get_client_ip(meta), (ip(self.REAL), False)) + + def test_rejected_header_does_not_fall_through(self): + meta = {"HTTP_X_FORWARDED_FOR": f'", {self.REAL}, {self.HOP}', "HTTP_CLIENT_IP": "9.9.9.9, 7.7.7.7"} + for strict in (False, True): + with self.subTest(strict=strict): + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta, strict), (None, False)) + + def test_strict_junk_does_not_fall_through(self): + meta = {"HTTP_X_FORWARDED_FOR": f"junk, 8.8.4.4, {self.HOP}", "HTTP_CLIENT_IP": "9.9.9.9, 7.7.7.7"} + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta, strict=True), (None, False)) + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("8.8.4.4"), True)) + + def test_private_client_is_final(self): + meta = {"HTTP_X_FORWARDED_FOR": f"10.1.2.3, {self.HOP}", "HTTP_CLIENT_IP": "9.9.9.9, 7.7.7.7"} + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("10.1.2.3"), True)) + self.assertEqual(IpWare(proxy_list=[self.HOP]).get_client_ip(meta), (ip("10.1.2.3"), True)) + + def test_lower_header_unused_when_first_is_present(self): + meta = {"HTTP_X_REAL_IP": "8.8.4.4", "REMOTE_ADDR": f"9.9.9.9, {self.HOP}"} + ipw = IpWare(precedence=("HTTP_X_REAL_IP", "REMOTE_ADDR"), proxy_count=1) + self.assertEqual(ipw.get_client_ip(meta), (None, False)) + + def test_invalid_hops_keep_their_position(self): + cases = { + "HTTP_X_FORWARDED_FOR": "9.9.9.9, 8.8.4.4, unknown", + "HTTP_FORWARDED": "for=9.9.9.9, for=8.8.4.4, for=_hidden", + } + for header, raw in cases.items(): + with self.subTest(header=header): + # The appended invalid hop is the proxy slot; the client is 8.8.4.4. + self.assertEqual(IpWare(proxy_count=1).get_client_ip({header: raw}), (ip("8.8.4.4"), True)) + meta = {"HTTP_FORWARDED": "for=9.9.9.9, for=8.8.4.4, proto=https;by=_edge"} + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("8.8.4.4"), True)) + + def test_invalid_client_slot_is_none(self): + meta = {"HTTP_X_FORWARDED_FOR": f"9.9.9.9, unknown, {self.HOP}"} + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (None, False)) + self.assertEqual(IpWare(proxy_list=[self.HOP]).get_client_ip(meta), (None, False)) + + def test_invalid_trusted_slot_fails_proxy_list(self): + meta = {"HTTP_X_FORWARDED_FOR": "9.9.9.9, 8.8.4.4, unknown"} + self.assertEqual(IpWare(proxy_list=[self.HOP]).get_client_ip(meta), (None, False)) + + def test_client_prefix_never_wins(self): + """With proxy_count=n the answer is never drawn from the client prefix.""" + forged = ["9.9.9.9", "7.7.7.7", "1.1.1.1"] + tails = ['"', '"\\', '" ', 'x"', '"a""', 'for="', '"[', '"9.9.9.9'] + for n in range(1, 4): + for k in range(0, 4): + for tail in tails: + prefix = ", ".join([*forged[:k], tail]) + for strict in (False, True): + for leftmost in (True, False): + with self.subTest(n=n, prefix=prefix, strict=strict, leftmost=leftmost): + hops = [f"198.51.100.{i}" for i in range(1, n + 1)] + meta = {"HTTP_X_FORWARDED_FOR": ", ".join([prefix, self.REAL, *hops])} + got, _ = IpWare(proxy_count=n, leftmost=leftmost).get_client_ip(meta, strict=strict) + self.assertNotIn(str(got), forged) def test_split_proxy_chain_empty(self): self.assertEqual(split_proxy_chain(""), []) diff --git a/tests/tests_modern_matrix.py b/tests/tests_modern_matrix.py index 1b4b9f6..a76724e 100644 --- a/tests/tests_modern_matrix.py +++ b/tests/tests_modern_matrix.py @@ -22,6 +22,7 @@ import itertools import random import unittest +import warnings from typing import ClassVar, Optional from python_ipware import IpWare @@ -34,6 +35,12 @@ ip_tier, ) + +def setUpModule(): + # Legacy is deprecated; this suite compares against it on purpose. + warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning) + + G, P, LL, LB, REJ = TIER_GLOBAL, TIER_PRIVATE, TIER_LINK_LOCAL, TIER_LOOPBACK, TIER_REJECT # token -> (address, tier) by hand, or None for a token that is not an IP. @@ -94,8 +101,13 @@ def _oracle(raw_values, leftmost, proxy_count, proxy_list, strict): """Reference model of the documented modern algorithm. ``raw_values`` are header values already in precedence order. + + With proxy_count / proxy_list the first present header decides alone, and + invalid hops keep their position (they are never skipped). """ configured = proxy_count is not None or bool(proxy_list) + if configured: + return _pinned_oracle(raw_values, leftmost, proxy_count, proxy_list, strict) best = None # (address, tier, trusted); first header wins ties for raw in raw_values: hops = [TRUTH[t.strip()] for t in raw.split(",")] @@ -106,32 +118,43 @@ def _oracle(raw_values, leftmost, proxy_count, proxy_list, strict): chain.reverse() if not chain: continue - proxies = len(chain) - 1 - if proxy_count is not None and (proxies < proxy_count or (strict and proxies != proxy_count)): - continue - if proxy_list: - n = len(proxy_list) - if proxies < n or (strict and proxies != n): - continue - if not all(_proxy_ok(addr, pat) for (addr, _), pat in zip(chain[-n:], proxy_list)): - continue - if configured: - n = len(proxy_list) if proxy_list else proxy_count - address, tier = chain[-(n + 1)] - else: - globals_ = [h for h in chain if h[1] == G] - address, tier = globals_[0] if globals_ else max(chain, key=lambda h: h[1]) + globals_ = [h for h in chain if h[1] == G] + address, tier = globals_[0] if globals_ else max(chain, key=lambda h: h[1]) if tier == REJ: continue if tier == G: - return ipaddress.ip_address(address), configured + return ipaddress.ip_address(address), False if best is None or tier > best[1]: - best = (address, tier, configured) + best = (address, tier, False) if best is None: return None, False return ipaddress.ip_address(best[0]), best[2] +def _pinned_oracle(raw_values, leftmost, proxy_count, proxy_list, strict): + if not raw_values: + return None, False + chain = [TRUTH[t.strip()] for t in raw_values[0].split(",")] # None marks an invalid hop + if strict and any(h is None for h in chain): + return None, False + if not leftmost: + chain.reverse() + proxies = len(chain) - 1 + if proxy_count is not None and (proxies < proxy_count or (strict and proxies != proxy_count)): + return None, False + if proxy_list: + n = len(proxy_list) + if proxies < n or (strict and proxies != n): + return None, False + if not all(h is not None and _proxy_ok(h[0], pat) for h, pat in zip(chain[-n:], proxy_list)): + return None, False + n = len(proxy_list) if proxy_list else proxy_count + hop = chain[-(n + 1)] + if hop is None or hop[1] == REJ: + return None, False + return ipaddress.ip_address(hop[0]), True + + class TestTierTable(unittest.TestCase): """The ranking every other test relies on, checked against the labels.""" @@ -277,6 +300,10 @@ def test_whole_single_header_matrix(self): meta = {"HTTP_X_FORWARDED_FOR": ", ".join(hops)} for proxy_count, proxy_list in CONFIGS: configured = proxy_count is not None or bool(proxy_list) + # Legacy drops invalid hops, which shifts the pinned client slot; + # modern keeps their position, so those answers differ on purpose. + if configured and "unknown" in hops: + continue for leftmost in (True, False): kw = {"leftmost": leftmost, "proxy_count": proxy_count, "proxy_list": proxy_list} legacy, modern = IpWare(algorithm="legacy", **kw), IpWare(**kw) diff --git a/tests/tests_router.py b/tests/tests_router.py index 9aad84e..7247137 100644 --- a/tests/tests_router.py +++ b/tests/tests_router.py @@ -1,15 +1,48 @@ import ipaddress import logging import unittest +import warnings from typing import ClassVar from python_ipware import IpWare, LegacyIpWare, ModernIpWare +from python_ipware.legacy import LEGACY_DEPRECATION_MESSAGE from python_ipware.modern.defaults import DEFAULT_PRECEDENCE from python_ipware.modern.parsers import TIER_GLOBAL, TIER_REJECT, ip_tier logging.disable(logging.CRITICAL) +def setUpModule(): + # Legacy is deprecated; tests that compare against it on purpose stay quiet. + # Set inside the run (unittest resets filters first); assertWarns still sees it. + warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning) + + +class TestLegacyDeprecation(unittest.TestCase): + def test_router_legacy_warns_at_caller(self): + with self.assertWarns(DeprecationWarning) as cm: + IpWare(algorithm="legacy") + self.assertEqual(str(cm.warning), LEGACY_DEPRECATION_MESSAGE) + self.assertEqual(cm.filename, __file__) + + def test_direct_legacy_warns_at_caller(self): + with self.assertWarns(DeprecationWarning) as cm: + LegacyIpWare() + self.assertEqual(cm.filename, __file__) + + def test_modern_does_not_warn(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + IpWare() + IpWare(algorithm="modern") + + def test_legacy_still_works(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + ipw = IpWare(algorithm="legacy") + self.assertEqual(ipw.get_client_ip({"REMOTE_ADDR": "8.8.8.8"})[0].exploded, "8.8.8.8") + + class TestAlgorithmRouter(unittest.TestCase): def test_default_is_auto_modern(self): ipw = IpWare() @@ -417,6 +450,10 @@ def test_modern_never_worse(self): for plist in self.PROXY_LISTS: kw = {"leftmost": leftmost, "proxy_count": count, "proxy_list": plist} configured = count is not None or bool(plist) + # Legacy drops invalid hops, shifting the pinned slot; + # modern keeps their position, so these differ on purpose. + if configured and "not-an-ip" in raw: + continue legacy = IpWare(algorithm="legacy", **kw) modern = IpWare(algorithm="modern", **kw) for strict in (False, True): @@ -431,7 +468,7 @@ def test_modern_never_worse(self): self.assertEqual(m_trusted, l_trusted or (configured and m_ip is not None)) checked += 1 improved += (m_ip, m_trusted) != (l_ip, l_trusted) - self.assertGreater(checked, 3000) + self.assertGreater(checked, 2500) self.assertGreater(improved, 0) # the matrix really exercises the new ranking From 8a0cbee7191b85dc8aeb13d8dad002e80a5645a2 Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Sun, 29 Nov 2026 05:50:47 -0500 Subject: [PATCH 2/7] 5.0.0: pinned mode ends on unusable top header; docs, warning guard, review fixes --- CHANGELOG.md | 6 ++- README.md | 15 ++++-- python_ipware/__version__.py | 2 +- python_ipware/legacy/__init__.py | 23 ++++++--- python_ipware/modern/defaults.py | 7 +-- python_ipware/modern/engine.py | 84 +++++++++++++++++++------------- python_ipware/router.py | 2 +- tests/tests_modern_config.py | 19 ++++++++ tests/tests_router.py | 8 ++- 9 files changed, 111 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f75519..64df62f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,10 @@ -## 4.1.2 +## 5.0.0 Reported by Sang Nguyen. -- Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 4.1.2+ +- Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 5.0.0+ +- Breaking: with `proxy_count` / `proxy_list` set, only the first header present (by precedence) is used; + lower headers are no longer consulted. Pass a `precedence` naming the header your proxies write. - Deprecate the legacy engine (`algorithm="legacy"` / `LegacyIpWare`). It now emits a `DeprecationWarning` and will be removed in a future major release; move to the default `IpWare()`. diff --git a/README.md b/README.md index 8ad06ee..da00a07 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,9 @@ ip, trusted_route = ipw.get_client_ip(meta, strict=False) Without `proxy_count` / `proxy_list`, headers are checked in precedence order. With either set, the first header present decides on its own; lower headers are not consulted, and the result is -`(None, False)` if that header does not validate. Every address is ranked: +`(None, False)` if that header does not validate. So with proxy settings, pass a `precedence` +naming only the header your proxies write (for example `("HTTP_X_FORWARDED_FOR", "REMOTE_ADDR")`). +Every address is ranked: | Rank | Addresses | | --- | --- | @@ -119,9 +121,9 @@ wins a tie. Within one header, the client entry depends on your proxy settings: -- **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, exactly as in v3. - Entries that are not IPs (`unknown`, `for=_hidden`) still count as positions, so they never shift - which entry is the client. +- **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, as in v3. Unlike + v3, entries that are empty or not IPs (`unknown`, `for=_hidden`) still count as positions, so they + never shift which entry is the client. - **Neither set:** the first public entry in the chain, not only the first entry. So `10.0.0.1, 177.139.233.139` yields `177.139.233.139` (v3 returned `10.0.0.1`). With `leftmost=False` the chain is scanned from the right. That public entry may be an upstream proxy @@ -150,7 +152,7 @@ flowchart TD ``` The legacy engine keeps v3's rules. A combination suite checks that the modern engine never returns a -worse address than legacy for the same input. +worse address than legacy for a single well-formed header. Ports are stripped (`1.2.3.4:8080`, `[2001:db8::1]:443`). IPv4-mapped (`::ffff:1.2.3.4`) and NAT64 well-known-prefix (`64:ff9b::1.2.3.4`) addresses are returned as plain IPv4. RFC 7239 `Forwarded` elements are read by their @@ -216,6 +218,9 @@ reachable directly, because clients can send these headers themselves: ipw = IpWare(precedence=("HTTP_CF_CONNECTING_IP", "HTTP_X_FORWARDED_FOR", "REMOTE_ADDR")) ``` +Do not combine this with `proxy_count` / `proxy_list`: with proxy settings the first header present +decides alone, and a single-IP header such as `CF-Connecting-IP` never has proxy hops to match. + ## Trusted proxies If your server sits behind known proxies, pass their IPs or prefixes: diff --git a/python_ipware/__version__.py b/python_ipware/__version__.py index 13ffcf4..ba7be38 100644 --- a/python_ipware/__version__.py +++ b/python_ipware/__version__.py @@ -1 +1 @@ -__version__ = "4.1.2" +__version__ = "5.0.0" diff --git a/python_ipware/legacy/__init__.py b/python_ipware/legacy/__init__.py index 7d7f7f0..06e0a56 100644 --- a/python_ipware/legacy/__init__.py +++ b/python_ipware/legacy/__init__.py @@ -6,7 +6,8 @@ The legacy engine is deprecated and will be removed in a future major release. Constructing it emits a ``DeprecationWarning``; the frozen ``engine`` module -itself is untouched. +itself is untouched, so importing ``python_ipware.legacy.engine.IpWare`` +directly bypasses the warning (that private path is not supported). Do not "improve" this module. New behavior belongs in ``python_ipware.modern``. """ @@ -32,17 +33,25 @@ def deprecated(_msg): # runtime no-op; the warning is issued in __init__ "removed in a future major release. Use the default engine: IpWare()." ) -_PACKAGE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.sep +_PACKAGE_DIR = os.path.normcase(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.sep) + + +def _in_package(filename: str) -> bool: + return os.path.normcase(os.path.abspath(filename)).startswith(_PACKAGE_DIR) def _warn_deprecated() -> None: # Point the warning at the first caller outside python_ipware, so it is # attributed to user code whether it came via IpWare(...) or LegacyIpWare(). - frame: Optional[FrameType] = sys._getframe(0) - level = 1 - while frame is not None and os.path.abspath(frame.f_code.co_filename).startswith(_PACKAGE_DIR): - frame = frame.f_back - level += 1 + # The walk only aims the warning; it must never stop it from being issued. + level = 2 + getframe = getattr(sys, "_getframe", None) # CPython/PyPy only + if getframe is not None: + frame: Optional[FrameType] = getframe(0) + level = 1 + while frame is not None and _in_package(frame.f_code.co_filename): + frame = frame.f_back + level += 1 warnings.warn(LEGACY_DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=level) diff --git a/python_ipware/modern/defaults.py b/python_ipware/modern/defaults.py index a1e3338..0e7d6a2 100644 --- a/python_ipware/modern/defaults.py +++ b/python_ipware/modern/defaults.py @@ -1,8 +1,9 @@ """Default header precedence for the modern engine. -Superset of the v3 list, adding widely-deployed CDN/edge headers. Headers are -scanned in order; the first one that yields a globally routable IP wins, with -private and then loopback addresses as fallbacks. +Superset of the v3 list, adding widely-deployed CDN/edge headers. Without +proxy settings, headers are scanned in order; the first one that yields a +globally routable IP wins, with private and then loopback addresses as +fallbacks. With proxy_count / proxy_list, the first header present decides. Ordering rule: existing entries never move. New headers are added only in the block just above ``REMOTE_ADDR``, so a new header can outrank the raw socket diff --git a/python_ipware/modern/engine.py b/python_ipware/modern/engine.py index 00ded44..d19913e 100644 --- a/python_ipware/modern/engine.py +++ b/python_ipware/modern/engine.py @@ -8,8 +8,10 @@ multicast, broadcast and reserved addresses are never returned. * Without trusted-proxy config, the first *globally routable* hop of a chain wins, not just the first hop, so ``10.0.0.1, 177.139.233.139`` yields the - public address. With ``proxy_count`` / ``proxy_list`` the client position is - fixed by the config, exactly as in v3. + public address, and headers are scanned in precedence order. With + ``proxy_count`` / ``proxy_list`` the first header present decides alone and + the client position is fixed by the config; unlike v3, invalid hops keep + their position instead of being dropped. * Same ``strict`` semantics for proxy_count / proxy_list validation. * Trusted-proxy matching anchored to the end of the chain. Each ``proxy_list`` entry is a CIDR network (``"100.64.0.0/10"``, ``"fd7a:115c:a1e0::/48"``), a @@ -90,13 +92,18 @@ def _fold(key: str) -> str: return key.upper().replace("-", "_") +# Marks a folded header whose spellings disagree. It is not text, so the +# unpinned scan skips it and the pinned path treats it as present but unusable. +_AMBIGUOUS = object() + + def _build_folded(meta: Mapping[Any, Any]) -> dict[str, object]: """Case- and dash-insensitive view of ``meta`` for lowercase-key adapters. When several spellings fold to the same name, the result must not depend on dict order. Real header names use dashes, while an underscore spelling in a raw header dict can only come from the client, so dash spellings win. - If several dash spellings disagree, the header is treated as absent. + If several dash spellings disagree, the header maps to ``_AMBIGUOUS``. """ groups: dict[str, list[tuple[str, object]]] = {} for key, value in meta.items(): @@ -110,8 +117,7 @@ def _build_folded(meta: Mapping[Any, Any]) -> dict[str, object]: for value in pool: if value not in distinct: distinct.append(value) - if len(distinct) == 1: - folded[name] = distinct[0] + folded[name] = distinct[0] if len(distinct) == 1 else _AMBIGUOUS return folded @@ -141,7 +147,7 @@ def __init__( raise ValueError("proxy_list entries must not be empty.") # proxy_count and proxy_list may both be set and may differ (v3 API): # the count is a hop-count requirement (minimum, or exact when strict) - # and the list pins the client position. See _best_from_chain. + # and the list pins the client position. See _pinned_from_chain. if isinstance(precedence, str) or ( precedence is not None and not all(isinstance(h, str) for h in precedence) ): @@ -156,14 +162,20 @@ def __init__( # -- meta access -------------------------------------------------------- - def _get_meta_values(self, meta: Optional[Mapping[Any, Any]]) -> list[str]: + def _get_meta_entries(self, meta: Optional[Mapping[Any, Any]]) -> list[Optional[str]]: + """Present headers in precedence order. + + Each entry is the stripped text, or None for a header that is present + but unusable (not text, or spellings that disagree). Absent and + whitespace-only headers are left out. + """ if meta is None: return [] if not isinstance(meta, Mapping): msg = f"meta must be a mapping of header names to values, got {type(meta).__name__}" raise TypeError(msg) folded = _build_folded(meta) - values: list[str] = [] + entries: list[Optional[str]] = [] for key in self.precedence: value = meta.get(key) if value is None: @@ -172,11 +184,18 @@ def _get_meta_values(self, meta: Optional[Mapping[Any, Any]]) -> list[str]: # keys (AWS Lambda / API Gateway v2, raw ASGI dicts) still match. if value is None: value = folded.get(_fold(key)) - # Header values are text; anything else (None, bytes, lists from - # a misbehaving adapter) is ignored rather than crashing. - if isinstance(value, str) and value.strip(): - values.append(value.strip()) - return values + if value is None: + continue + # Header values are text; anything else (bytes, lists from a + # misbehaving adapter, ambiguous spellings) is unusable, never a crash. + if not isinstance(value, str): + entries.append(None) + elif value.strip(): + entries.append(value.strip()) + return entries + + def _get_meta_values(self, meta: Optional[Mapping[Any, Any]]) -> list[str]: + return [v for v in self._get_meta_entries(meta) if v is not None] # -- validation --------------------------------------------------------- @@ -209,7 +228,7 @@ def _pinned_from_chain(self, chain: list[OptionalIp]) -> OptionalIp: count = len(self.proxy_list) if self.proxy_list else (self.proxy_count or 0) return chain[-(count + 1)] - def _best_from_chain(self, chain: list[IpAddressType]) -> tuple[OptionalIp, bool]: + def _best_from_chain(self, chain: list[IpAddressType]) -> OptionalIp: # ``chain`` is already client-first (see get_client_ip) and non-empty. # No trusted-proxy config, so no position in the chain is verified. # Take the first globally routable hop; otherwise the best-ranked hop, @@ -219,54 +238,49 @@ def _best_from_chain(self, chain: list[IpAddressType]) -> tuple[OptionalIp, bool for ip in chain: tier = ip_tier(ip) if tier == TIER_GLOBAL: - return ip, False + return ip if tier > best_tier: best, best_tier = ip, tier - return best, False + return best # -- public API --------------------------------------------------------- def get_client_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool = False) -> tuple[OptionalIp, bool]: - # Best non-global candidate so far. Strictly-greater comparison keeps - # the earliest header on ties, preserving header precedence. - fallback: OptionalIp = None - fallback_tier = TIER_REJECT - fallback_trusted = False - if self.proxy_list or self.proxy_count is not None: return self._get_pinned_ip(meta, strict) + # No proxy config, so nothing is trusted. Best non-global candidate so + # far; strictly-greater comparison keeps the earliest header on ties. + fallback: OptionalIp = None + fallback_tier = TIER_REJECT for raw in self._get_meta_values(meta): chain = split_proxy_chain(raw, strict) if not chain: continue - # Put the chain in client-first order ONCE, before any validation, so - # the proxy checks and the client pick look at the same end. if not self.leftmost: chain.reverse() - - ip, trusted = self._best_from_chain(chain) + ip = self._best_from_chain(chain) if ip is None: continue tier = ip_tier(ip) if tier == TIER_GLOBAL: - return ip, trusted + return ip, False if tier > fallback_tier: - fallback, fallback_tier, fallback_trusted = ip, tier, trusted - - return fallback, fallback_trusted + fallback, fallback_tier = ip, tier + return fallback, False def _get_pinned_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool) -> tuple[OptionalIp, bool]: """Resolve with proxy_count / proxy_list: the first header present decides. Lower-precedence headers are never consulted once a header is present, - whether it validates or not and whatever the client's tier. Invalid - hops keep their position, so they can never shift the client slot. + whether it is usable or validates, and whatever the client's tier. + Invalid and empty hops keep their position, so they can never shift the + client slot. """ - values = self._get_meta_values(meta) - if not values: + entries = self._get_meta_entries(meta) + if not entries or entries[0] is None: return None, False - chain = split_proxy_chain_positions(values[0], strict) + chain = split_proxy_chain_positions(entries[0], strict) if not chain: return None, False # Client-first order ONCE, before validation, so the proxy checks and diff --git a/python_ipware/router.py b/python_ipware/router.py index a499ea3..82f4d38 100644 --- a/python_ipware/router.py +++ b/python_ipware/router.py @@ -8,7 +8,7 @@ The ``algorithm`` selector chooses between them. ``"auto"`` (the default) is a clean alias for ``"modern"`` — the enhanced engine is where development moves forward. It passes the full v3 suite, and a differential test checks it never -returns a worse address than v3. It picks better where v3 did not: a public +returns a worse address than v3 for a single well-formed header. It picks better where v3 did not: a public hop behind a private first hop, no multicast / unspecified results, and ``trusted_route`` for private clients behind trusted proxies (see CHANGELOG). ``legacy`` remains available as an explicit escape hatch for projects that diff --git a/tests/tests_modern_config.py b/tests/tests_modern_config.py index 9bc530b..2df93ee 100644 --- a/tests/tests_modern_config.py +++ b/tests/tests_modern_config.py @@ -313,6 +313,25 @@ def test_private_client_is_final(self): self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("10.1.2.3"), True)) self.assertEqual(IpWare(proxy_list=[self.HOP]).get_client_ip(meta), (ip("10.1.2.3"), True)) + def test_unusable_first_header_does_not_fall_through(self): + forged = {"Client-IP": f"9.9.9.9, {self.HOP}"} + metas = { + "disagreeing spellings": {"x-forwarded-for": "junk", "X-Forwarded-For": f"{self.REAL}, {self.HOP}"}, + "non-text value": {"HTTP_X_FORWARDED_FOR": [f"{self.REAL}, {self.HOP}"]}, + } + for name, meta in metas.items(): + for kw in ({"proxy_count": 1}, {"proxy_list": [self.HOP]}): + with self.subTest(case=name, **kw): + self.assertEqual(IpWare(**kw).get_client_ip({**meta, **forged}), (None, False)) + + def test_unusable_header_still_skipped_without_proxy_config(self): + meta = {"x-forwarded-for": "6.6.6.6", "X-Forwarded-For": "7.7.7.7", "REMOTE_ADDR": "8.8.8.8"} + self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False)) + + def test_empty_hops_keep_their_position(self): + meta = {"HTTP_X_FORWARDED_FOR": "9.9.9.9, 8.8.4.4, "} + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("8.8.4.4"), True)) + def test_lower_header_unused_when_first_is_present(self): meta = {"HTTP_X_REAL_IP": "8.8.4.4", "REMOTE_ADDR": f"9.9.9.9, {self.HOP}"} ipw = IpWare(precedence=("HTTP_X_REAL_IP", "REMOTE_ADDR"), proxy_count=1) diff --git a/tests/tests_router.py b/tests/tests_router.py index 7247137..ce65ba7 100644 --- a/tests/tests_router.py +++ b/tests/tests_router.py @@ -1,8 +1,10 @@ import ipaddress import logging +import sys import unittest import warnings from typing import ClassVar +from unittest import mock from python_ipware import IpWare, LegacyIpWare, ModernIpWare from python_ipware.legacy import LEGACY_DEPRECATION_MESSAGE @@ -36,6 +38,10 @@ def test_modern_does_not_warn(self): IpWare() IpWare(algorithm="modern") + def test_warning_issued_without_getframe(self): + with mock.patch.object(sys, "_getframe", None), self.assertWarns(DeprecationWarning): + LegacyIpWare() + def test_legacy_still_works(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) @@ -468,7 +474,7 @@ def test_modern_never_worse(self): self.assertEqual(m_trusted, l_trusted or (configured and m_ip is not None)) checked += 1 improved += (m_ip, m_trusted) != (l_ip, l_trusted) - self.assertGreater(checked, 2500) + self.assertGreater(checked, 2800) self.assertGreater(improved, 0) # the matrix really exercises the new ranking From 9a560912cda84947d5fad89f7b7219fa058da48b Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Sun, 29 Nov 2026 05:53:46 -0500 Subject: [PATCH 3/7] Decide each header from all its spellings; dashed beats underscore; doc version wording --- CHANGELOG.md | 3 ++- python_ipware/legacy/__init__.py | 2 +- python_ipware/modern/engine.py | 17 ++++++++--------- python_ipware/router.py | 2 +- tests/tests_modern_config.py | 13 +++++++++++++ tests/tests_router.py | 6 ++++-- 6 files changed, 29 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64df62f..2395825 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,8 @@ Reported by Sang Nguyen. - Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 5.0.0+ - Breaking: with `proxy_count` / `proxy_list` set, only the first header present (by precedence) is used; - lower headers are no longer consulted. Pass a `precedence` naming the header your proxies write. + lower headers are no longer consulted, and empty or non-IP entries keep their position in the chain. + Pass a `precedence` naming the header your proxies write. - Deprecate the legacy engine (`algorithm="legacy"` / `LegacyIpWare`). It now emits a `DeprecationWarning` and will be removed in a future major release; move to the default `IpWare()`. diff --git a/python_ipware/legacy/__init__.py b/python_ipware/legacy/__init__.py index 06e0a56..472cf41 100644 --- a/python_ipware/legacy/__init__.py +++ b/python_ipware/legacy/__init__.py @@ -1,7 +1,7 @@ """Frozen v3 algorithm (deprecated). This subpackage preserves the exact behavior of python-ipware 3.x. It is kept -byte-for-byte stable so that projects upgrading to 4.x can pin +byte-for-byte stable so that projects upgrading to 4.x or 5.x can pin ``algorithm="legacy"`` and get identical results to what they had before. The legacy engine is deprecated and will be removed in a future major release. diff --git a/python_ipware/modern/engine.py b/python_ipware/modern/engine.py index d19913e..18a06b0 100644 --- a/python_ipware/modern/engine.py +++ b/python_ipware/modern/engine.py @@ -107,14 +107,15 @@ def _build_folded(meta: Mapping[Any, Any]) -> dict[str, object]: """ groups: dict[str, list[tuple[str, object]]] = {} for key, value in meta.items(): - if isinstance(key, str): + if isinstance(key, str) and value is not None: groups.setdefault(_fold(key), []).append((key, value)) folded: dict[str, object] = {} for name, items in groups.items(): dashed = [v for k, v in items if "-" in k] pool = dashed or [v for _, v in items] distinct: list[object] = [] - for value in pool: + for raw in pool: + value = raw.strip() if isinstance(raw, str) else raw if value not in distinct: distinct.append(value) folded[name] = distinct[0] if len(distinct) == 1 else _AMBIGUOUS @@ -177,13 +178,11 @@ def _get_meta_entries(self, meta: Optional[Mapping[Any, Any]]) -> list[Optional[ folded = _build_folded(meta) entries: list[Optional[str]] = [] for key in self.precedence: - value = meta.get(key) - if value is None: - value = meta.get(key.replace("_", "-")) - # Exact keys win; the folded view only fills gaps, so lowercase - # keys (AWS Lambda / API Gateway v2, raw ASGI dicts) still match. - if value is None: - value = folded.get(_fold(key)) + # Every spelling of a header is decided together (case, dash and + # underscore insensitive), so no single spelling can win outright. + # WSGI / ASGI / Lambda dicts hold one spelling per header, so this + # matches exact, lowercase and dashed keys alike. + value = folded.get(_fold(key)) if value is None: continue # Header values are text; anything else (bytes, lists from a diff --git a/python_ipware/router.py b/python_ipware/router.py index 82f4d38..84ff802 100644 --- a/python_ipware/router.py +++ b/python_ipware/router.py @@ -1,6 +1,6 @@ """Public ``IpWare`` facade with an algorithm router. -python-ipware 4.x ships two engines: +python-ipware 4.x and 5.x ship two engines: * ``legacy`` -> the frozen, byte-compatible v3 algorithm. * ``modern`` -> the enhanced v4 algorithm (more headers, hardened parsing). diff --git a/tests/tests_modern_config.py b/tests/tests_modern_config.py index 2df93ee..c2c9eee 100644 --- a/tests/tests_modern_config.py +++ b/tests/tests_modern_config.py @@ -318,12 +318,25 @@ def test_unusable_first_header_does_not_fall_through(self): metas = { "disagreeing spellings": {"x-forwarded-for": "junk", "X-Forwarded-For": f"{self.REAL}, {self.HOP}"}, "non-text value": {"HTTP_X_FORWARDED_FOR": [f"{self.REAL}, {self.HOP}"]}, + "exact-hit case variant": {"X-FORWARDED-FOR": "6.6.6.6", "X-Forwarded-For": f"{self.REAL}, {self.HOP}"}, + "blank dashed variant": {"X-FORWARDED-FOR": " ", "X-Forwarded-For": f"{self.REAL}, {self.HOP}"}, } for name, meta in metas.items(): for kw in ({"proxy_count": 1}, {"proxy_list": [self.HOP]}): with self.subTest(case=name, **kw): self.assertEqual(IpWare(**kw).get_client_ip({**meta, **forged}), (None, False)) + def test_dashed_spelling_beats_underscore_spelling(self): + cases = { + "underscore exact hit": {"X_FORWARDED_FOR": "9.9.9.9, 7.7.7.7"}, + "blank underscore exact hit": {"X_FORWARDED_FOR": " ", "Client-IP": "9.9.9.9, 7.7.7.7"}, + } + for name, extra in cases.items(): + meta = {**extra, "X-Forwarded-For": f"{self.REAL}, {self.HOP}"} + for kw in ({"proxy_count": 1}, {"proxy_list": [self.HOP]}): + with self.subTest(case=name, **kw): + self.assertEqual(IpWare(**kw).get_client_ip(meta), (ip(self.REAL), True)) + def test_unusable_header_still_skipped_without_proxy_config(self): meta = {"x-forwarded-for": "6.6.6.6", "X-Forwarded-For": "7.7.7.7", "REMOTE_ADDR": "8.8.8.8"} self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False)) diff --git a/tests/tests_router.py b/tests/tests_router.py index ce65ba7..ca4cea4 100644 --- a/tests/tests_router.py +++ b/tests/tests_router.py @@ -348,10 +348,12 @@ def test_lowercase_keys_match(self): ip, _ = IpWare().get_client_ip(meta) self.assertEqual(str(ip), "203.0.113.70") - def test_exact_key_beats_folded_key(self): + def test_dashed_spelling_beats_underscore_spelling(self): + # Real header names use dashes; an underscore spelling can only come + # from the client, so it never outranks the dashed header. meta = {"X_FORWARDED_FOR": "203.0.113.71", "x-forwarded-for": "203.0.113.72"} ip, _ = IpWare().get_client_ip(meta) - self.assertEqual(str(ip), "203.0.113.71") + self.assertEqual(str(ip), "203.0.113.72") def test_empty_proxy_entry_raises(self): for plist in ([""], [" "], ["10.0.0.", ""]): From 898ae419ad23a1d875ca4e9ec4ddcb43b0758ed5 Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Sun, 29 Nov 2026 05:55:52 -0500 Subject: [PATCH 4/7] CGI names (REMOTE_ADDR, HTTP_*) count only underscore spellings; docs --- README.md | 5 ++++- python_ipware/modern/engine.py | 34 +++++++++++++++++++++++++++------- tests/tests_modern_config.py | 20 ++++++++++++++++++++ 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index da00a07..9988750 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,10 @@ Ports are stripped (`1.2.3.4:8080`, `[2001:db8::1]:443`). IPv4-mapped (`::ffff:1 well-known-prefix (`64:ff9b::1.2.3.4`) addresses are returned as plain IPv4. RFC 7239 `Forwarded` elements are read by their `for=` value (`for="[2001:db8::1]:4711";proto=https`). Malformed tokens such as `[::1`, `[::1]junk`, or `1.2.3.4:abc` are rejected rather than truncated. Header names match -case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too. +case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too. When one header +appears under several spellings, a dashed name (`X-Forwarded-For`) beats an underscore one +(`X_FORWARDED_FOR`), and disagreeing spellings make the header unusable. `REMOTE_ADDR` and +`HTTP_*` keys are server variables, so a client header such as `Remote-Addr` never replaces them. ## Default header precedence diff --git a/python_ipware/modern/engine.py b/python_ipware/modern/engine.py index 18a06b0..7d36a61 100644 --- a/python_ipware/modern/engine.py +++ b/python_ipware/modern/engine.py @@ -97,13 +97,28 @@ def _fold(key: str) -> str: _AMBIGUOUS = object() +def _is_cgi_name(name: str) -> bool: + """True for CGI / WSGI variable names, which are never sent as header names.""" + return name == "REMOTE_ADDR" or name.startswith("HTTP_") + + def _build_folded(meta: Mapping[Any, Any]) -> dict[str, object]: - """Case- and dash-insensitive view of ``meta`` for lowercase-key adapters. + """Case-, dash- and underscore-insensitive view of ``meta``. + + This is the only lookup path, so every spelling of a name is decided + together and the result never depends on dict order. Keys with a None + value are ignored, and string values are compared after stripping. - When several spellings fold to the same name, the result must not depend - on dict order. Real header names use dashes, while an underscore spelling - in a raw header dict can only come from the client, so dash spellings win. - If several dash spellings disagree, the header maps to ``_AMBIGUOUS``. + Which spellings count depends on the folded name: + + * CGI / WSGI variables (``REMOTE_ADDR``, ``HTTP_*``) are set by the server + or the app, never sent as header names, so only underscore spellings + count. A client header such as ``Remote-Addr`` cannot replace them. + * Everything else is a header name. Real header names use dashes, while + an underscore spelling in a raw header dict can only come from the + client, so dash spellings win when present. + + If the counted spellings disagree, the name maps to ``_AMBIGUOUS``. """ groups: dict[str, list[tuple[str, object]]] = {} for key, value in meta.items(): @@ -111,8 +126,13 @@ def _build_folded(meta: Mapping[Any, Any]) -> dict[str, object]: groups.setdefault(_fold(key), []).append((key, value)) folded: dict[str, object] = {} for name, items in groups.items(): - dashed = [v for k, v in items if "-" in k] - pool = dashed or [v for _, v in items] + if _is_cgi_name(name): + pool = [v for k, v in items if "-" not in k] + if not pool: + continue + else: + dashed = [v for k, v in items if "-" in k] + pool = dashed or [v for _, v in items] distinct: list[object] = [] for raw in pool: value = raw.strip() if isinstance(raw, str) else raw diff --git a/tests/tests_modern_config.py b/tests/tests_modern_config.py index c2c9eee..771dd04 100644 --- a/tests/tests_modern_config.py +++ b/tests/tests_modern_config.py @@ -337,6 +337,26 @@ def test_dashed_spelling_beats_underscore_spelling(self): with self.subTest(case=name, **kw): self.assertEqual(IpWare(**kw).get_client_ip(meta), (ip(self.REAL), True)) + def test_client_header_cannot_replace_cgi_variable(self): + cases = [ + ({"remote-addr": "9.9.9.9", "REMOTE_ADDR": self.REAL}, {"precedence": ("REMOTE_ADDR",)}, False), + ( + {"Remote-Addr": "9.9.9.9", "REMOTE_ADDR": self.REAL}, + {"precedence": ("REMOTE_ADDR",), "proxy_count": 0}, + True, + ), + ({"remote-addr": " ", "REMOTE_ADDR": self.REAL}, {}, False), + ] + for meta, kw, trusted in cases: + with self.subTest(meta=meta, **kw): + self.assertEqual(IpWare(**kw).get_client_ip(meta), (ip(self.REAL), trusted)) + meta = {"Http-X-Forwarded-For": f"9.9.9.9, {self.HOP}", "HTTP_X_FORWARDED_FOR": f"{self.REAL}, {self.HOP}"} + self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip(self.REAL), True)) + + def test_dashed_only_cgi_name_is_absent(self): + meta = {"Remote-Addr": "9.9.9.9", "X-Forwarded-For": "8.8.8.8"} + self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False)) + def test_unusable_header_still_skipped_without_proxy_config(self): meta = {"x-forwarded-for": "6.6.6.6", "X-Forwarded-For": "7.7.7.7", "REMOTE_ADDR": "8.8.8.8"} self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False)) From 5d6e9ea865f48e6e2dbedc559b9912668ada711c Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Sun, 29 Nov 2026 05:57:15 -0500 Subject: [PATCH 5/7] Test: dashed-only CGI name is absent (isolated) --- tests/tests_modern_config.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/tests_modern_config.py b/tests/tests_modern_config.py index 771dd04..1c080e7 100644 --- a/tests/tests_modern_config.py +++ b/tests/tests_modern_config.py @@ -354,8 +354,8 @@ def test_client_header_cannot_replace_cgi_variable(self): self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip(self.REAL), True)) def test_dashed_only_cgi_name_is_absent(self): - meta = {"Remote-Addr": "9.9.9.9", "X-Forwarded-For": "8.8.8.8"} - self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False)) + meta = {"Remote-Addr": "9.9.9.9"} + self.assertEqual(IpWare().get_client_ip(meta), (None, False)) def test_unusable_header_still_skipped_without_proxy_config(self): meta = {"x-forwarded-for": "6.6.6.6", "X-Forwarded-For": "7.7.7.7", "REMOTE_ADDR": "8.8.8.8"} From 540b88e7f5bb6bea700bc9e0afc648c4eb1c0892 Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Sun, 29 Nov 2026 05:58:57 -0500 Subject: [PATCH 6/7] Changelog: credit reporter's GitHub handle --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2395825..66dae12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ ## 5.0.0 -Reported by Sang Nguyen. +Reported by Sang Nguyen ([@Sengtocxoen](https://github.com/Sengtocxoen)). - Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 5.0.0+ - Breaking: with `proxy_count` / `proxy_list` set, only the first header present (by precedence) is used; From 2247e23eb17e8ddf79a45f3a9f29a77a52e0a412 Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Sun, 29 Nov 2026 05:59:48 -0500 Subject: [PATCH 7/7] Changelog: credit reporter as requested --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66dae12..cdfd9bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ ## 5.0.0 -Reported by Sang Nguyen ([@Sengtocxoen](https://github.com/Sengtocxoen)). +Reported by Sang Nguyen (sangn6767@gmail.com). - Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 5.0.0+ - Breaking: with `proxy_count` / `proxy_list` set, only the first header present (by precedence) is used;