python-ipware 4.1.1__tar.gz → 5.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {python_ipware-4.1.1 → python_ipware-5.0.0}/.gitignore +4 -1
  2. {python_ipware-4.1.1 → python_ipware-5.0.0}/CHANGELOG.md +11 -0
  3. {python_ipware-4.1.1 → python_ipware-5.0.0}/PKG-INFO +28 -14
  4. {python_ipware-4.1.1 → python_ipware-5.0.0}/README.md +27 -13
  5. python_ipware-5.0.0/python_ipware/__version__.py +1 -0
  6. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/legacy/README.md +2 -0
  7. python_ipware-5.0.0/python_ipware/legacy/__init__.py +67 -0
  8. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/modern/defaults.py +4 -3
  9. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/modern/engine.py +110 -52
  10. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/modern/parsers.py +45 -14
  11. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/router.py +7 -5
  12. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/legacy/run_against_legacy.py +4 -0
  13. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/tests_modern_config.py +175 -3
  14. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/tests_modern_matrix.py +44 -17
  15. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/tests_router.py +48 -3
  16. python_ipware-4.1.1/python_ipware/__version__.py +0 -1
  17. python_ipware-4.1.1/python_ipware/legacy/__init__.py +0 -12
  18. {python_ipware-4.1.1 → python_ipware-5.0.0}/LICENSE +0 -0
  19. {python_ipware-4.1.1 → python_ipware-5.0.0}/SECURITY.md +0 -0
  20. {python_ipware-4.1.1 → python_ipware-5.0.0}/pyproject.toml +0 -0
  21. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/__init__.py +0 -0
  22. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/legacy/engine.py +0 -0
  23. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/modern/__init__.py +0 -0
  24. {python_ipware-4.1.1 → python_ipware-5.0.0}/python_ipware/py.typed +0 -0
  25. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/__init__.py +0 -0
  26. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/legacy/__init__.py +0 -0
  27. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/legacy/tests_ipv4.py +0 -0
  28. {python_ipware-4.1.1 → python_ipware-5.0.0}/tests/legacy/tests_ipv6.py +0 -0
@@ -57,4 +57,7 @@ docs/_build/
57
57
  target/
58
58
 
59
59
  .DS_Store
60
- .ruff_cache
60
+ .ruff_cache
61
+ /.dojo/
62
+ /.dojo-d/
63
+ /temp/
@@ -1,3 +1,14 @@
1
+ ## 5.0.0
2
+
3
+ Reported by Sang Nguyen (sangn6767@gmail.com).
4
+
5
+ - Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 5.0.0+
6
+ - Breaking: with `proxy_count` / `proxy_list` set, only the first header present (by precedence) is used;
7
+ lower headers are no longer consulted, and empty or non-IP entries keep their position in the chain.
8
+ Pass a `precedence` naming the header your proxies write.
9
+ - Deprecate the legacy engine (`algorithm="legacy"` / `LegacyIpWare`). It now emits a `DeprecationWarning`
10
+ and will be removed in a future major release; move to the default `IpWare()`.
11
+
1
12
  ## 4.1.1
2
13
 
3
14
  Reported privately by David Gilman.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-ipware
3
- Version: 4.1.1
3
+ Version: 5.0.0
4
4
  Summary: A Python package to retrieve a client's real IP address.
5
5
  Project-URL: Homepage, https://github.com/un33k/python-ipware
6
6
  Project-URL: Documentation, https://github.com/un33k/python-ipware#readme
@@ -78,8 +78,9 @@ Python 3.9+ is supported (tested on 3.9 – 3.14), with no upper version cap. No
78
78
  On a newer Python that isn't in the test matrix yet? It should just work — if it doesn't,
79
79
  [open an issue](https://github.com/un33k/python-ipware/issues) and we'll fix it.
80
80
 
81
- > **Legacy:** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`.
82
- > See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md).
81
+ > **Legacy (deprecated):** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`,
82
+ > but it emits a `DeprecationWarning` and will be removed in a future major release. Move to the default
83
+ > `IpWare()`. See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md).
83
84
 
84
85
  ## What it's used for
85
86
 
@@ -143,7 +144,11 @@ ip, trusted_route = ipw.get_client_ip(meta, strict=False)
143
144
 
144
145
  ### Selection rules
145
146
 
146
- Headers are checked in precedence order. Every address is ranked:
147
+ Without `proxy_count` / `proxy_list`, headers are checked in precedence order. With either set,
148
+ the first header present decides on its own; lower headers are not consulted, and the result is
149
+ `(None, False)` if that header does not validate. So with proxy settings, pass a `precedence`
150
+ naming only the header your proxies write (for example `("HTTP_X_FORWARDED_FOR", "REMOTE_ADDR")`).
151
+ Every address is ranked:
147
152
 
148
153
  | Rank | Addresses |
149
154
  | --- | --- |
@@ -158,7 +163,9 @@ wins a tie.
158
163
 
159
164
  Within one header, the client entry depends on your proxy settings:
160
165
 
161
- - **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, exactly as in v3.
166
+ - **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, as in v3. Unlike
167
+ v3, entries that are empty or not IPs (`unknown`, `for=_hidden`) still count as positions, so they
168
+ never shift which entry is the client.
162
169
  - **Neither set:** the first public entry in the chain, not only the first entry. So
163
170
  `10.0.0.1, 177.139.233.139` yields `177.139.233.139` (v3 returned `10.0.0.1`). With
164
171
  `leftmost=False` the chain is scanned from the right. That public entry may be an upstream proxy
@@ -174,25 +181,29 @@ flowchart TD
174
181
  A["Request headers (...)"] --> B["Take the next header in precedence order"]
175
182
  B --> C{"Header present?"}
176
183
  C -->|no| B
177
- C -->|yes| D["Split the chain: client, proxy1, proxy2"]
178
- D --> E{"Matches proxy_count and proxy_list?"}
179
- E -->|no| B
180
- E -->|yes| F["Pick the client entry"]
181
- F --> G{"Public IP?"}
182
- G -->|yes| H["Return (ip, trusted_route)"]
184
+ C -->|yes| K{"proxy_count or proxy_list set?"}
185
+ K -->|yes| E{"Matches proxy_count and proxy_list?"}
186
+ E -->|no| N["Return (None, False)"]
187
+ E -->|yes| F["Return the entry before the trusted proxies, True"]
188
+ K -->|no| D["Split the chain"]
189
+ D --> G{"Public IP in it?"}
190
+ G -->|yes| H["Return (ip, False)"]
183
191
  G -->|no| I["Keep if it outranks the current fallback"]
184
192
  I --> B
185
193
  B -->|no headers left| J["Return the best fallback, else None"]
186
194
  ```
187
195
 
188
196
  The legacy engine keeps v3's rules. A combination suite checks that the modern engine never returns a
189
- worse address than legacy for the same input.
197
+ worse address than legacy for a single well-formed header.
190
198
 
191
199
  Ports are stripped (`1.2.3.4:8080`, `[2001:db8::1]:443`). IPv4-mapped (`::ffff:1.2.3.4`) and NAT64
192
200
  well-known-prefix (`64:ff9b::1.2.3.4`) addresses are returned as plain IPv4. RFC 7239 `Forwarded` elements are read by their
193
201
  `for=` value (`for="[2001:db8::1]:4711";proto=https`). Malformed tokens such as `[::1`,
194
202
  `[::1]junk`, or `1.2.3.4:abc` are rejected rather than truncated. Header names match
195
- case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too.
203
+ case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too. When one header
204
+ appears under several spellings, a dashed name (`X-Forwarded-For`) beats an underscore one
205
+ (`X_FORWARDED_FOR`), and disagreeing spellings make the header unusable. `REMOTE_ADDR` and
206
+ `HTTP_*` keys are server variables, so a client header such as `Remote-Addr` never replaces them.
196
207
 
197
208
  ## Default header precedence
198
209
 
@@ -252,6 +263,9 @@ reachable directly, because clients can send these headers themselves:
252
263
  ipw = IpWare(precedence=("HTTP_CF_CONNECTING_IP", "HTTP_X_FORWARDED_FOR", "REMOTE_ADDR"))
253
264
  ```
254
265
 
266
+ Do not combine this with `proxy_count` / `proxy_list`: with proxy settings the first header present
267
+ decides alone, and a single-IP header such as `CF-Connecting-IP` never has proxy hops to match.
268
+
255
269
  ## Trusted proxies
256
270
 
257
271
  If your server sits behind known proxies, pass their IPs or prefixes:
@@ -358,7 +372,7 @@ backward compatibility; all improvements target the modern engine. Need support?
358
372
 
359
373
  ## Sponsors
360
374
 
361
- [Neekware Inc.](https://neekware.com) — creator of [Dojo Workspace](https://heydojo.ai), your AI workspace for building, learning, and getting things done.
375
+ [HeyDojo AI](https://heydojo.ai) — creator of [Dojo Workspace](https://heydojo.ai), your AI workspace for building, learning, and getting things done.
362
376
 
363
377
  🚀 Created with [Dojo](https://heydojo.ai) ⛩️
364
378
 
@@ -36,8 +36,9 @@ Python 3.9+ is supported (tested on 3.9 – 3.14), with no upper version cap. No
36
36
  On a newer Python that isn't in the test matrix yet? It should just work — if it doesn't,
37
37
  [open an issue](https://github.com/un33k/python-ipware/issues) and we'll fix it.
38
38
 
39
- > **Legacy:** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`.
40
- > See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md).
39
+ > **Legacy (deprecated):** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`,
40
+ > but it emits a `DeprecationWarning` and will be removed in a future major release. Move to the default
41
+ > `IpWare()`. See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md).
41
42
 
42
43
  ## What it's used for
43
44
 
@@ -101,7 +102,11 @@ ip, trusted_route = ipw.get_client_ip(meta, strict=False)
101
102
 
102
103
  ### Selection rules
103
104
 
104
- Headers are checked in precedence order. Every address is ranked:
105
+ Without `proxy_count` / `proxy_list`, headers are checked in precedence order. With either set,
106
+ the first header present decides on its own; lower headers are not consulted, and the result is
107
+ `(None, False)` if that header does not validate. So with proxy settings, pass a `precedence`
108
+ naming only the header your proxies write (for example `("HTTP_X_FORWARDED_FOR", "REMOTE_ADDR")`).
109
+ Every address is ranked:
105
110
 
106
111
  | Rank | Addresses |
107
112
  | --- | --- |
@@ -116,7 +121,9 @@ wins a tie.
116
121
 
117
122
  Within one header, the client entry depends on your proxy settings:
118
123
 
119
- - **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, exactly as in v3.
124
+ - **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, as in v3. Unlike
125
+ v3, entries that are empty or not IPs (`unknown`, `for=_hidden`) still count as positions, so they
126
+ never shift which entry is the client.
120
127
  - **Neither set:** the first public entry in the chain, not only the first entry. So
121
128
  `10.0.0.1, 177.139.233.139` yields `177.139.233.139` (v3 returned `10.0.0.1`). With
122
129
  `leftmost=False` the chain is scanned from the right. That public entry may be an upstream proxy
@@ -132,25 +139,29 @@ flowchart TD
132
139
  A["Request headers (...)"] --> B["Take the next header in precedence order"]
133
140
  B --> C{"Header present?"}
134
141
  C -->|no| B
135
- C -->|yes| D["Split the chain: client, proxy1, proxy2"]
136
- D --> E{"Matches proxy_count and proxy_list?"}
137
- E -->|no| B
138
- E -->|yes| F["Pick the client entry"]
139
- F --> G{"Public IP?"}
140
- G -->|yes| H["Return (ip, trusted_route)"]
142
+ C -->|yes| K{"proxy_count or proxy_list set?"}
143
+ K -->|yes| E{"Matches proxy_count and proxy_list?"}
144
+ E -->|no| N["Return (None, False)"]
145
+ E -->|yes| F["Return the entry before the trusted proxies, True"]
146
+ K -->|no| D["Split the chain"]
147
+ D --> G{"Public IP in it?"}
148
+ G -->|yes| H["Return (ip, False)"]
141
149
  G -->|no| I["Keep if it outranks the current fallback"]
142
150
  I --> B
143
151
  B -->|no headers left| J["Return the best fallback, else None"]
144
152
  ```
145
153
 
146
154
  The legacy engine keeps v3's rules. A combination suite checks that the modern engine never returns a
147
- worse address than legacy for the same input.
155
+ worse address than legacy for a single well-formed header.
148
156
 
149
157
  Ports are stripped (`1.2.3.4:8080`, `[2001:db8::1]:443`). IPv4-mapped (`::ffff:1.2.3.4`) and NAT64
150
158
  well-known-prefix (`64:ff9b::1.2.3.4`) addresses are returned as plain IPv4. RFC 7239 `Forwarded` elements are read by their
151
159
  `for=` value (`for="[2001:db8::1]:4711";proto=https`). Malformed tokens such as `[::1`,
152
160
  `[::1]junk`, or `1.2.3.4:abc` are rejected rather than truncated. Header names match
153
- case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too.
161
+ case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too. When one header
162
+ appears under several spellings, a dashed name (`X-Forwarded-For`) beats an underscore one
163
+ (`X_FORWARDED_FOR`), and disagreeing spellings make the header unusable. `REMOTE_ADDR` and
164
+ `HTTP_*` keys are server variables, so a client header such as `Remote-Addr` never replaces them.
154
165
 
155
166
  ## Default header precedence
156
167
 
@@ -210,6 +221,9 @@ reachable directly, because clients can send these headers themselves:
210
221
  ipw = IpWare(precedence=("HTTP_CF_CONNECTING_IP", "HTTP_X_FORWARDED_FOR", "REMOTE_ADDR"))
211
222
  ```
212
223
 
224
+ Do not combine this with `proxy_count` / `proxy_list`: with proxy settings the first header present
225
+ decides alone, and a single-IP header such as `CF-Connecting-IP` never has proxy hops to match.
226
+
213
227
  ## Trusted proxies
214
228
 
215
229
  If your server sits behind known proxies, pass their IPs or prefixes:
@@ -316,7 +330,7 @@ backward compatibility; all improvements target the modern engine. Need support?
316
330
 
317
331
  ## Sponsors
318
332
 
319
- [Neekware Inc.](https://neekware.com) — creator of [Dojo Workspace](https://heydojo.ai), your AI workspace for building, learning, and getting things done.
333
+ [HeyDojo AI](https://heydojo.ai) — creator of [Dojo Workspace](https://heydojo.ai), your AI workspace for building, learning, and getting things done.
320
334
 
321
335
  🚀 Created with [Dojo](https://heydojo.ai) ⛩️
322
336
 
@@ -0,0 +1 @@
1
+ __version__ = "5.0.0"
@@ -1,5 +1,7 @@
1
1
  # Legacy engine (v3) — how to use
2
2
 
3
+ > **Deprecated.** The legacy engine emits a `DeprecationWarning` and will be removed in a future major release. Use the default `IpWare()` instead.
4
+ >
3
5
  > 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).
4
6
 
5
7
  ```python
@@ -0,0 +1,67 @@
1
+ """Frozen v3 algorithm (deprecated).
2
+
3
+ This subpackage preserves the exact behavior of python-ipware 3.x. It is kept
4
+ byte-for-byte stable so that projects upgrading to 4.x or 5.x can pin
5
+ ``algorithm="legacy"`` and get identical results to what they had before.
6
+
7
+ The legacy engine is deprecated and will be removed in a future major release.
8
+ Constructing it emits a ``DeprecationWarning``; the frozen ``engine`` module
9
+ itself is untouched, so importing ``python_ipware.legacy.engine.IpWare``
10
+ directly bypasses the warning (that private path is not supported).
11
+
12
+ Do not "improve" this module. New behavior belongs in ``python_ipware.modern``.
13
+ """
14
+
15
+ import os
16
+ import sys
17
+ import warnings
18
+ from types import FrameType
19
+ from typing import TYPE_CHECKING, Any, Optional
20
+
21
+ from .engine import IpWare as _V3IpWare
22
+
23
+ if TYPE_CHECKING:
24
+ from typing_extensions import deprecated
25
+ else:
26
+
27
+ def deprecated(_msg): # runtime no-op; the warning is issued in __init__
28
+ return lambda obj: obj
29
+
30
+
31
+ LEGACY_DEPRECATION_MESSAGE = (
32
+ "The legacy engine (algorithm='legacy' / LegacyIpWare) is deprecated and will be "
33
+ "removed in a future major release. Use the default engine: IpWare()."
34
+ )
35
+
36
+ _PACKAGE_DIR = os.path.normcase(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.sep)
37
+
38
+
39
+ def _in_package(filename: str) -> bool:
40
+ return os.path.normcase(os.path.abspath(filename)).startswith(_PACKAGE_DIR)
41
+
42
+
43
+ def _warn_deprecated() -> None:
44
+ # Point the warning at the first caller outside python_ipware, so it is
45
+ # attributed to user code whether it came via IpWare(...) or LegacyIpWare().
46
+ # The walk only aims the warning; it must never stop it from being issued.
47
+ level = 2
48
+ getframe = getattr(sys, "_getframe", None) # CPython/PyPy only
49
+ if getframe is not None:
50
+ frame: Optional[FrameType] = getframe(0)
51
+ level = 1
52
+ while frame is not None and _in_package(frame.f_code.co_filename):
53
+ frame = frame.f_back
54
+ level += 1
55
+ warnings.warn(LEGACY_DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=level)
56
+
57
+
58
+ @deprecated(LEGACY_DEPRECATION_MESSAGE)
59
+ class LegacyIpWare(_V3IpWare):
60
+ """The frozen v3 engine. Deprecated: use ``IpWare()`` (modern)."""
61
+
62
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
63
+ _warn_deprecated()
64
+ super().__init__(*args, **kwargs)
65
+
66
+
67
+ __all__ = ["LEGACY_DEPRECATION_MESSAGE", "LegacyIpWare"]
@@ -1,8 +1,9 @@
1
1
  """Default header precedence for the modern engine.
2
2
 
3
- Superset of the v3 list, adding widely-deployed CDN/edge headers. Headers are
4
- scanned in order; the first one that yields a globally routable IP wins, with
5
- private and then loopback addresses as fallbacks.
3
+ Superset of the v3 list, adding widely-deployed CDN/edge headers. Without
4
+ proxy settings, headers are scanned in order; the first one that yields a
5
+ globally routable IP wins, with private and then loopback addresses as
6
+ fallbacks. With proxy_count / proxy_list, the first header present decides.
6
7
 
7
8
  Ordering rule: existing entries never move. New headers are added only in the
8
9
  block just above ``REMOTE_ADDR``, so a new header can outrank the raw socket
@@ -8,8 +8,10 @@ Same inputs, outputs and proxy semantics as v3, with a better best-match:
8
8
  multicast, broadcast and reserved addresses are never returned.
9
9
  * Without trusted-proxy config, the first *globally routable* hop of a chain
10
10
  wins, not just the first hop, so ``10.0.0.1, 177.139.233.139`` yields the
11
- public address. With ``proxy_count`` / ``proxy_list`` the client position is
12
- fixed by the config, exactly as in v3.
11
+ public address, and headers are scanned in precedence order. With
12
+ ``proxy_count`` / ``proxy_list`` the first header present decides alone and
13
+ the client position is fixed by the config; unlike v3, invalid hops keep
14
+ their position instead of being dropped.
13
15
  * Same ``strict`` semantics for proxy_count / proxy_list validation.
14
16
  * Trusted-proxy matching anchored to the end of the chain. Each ``proxy_list``
15
17
  entry is a CIDR network (``"100.64.0.0/10"``, ``"fd7a:115c:a1e0::/48"``), a
@@ -33,6 +35,7 @@ from .parsers import (
33
35
  IpNetworkType,
34
36
  ip_tier,
35
37
  split_proxy_chain,
38
+ split_proxy_chain_positions,
36
39
  unwrap_ipv4,
37
40
  unwrap_ipv4_network,
38
41
  )
@@ -89,28 +92,53 @@ def _fold(key: str) -> str:
89
92
  return key.upper().replace("-", "_")
90
93
 
91
94
 
95
+ # Marks a folded header whose spellings disagree. It is not text, so the
96
+ # unpinned scan skips it and the pinned path treats it as present but unusable.
97
+ _AMBIGUOUS = object()
98
+
99
+
100
+ def _is_cgi_name(name: str) -> bool:
101
+ """True for CGI / WSGI variable names, which are never sent as header names."""
102
+ return name == "REMOTE_ADDR" or name.startswith("HTTP_")
103
+
104
+
92
105
  def _build_folded(meta: Mapping[Any, Any]) -> dict[str, object]:
93
- """Case- and dash-insensitive view of ``meta`` for lowercase-key adapters.
106
+ """Case-, dash- and underscore-insensitive view of ``meta``.
107
+
108
+ This is the only lookup path, so every spelling of a name is decided
109
+ together and the result never depends on dict order. Keys with a None
110
+ value are ignored, and string values are compared after stripping.
111
+
112
+ Which spellings count depends on the folded name:
94
113
 
95
- When several spellings fold to the same name, the result must not depend
96
- on dict order. Real header names use dashes, while an underscore spelling
97
- in a raw header dict can only come from the client, so dash spellings win.
98
- If several dash spellings disagree, the header is treated as absent.
114
+ * CGI / WSGI variables (``REMOTE_ADDR``, ``HTTP_*``) are set by the server
115
+ or the app, never sent as header names, so only underscore spellings
116
+ count. A client header such as ``Remote-Addr`` cannot replace them.
117
+ * Everything else is a header name. Real header names use dashes, while
118
+ an underscore spelling in a raw header dict can only come from the
119
+ client, so dash spellings win when present.
120
+
121
+ If the counted spellings disagree, the name maps to ``_AMBIGUOUS``.
99
122
  """
100
123
  groups: dict[str, list[tuple[str, object]]] = {}
101
124
  for key, value in meta.items():
102
- if isinstance(key, str):
125
+ if isinstance(key, str) and value is not None:
103
126
  groups.setdefault(_fold(key), []).append((key, value))
104
127
  folded: dict[str, object] = {}
105
128
  for name, items in groups.items():
106
- dashed = [v for k, v in items if "-" in k]
107
- pool = dashed or [v for _, v in items]
129
+ if _is_cgi_name(name):
130
+ pool = [v for k, v in items if "-" not in k]
131
+ if not pool:
132
+ continue
133
+ else:
134
+ dashed = [v for k, v in items if "-" in k]
135
+ pool = dashed or [v for _, v in items]
108
136
  distinct: list[object] = []
109
- for value in pool:
137
+ for raw in pool:
138
+ value = raw.strip() if isinstance(raw, str) else raw
110
139
  if value not in distinct:
111
140
  distinct.append(value)
112
- if len(distinct) == 1:
113
- folded[name] = distinct[0]
141
+ folded[name] = distinct[0] if len(distinct) == 1 else _AMBIGUOUS
114
142
  return folded
115
143
 
116
144
 
@@ -140,7 +168,7 @@ class ModernIpWare:
140
168
  raise ValueError("proxy_list entries must not be empty.")
141
169
  # proxy_count and proxy_list may both be set and may differ (v3 API):
142
170
  # the count is a hop-count requirement (minimum, or exact when strict)
143
- # and the list pins the client position. See _best_from_chain.
171
+ # and the list pins the client position. See _pinned_from_chain.
144
172
  if isinstance(precedence, str) or (
145
173
  precedence is not None and not all(isinstance(h, str) for h in precedence)
146
174
  ):
@@ -155,31 +183,42 @@ class ModernIpWare:
155
183
 
156
184
  # -- meta access --------------------------------------------------------
157
185
 
158
- def _get_meta_values(self, meta: Optional[Mapping[Any, Any]]) -> list[str]:
186
+ def _get_meta_entries(self, meta: Optional[Mapping[Any, Any]]) -> list[Optional[str]]:
187
+ """Present headers in precedence order.
188
+
189
+ Each entry is the stripped text, or None for a header that is present
190
+ but unusable (not text, or spellings that disagree). Absent and
191
+ whitespace-only headers are left out.
192
+ """
159
193
  if meta is None:
160
194
  return []
161
195
  if not isinstance(meta, Mapping):
162
196
  msg = f"meta must be a mapping of header names to values, got {type(meta).__name__}"
163
197
  raise TypeError(msg)
164
198
  folded = _build_folded(meta)
165
- values: list[str] = []
199
+ entries: list[Optional[str]] = []
166
200
  for key in self.precedence:
167
- value = meta.get(key)
168
- if value is None:
169
- value = meta.get(key.replace("_", "-"))
170
- # Exact keys win; the folded view only fills gaps, so lowercase
171
- # keys (AWS Lambda / API Gateway v2, raw ASGI dicts) still match.
201
+ # Every spelling of a header is decided together (case, dash and
202
+ # underscore insensitive), so no single spelling can win outright.
203
+ # WSGI / ASGI / Lambda dicts hold one spelling per header, so this
204
+ # matches exact, lowercase and dashed keys alike.
205
+ value = folded.get(_fold(key))
172
206
  if value is None:
173
- value = folded.get(_fold(key))
174
- # Header values are text; anything else (None, bytes, lists from
175
- # a misbehaving adapter) is ignored rather than crashing.
176
- if isinstance(value, str) and value.strip():
177
- values.append(value.strip())
178
- return values
207
+ continue
208
+ # Header values are text; anything else (bytes, lists from a
209
+ # misbehaving adapter, ambiguous spellings) is unusable, never a crash.
210
+ if not isinstance(value, str):
211
+ entries.append(None)
212
+ elif value.strip():
213
+ entries.append(value.strip())
214
+ return entries
215
+
216
+ def _get_meta_values(self, meta: Optional[Mapping[Any, Any]]) -> list[str]:
217
+ return [v for v in self._get_meta_entries(meta) if v is not None]
179
218
 
180
219
  # -- validation ---------------------------------------------------------
181
220
 
182
- def _proxy_count_valid(self, chain: list[IpAddressType], strict: bool) -> bool:
221
+ def _proxy_count_valid(self, chain: list[OptionalIp], strict: bool) -> bool:
183
222
  if self.proxy_count is None:
184
223
  return True
185
224
  proxies = len(chain) - 1
@@ -187,7 +226,7 @@ class ModernIpWare:
187
226
  return proxies == self.proxy_count
188
227
  return proxies >= self.proxy_count
189
228
 
190
- def _proxy_list_valid(self, chain: list[IpAddressType], strict: bool) -> bool:
229
+ def _proxy_list_valid(self, chain: list[OptionalIp], strict: bool) -> bool:
191
230
  if not self.proxy_list:
192
231
  return True
193
232
  count = len(self.proxy_list)
@@ -197,18 +236,19 @@ class ModernIpWare:
197
236
  return False
198
237
  # Compare the trailing proxies against the trusted entries in order.
199
238
  return all(
200
- _proxy_matches(ip, matcher)
239
+ ip is not None and _proxy_matches(ip, matcher)
201
240
  for ip, matcher in zip(chain[-count:], self._proxy_matchers)
202
241
  )
203
242
 
204
243
  # -- selection ----------------------------------------------------------
205
244
 
206
- def _best_from_chain(self, chain: list[IpAddressType]) -> tuple[OptionalIp, bool]:
245
+ def _pinned_from_chain(self, chain: list[OptionalIp]) -> OptionalIp:
246
+ """Client slot fixed by proxy_list / proxy_count; None if that slot is invalid."""
247
+ count = len(self.proxy_list) if self.proxy_list else (self.proxy_count or 0)
248
+ return chain[-(count + 1)]
249
+
250
+ def _best_from_chain(self, chain: list[IpAddressType]) -> OptionalIp:
207
251
  # ``chain`` is already client-first (see get_client_ip) and non-empty.
208
- if self.proxy_list:
209
- return chain[-(len(self.proxy_list) + 1)], True
210
- if self.proxy_count is not None:
211
- return chain[-(self.proxy_count + 1)], True
212
252
  # No trusted-proxy config, so no position in the chain is verified.
213
253
  # Take the first globally routable hop; otherwise the best-ranked hop,
214
254
  # earliest on ties. This never picks a worse address than v3's chain[0].
@@ -217,40 +257,58 @@ class ModernIpWare:
217
257
  for ip in chain:
218
258
  tier = ip_tier(ip)
219
259
  if tier == TIER_GLOBAL:
220
- return ip, False
260
+ return ip
221
261
  if tier > best_tier:
222
262
  best, best_tier = ip, tier
223
- return best, False
263
+ return best
224
264
 
225
265
  # -- public API ---------------------------------------------------------
226
266
 
227
267
  def get_client_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool = False) -> tuple[OptionalIp, bool]:
228
- # Best non-global candidate so far. Strictly-greater comparison keeps
229
- # the earliest header on ties, preserving header precedence.
268
+ if self.proxy_list or self.proxy_count is not None:
269
+ return self._get_pinned_ip(meta, strict)
270
+
271
+ # No proxy config, so nothing is trusted. Best non-global candidate so
272
+ # far; strictly-greater comparison keeps the earliest header on ties.
230
273
  fallback: OptionalIp = None
231
274
  fallback_tier = TIER_REJECT
232
- fallback_trusted = False
233
-
234
275
  for raw in self._get_meta_values(meta):
235
276
  chain = split_proxy_chain(raw, strict)
236
277
  if not chain:
237
278
  continue
238
- # Put the chain in client-first order ONCE, before any validation, so
239
- # the proxy checks and the client pick look at the same end.
240
279
  if not self.leftmost:
241
280
  chain.reverse()
242
- if not self._proxy_count_valid(chain, strict):
243
- continue
244
- if not self._proxy_list_valid(chain, strict):
245
- continue
246
-
247
- ip, trusted = self._best_from_chain(chain)
281
+ ip = self._best_from_chain(chain)
248
282
  if ip is None:
249
283
  continue
250
284
  tier = ip_tier(ip)
251
285
  if tier == TIER_GLOBAL:
252
- return ip, trusted
286
+ return ip, False
253
287
  if tier > fallback_tier:
254
- fallback, fallback_tier, fallback_trusted = ip, tier, trusted
288
+ fallback, fallback_tier = ip, tier
289
+ return fallback, False
290
+
291
+ def _get_pinned_ip(self, meta: Optional[Mapping[Any, Any]], strict: bool) -> tuple[OptionalIp, bool]:
292
+ """Resolve with proxy_count / proxy_list: the first header present decides.
255
293
 
256
- return fallback, fallback_trusted
294
+ Lower-precedence headers are never consulted once a header is present,
295
+ whether it is usable or validates, and whatever the client's tier.
296
+ Invalid and empty hops keep their position, so they can never shift the
297
+ client slot.
298
+ """
299
+ entries = self._get_meta_entries(meta)
300
+ if not entries or entries[0] is None:
301
+ return None, False
302
+ chain = split_proxy_chain_positions(entries[0], strict)
303
+ if not chain:
304
+ return None, False
305
+ # Client-first order ONCE, before validation, so the proxy checks and
306
+ # the client pick look at the same end.
307
+ if not self.leftmost:
308
+ chain.reverse()
309
+ if not (self._proxy_count_valid(chain, strict) and self._proxy_list_valid(chain, strict)):
310
+ return None, False
311
+ ip = self._pinned_from_chain(chain)
312
+ if ip is None or ip_tier(ip) == TIER_REJECT:
313
+ return None, False
314
+ return ip, True
@@ -115,13 +115,28 @@ def strip_port(value: str) -> str:
115
115
  return value # bare IPv6 or bare IPv4
116
116
 
117
117
 
118
+ def _has_unclosed_quote(value: str) -> bool:
119
+ """True when a double-quoted string in ``value`` is never closed."""
120
+ if '"' not in value:
121
+ return False
122
+ quoted = escaped = False
123
+ for ch in value:
124
+ if escaped:
125
+ escaped = False
126
+ elif quoted and ch == "\\":
127
+ escaped = True
128
+ elif ch == '"':
129
+ quoted = not quoted
130
+ return quoted
131
+
132
+
118
133
  def split_unquoted(value: str, sep: str) -> list[str]:
119
134
  """Split ``value`` on ``sep``, ignoring separators inside double quotes.
120
135
 
121
136
  RFC 7239 values may be quoted strings (``by="a,b"``), and a separator
122
137
  inside one must not start a new hop or parameter. Backslash escapes inside
123
- quotes are honoured. An unclosed quote swallows the rest of the value, so
124
- that token fails to parse instead of leaking a fragment as a fake hop.
138
+ quotes are honoured. An unclosed quote swallows the rest of the value;
139
+ ``split_proxy_chain`` rejects such values before splitting.
125
140
  """
126
141
  if '"' not in value:
127
142
  return value.split(sep)
@@ -206,25 +221,41 @@ def unwrap_ipv4_network(net: IpNetworkType) -> IpNetworkType:
206
221
  return net
207
222
 
208
223
 
209
- def split_proxy_chain(raw: Optional[str], strict: bool = False) -> Optional[list[IpAddressType]]:
210
- """Split a comma-separated proxy chain into ordered ``ip_address`` objects.
224
+ def split_proxy_chain_positions(raw: Optional[str], strict: bool = False) -> Optional[list[Optional[IpAddressType]]]:
225
+ """Split a proxy chain, keeping a ``None`` placeholder for each invalid hop.
211
226
 
212
- Order is preserved left-to-right as it appears in the header. Tokens in
213
- RFC 7239 form (``for=...;proto=...``) are reduced to their ``for`` value;
214
- obfuscated identifiers such as ``for=unknown`` or ``for=_hidden`` are not
215
- IPs and count as invalid. In strict mode, any invalid or empty token makes
216
- the whole chain invalid (returns None), since a malformed header should not
217
- be trusted. Otherwise invalid and empty tokens are skipped.
227
+ Like ``split_proxy_chain`` but positional: an invalid or empty token keeps
228
+ its slot, so counting hops from either end stays aligned with the header.
229
+ Strict mode and an unclosed double quote still reject the whole chain.
218
230
  """
219
231
  if not raw:
220
232
  return []
221
- result: list[IpAddressType] = []
233
+ if _has_unclosed_quote(raw):
234
+ return None
235
+ result: list[Optional[IpAddressType]] = []
222
236
  for token in split_unquoted(raw, ","):
223
237
  # No plain IP token contains "=", only RFC 7239 Forwarded elements do.
224
238
  candidate = forwarded_for(token) if "=" in token else token
225
239
  ip = parse_ip(candidate)
226
- if ip is not None:
227
- result.append(ip)
228
- elif strict:
240
+ if ip is None and strict:
229
241
  return None
242
+ result.append(ip)
230
243
  return result
244
+
245
+
246
+ def split_proxy_chain(raw: Optional[str], strict: bool = False) -> Optional[list[IpAddressType]]:
247
+ """Split a comma-separated proxy chain into ordered ``ip_address`` objects.
248
+
249
+ Order is preserved left-to-right as it appears in the header. Tokens in
250
+ RFC 7239 form (``for=...;proto=...``) are reduced to their ``for`` value;
251
+ obfuscated identifiers such as ``for=unknown`` or ``for=_hidden`` are not
252
+ IPs and count as invalid. In strict mode, any invalid or empty token makes
253
+ the whole chain invalid (returns None), since a malformed header should not
254
+ be trusted. Otherwise invalid and empty tokens are skipped.
255
+
256
+ An unclosed double quote makes the chain invalid in both modes.
257
+ """
258
+ chain = split_proxy_chain_positions(raw, strict)
259
+ if chain is None:
260
+ return None
261
+ return [ip for ip in chain if ip is not None]
@@ -1,6 +1,6 @@
1
1
  """Public ``IpWare`` facade with an algorithm router.
2
2
 
3
- python-ipware 4.x ships two engines:
3
+ python-ipware 4.x and 5.x ship two engines:
4
4
 
5
5
  * ``legacy`` -> the frozen, byte-compatible v3 algorithm.
6
6
  * ``modern`` -> the enhanced v4 algorithm (more headers, hardened parsing).
@@ -8,18 +8,19 @@ python-ipware 4.x ships two engines:
8
8
  The ``algorithm`` selector chooses between them. ``"auto"`` (the default) is a
9
9
  clean alias for ``"modern"`` — the enhanced engine is where development moves
10
10
  forward. It passes the full v3 suite, and a differential test checks it never
11
- returns a worse address than v3. It picks better where v3 did not: a public
11
+ returns a worse address than v3 for a single well-formed header. It picks better where v3 did not: a public
12
12
  hop behind a private first hop, no multicast / unspecified results, and
13
13
  ``trusted_route`` for private clients behind trusted proxies (see CHANGELOG).
14
14
  ``legacy`` remains available as an explicit escape hatch for projects that
15
- need byte-for-byte v3 behavior. There is no silent runtime fallback, so
16
- behavior stays predictable.
15
+ need byte-for-byte v3 behavior, but it is deprecated: selecting it emits a
16
+ ``DeprecationWarning``, and it will be removed in a future major release.
17
+ There is no silent runtime fallback, so behavior stays predictable.
17
18
 
18
19
  from python_ipware import IpWare
19
20
 
20
21
  IpWare() # auto -> modern (the forward-moving default)
21
22
  IpWare(algorithm="modern") # explicit modern
22
- IpWare(algorithm="legacy") # frozen v3 behavior (escape hatch)
23
+ IpWare(algorithm="legacy") # frozen v3 behavior (deprecated escape hatch)
23
24
  """
24
25
 
25
26
  from typing import Literal, Optional
@@ -52,6 +53,7 @@ class IpWare:
52
53
  resolved = "modern" if algorithm == "auto" else algorithm
53
54
  self.resolved_algorithm = resolved
54
55
 
56
+ self._impl: "LegacyIpWare | ModernIpWare"
55
57
  if resolved == "legacy":
56
58
  self._impl = LegacyIpWare(
57
59
  precedence=precedence,
@@ -16,6 +16,7 @@ from __future__ import annotations
16
16
  import functools
17
17
  import sys
18
18
  import unittest
19
+ import warnings
19
20
 
20
21
  from python_ipware import IpWare
21
22
 
@@ -23,6 +24,9 @@ from . import tests_ipv4, tests_ipv6
23
24
 
24
25
  LegacyBound = functools.partial(IpWare, algorithm="legacy")
25
26
 
27
+ # The legacy engine is deprecated; this runner exercises it on purpose.
28
+ warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning)
29
+
26
30
 
27
31
  def build_suite() -> unittest.TestSuite:
28
32
  # Rebind the IpWare symbol the untouched test modules use.
@@ -4,15 +4,28 @@ exhaustive matrices in tests_modern_matrix.py cannot reach."""
4
4
 
5
5
  import ipaddress
6
6
  import unittest
7
+ import warnings
7
8
  from typing import ClassVar
8
9
 
9
10
  from python_ipware import IpWare
10
- from python_ipware.modern.parsers import TIER_PRIVATE, TIER_REJECT, ip_tier, split_proxy_chain, split_unquoted
11
+ from python_ipware.modern.parsers import (
12
+ TIER_PRIVATE,
13
+ TIER_REJECT,
14
+ _has_unclosed_quote,
15
+ ip_tier,
16
+ split_proxy_chain,
17
+ split_unquoted,
18
+ )
11
19
 
12
20
  ip = ipaddress.ip_address
13
21
  CLIENT = ip("8.8.8.8")
14
22
 
15
23
 
24
+ def setUpModule():
25
+ # Legacy is deprecated; the few comparisons against it here are on purpose.
26
+ warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning)
27
+
28
+
16
29
  def trusted_via(proxy_entry, hop, strict=True):
17
30
  """Resolve ``8.8.8.8, <hop>`` with a single trusted proxy entry."""
18
31
  meta = {"HTTP_X_FORWARDED_FOR": f"8.8.8.8, {hop}"}
@@ -224,9 +237,9 @@ class TestForwardedQuoting(unittest.TestCase):
224
237
  meta = {"HTTP_FORWARDED": 'for=8.8.4.4;by="_a,9.9.9.9"'}
225
238
  self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (None, False))
226
239
 
227
- def test_unclosed_quote_swallows_the_rest(self):
240
+ def test_unclosed_quote_rejects_the_header(self):
228
241
  meta = {"HTTP_FORWARDED": 'for=8.8.8.8, for="6.6.6.6, for=9.9.9.9'}
229
- self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False))
242
+ self.assertEqual(IpWare().get_client_ip(meta), (None, False))
230
243
  self.assertEqual(IpWare().get_client_ip(meta, strict=True), (None, False))
231
244
 
232
245
  def test_split_unquoted_helper(self):
@@ -234,6 +247,165 @@ class TestForwardedQuoting(unittest.TestCase):
234
247
  self.assertEqual(split_unquoted('a,"b,c",d', ","), ["a", '"b,c"', "d"])
235
248
  self.assertEqual(split_unquoted('"a\\",b",c', ","), ['"a\\",b"', "c"])
236
249
  self.assertEqual(split_unquoted("", ","), [""])
250
+ self.assertEqual(split_unquoted('a,"b,c', ","), ["a", '"b,c']) # unchanged helper contract
251
+
252
+ def test_unclosed_quote_detection(self):
253
+ self.assertTrue(_has_unclosed_quote('a,"b,c'))
254
+ self.assertTrue(_has_unclosed_quote('a,"b\\"')) # escaped quote does not close
255
+ self.assertFalse(_has_unclosed_quote('a,"b,c",d'))
256
+ self.assertFalse(_has_unclosed_quote("a,b"))
257
+
258
+ def test_split_proxy_chain_rejects_unclosed_quote(self):
259
+ for strict in (False, True):
260
+ with self.subTest(strict=strict):
261
+ self.assertIsNone(split_proxy_chain('9.9.9.9, ", 8.8.8.8', strict))
262
+
263
+
264
+ class TestMalformedQuoting(unittest.TestCase):
265
+ """Malformed quoting in a client-supplied prefix is rejected, not repaired."""
266
+
267
+ REAL = "203.0.113.7" # true client, appended by the edge proxy
268
+ HOP = "198.51.100.10" # trusted proxy, appended by the inner proxy
269
+
270
+ def resolve(self, prefix, strict=False, header="HTTP_X_FORWARDED_FOR", **kw):
271
+ meta = {header: f"{prefix}, {self.REAL}, {self.HOP}"}
272
+ return IpWare(**kw).get_client_ip(meta, strict=strict)
273
+
274
+ def test_control_forged_prefix_is_ignored(self):
275
+ self.assertEqual(self.resolve("9.9.9.9", proxy_count=1), (ip(self.REAL), True))
276
+ self.assertEqual(self.resolve("9.9.9.9", proxy_list=[self.HOP]), (ip(self.REAL), True))
277
+
278
+ def test_unclosed_quote_proxy_count(self):
279
+ for strict in (False, True):
280
+ with self.subTest(strict=strict):
281
+ self.assertEqual(self.resolve('9.9.9.9, 7.7.7.7, "', strict, proxy_count=1), (None, False))
282
+
283
+ def test_unclosed_quote_proxy_list(self):
284
+ prefix = f'9.9.9.9, {self.HOP}, "'
285
+ for strict in (False, True):
286
+ with self.subTest(strict=strict):
287
+ self.assertEqual(self.resolve(prefix, strict, proxy_list=[self.HOP]), (None, False))
288
+
289
+ def test_unclosed_quote_rightmost(self):
290
+ self.assertEqual(self.resolve('9.9.9.9, 7.7.7.7, "', proxy_count=1, leftmost=False), (None, False))
291
+
292
+ def test_unclosed_quote_forwarded_header(self):
293
+ meta = {"HTTP_FORWARDED": f'for=9.9.9.9, for=7.7.7.7, for=", for={self.REAL}, for="[2001:db8::1]:4711"'}
294
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (None, False))
295
+
296
+ def test_falls_back_to_next_header(self):
297
+ meta = {"HTTP_X_FORWARDED_FOR": f'9.9.9.9, ", {self.REAL}', "REMOTE_ADDR": self.REAL}
298
+ self.assertEqual(IpWare().get_client_ip(meta), (ip(self.REAL), False))
299
+
300
+ def test_rejected_header_does_not_fall_through(self):
301
+ meta = {"HTTP_X_FORWARDED_FOR": f'", {self.REAL}, {self.HOP}', "HTTP_CLIENT_IP": "9.9.9.9, 7.7.7.7"}
302
+ for strict in (False, True):
303
+ with self.subTest(strict=strict):
304
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta, strict), (None, False))
305
+
306
+ def test_strict_junk_does_not_fall_through(self):
307
+ meta = {"HTTP_X_FORWARDED_FOR": f"junk, 8.8.4.4, {self.HOP}", "HTTP_CLIENT_IP": "9.9.9.9, 7.7.7.7"}
308
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta, strict=True), (None, False))
309
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("8.8.4.4"), True))
310
+
311
+ def test_private_client_is_final(self):
312
+ meta = {"HTTP_X_FORWARDED_FOR": f"10.1.2.3, {self.HOP}", "HTTP_CLIENT_IP": "9.9.9.9, 7.7.7.7"}
313
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("10.1.2.3"), True))
314
+ self.assertEqual(IpWare(proxy_list=[self.HOP]).get_client_ip(meta), (ip("10.1.2.3"), True))
315
+
316
+ def test_unusable_first_header_does_not_fall_through(self):
317
+ forged = {"Client-IP": f"9.9.9.9, {self.HOP}"}
318
+ metas = {
319
+ "disagreeing spellings": {"x-forwarded-for": "junk", "X-Forwarded-For": f"{self.REAL}, {self.HOP}"},
320
+ "non-text value": {"HTTP_X_FORWARDED_FOR": [f"{self.REAL}, {self.HOP}"]},
321
+ "exact-hit case variant": {"X-FORWARDED-FOR": "6.6.6.6", "X-Forwarded-For": f"{self.REAL}, {self.HOP}"},
322
+ "blank dashed variant": {"X-FORWARDED-FOR": " ", "X-Forwarded-For": f"{self.REAL}, {self.HOP}"},
323
+ }
324
+ for name, meta in metas.items():
325
+ for kw in ({"proxy_count": 1}, {"proxy_list": [self.HOP]}):
326
+ with self.subTest(case=name, **kw):
327
+ self.assertEqual(IpWare(**kw).get_client_ip({**meta, **forged}), (None, False))
328
+
329
+ def test_dashed_spelling_beats_underscore_spelling(self):
330
+ cases = {
331
+ "underscore exact hit": {"X_FORWARDED_FOR": "9.9.9.9, 7.7.7.7"},
332
+ "blank underscore exact hit": {"X_FORWARDED_FOR": " ", "Client-IP": "9.9.9.9, 7.7.7.7"},
333
+ }
334
+ for name, extra in cases.items():
335
+ meta = {**extra, "X-Forwarded-For": f"{self.REAL}, {self.HOP}"}
336
+ for kw in ({"proxy_count": 1}, {"proxy_list": [self.HOP]}):
337
+ with self.subTest(case=name, **kw):
338
+ self.assertEqual(IpWare(**kw).get_client_ip(meta), (ip(self.REAL), True))
339
+
340
+ def test_client_header_cannot_replace_cgi_variable(self):
341
+ cases = [
342
+ ({"remote-addr": "9.9.9.9", "REMOTE_ADDR": self.REAL}, {"precedence": ("REMOTE_ADDR",)}, False),
343
+ (
344
+ {"Remote-Addr": "9.9.9.9", "REMOTE_ADDR": self.REAL},
345
+ {"precedence": ("REMOTE_ADDR",), "proxy_count": 0},
346
+ True,
347
+ ),
348
+ ({"remote-addr": " ", "REMOTE_ADDR": self.REAL}, {}, False),
349
+ ]
350
+ for meta, kw, trusted in cases:
351
+ with self.subTest(meta=meta, **kw):
352
+ self.assertEqual(IpWare(**kw).get_client_ip(meta), (ip(self.REAL), trusted))
353
+ meta = {"Http-X-Forwarded-For": f"9.9.9.9, {self.HOP}", "HTTP_X_FORWARDED_FOR": f"{self.REAL}, {self.HOP}"}
354
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip(self.REAL), True))
355
+
356
+ def test_dashed_only_cgi_name_is_absent(self):
357
+ meta = {"Remote-Addr": "9.9.9.9"}
358
+ self.assertEqual(IpWare().get_client_ip(meta), (None, False))
359
+
360
+ def test_unusable_header_still_skipped_without_proxy_config(self):
361
+ meta = {"x-forwarded-for": "6.6.6.6", "X-Forwarded-For": "7.7.7.7", "REMOTE_ADDR": "8.8.8.8"}
362
+ self.assertEqual(IpWare().get_client_ip(meta), (CLIENT, False))
363
+
364
+ def test_empty_hops_keep_their_position(self):
365
+ meta = {"HTTP_X_FORWARDED_FOR": "9.9.9.9, 8.8.4.4, "}
366
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("8.8.4.4"), True))
367
+
368
+ def test_lower_header_unused_when_first_is_present(self):
369
+ meta = {"HTTP_X_REAL_IP": "8.8.4.4", "REMOTE_ADDR": f"9.9.9.9, {self.HOP}"}
370
+ ipw = IpWare(precedence=("HTTP_X_REAL_IP", "REMOTE_ADDR"), proxy_count=1)
371
+ self.assertEqual(ipw.get_client_ip(meta), (None, False))
372
+
373
+ def test_invalid_hops_keep_their_position(self):
374
+ cases = {
375
+ "HTTP_X_FORWARDED_FOR": "9.9.9.9, 8.8.4.4, unknown",
376
+ "HTTP_FORWARDED": "for=9.9.9.9, for=8.8.4.4, for=_hidden",
377
+ }
378
+ for header, raw in cases.items():
379
+ with self.subTest(header=header):
380
+ # The appended invalid hop is the proxy slot; the client is 8.8.4.4.
381
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip({header: raw}), (ip("8.8.4.4"), True))
382
+ meta = {"HTTP_FORWARDED": "for=9.9.9.9, for=8.8.4.4, proto=https;by=_edge"}
383
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (ip("8.8.4.4"), True))
384
+
385
+ def test_invalid_client_slot_is_none(self):
386
+ meta = {"HTTP_X_FORWARDED_FOR": f"9.9.9.9, unknown, {self.HOP}"}
387
+ self.assertEqual(IpWare(proxy_count=1).get_client_ip(meta), (None, False))
388
+ self.assertEqual(IpWare(proxy_list=[self.HOP]).get_client_ip(meta), (None, False))
389
+
390
+ def test_invalid_trusted_slot_fails_proxy_list(self):
391
+ meta = {"HTTP_X_FORWARDED_FOR": "9.9.9.9, 8.8.4.4, unknown"}
392
+ self.assertEqual(IpWare(proxy_list=[self.HOP]).get_client_ip(meta), (None, False))
393
+
394
+ def test_client_prefix_never_wins(self):
395
+ """With proxy_count=n the answer is never drawn from the client prefix."""
396
+ forged = ["9.9.9.9", "7.7.7.7", "1.1.1.1"]
397
+ tails = ['"', '"\\', '" ', 'x"', '"a""', 'for="', '"[', '"9.9.9.9']
398
+ for n in range(1, 4):
399
+ for k in range(0, 4):
400
+ for tail in tails:
401
+ prefix = ", ".join([*forged[:k], tail])
402
+ for strict in (False, True):
403
+ for leftmost in (True, False):
404
+ with self.subTest(n=n, prefix=prefix, strict=strict, leftmost=leftmost):
405
+ hops = [f"198.51.100.{i}" for i in range(1, n + 1)]
406
+ meta = {"HTTP_X_FORWARDED_FOR": ", ".join([prefix, self.REAL, *hops])}
407
+ got, _ = IpWare(proxy_count=n, leftmost=leftmost).get_client_ip(meta, strict=strict)
408
+ self.assertNotIn(str(got), forged)
237
409
 
238
410
  def test_split_proxy_chain_empty(self):
239
411
  self.assertEqual(split_proxy_chain(""), [])
@@ -22,6 +22,7 @@ import ipaddress
22
22
  import itertools
23
23
  import random
24
24
  import unittest
25
+ import warnings
25
26
  from typing import ClassVar, Optional
26
27
 
27
28
  from python_ipware import IpWare
@@ -34,6 +35,12 @@ from python_ipware.modern.parsers import (
34
35
  ip_tier,
35
36
  )
36
37
 
38
+
39
+ def setUpModule():
40
+ # Legacy is deprecated; this suite compares against it on purpose.
41
+ warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning)
42
+
43
+
37
44
  G, P, LL, LB, REJ = TIER_GLOBAL, TIER_PRIVATE, TIER_LINK_LOCAL, TIER_LOOPBACK, TIER_REJECT
38
45
 
39
46
  # 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):
94
101
  """Reference model of the documented modern algorithm.
95
102
 
96
103
  ``raw_values`` are header values already in precedence order.
104
+
105
+ With proxy_count / proxy_list the first present header decides alone, and
106
+ invalid hops keep their position (they are never skipped).
97
107
  """
98
108
  configured = proxy_count is not None or bool(proxy_list)
109
+ if configured:
110
+ return _pinned_oracle(raw_values, leftmost, proxy_count, proxy_list, strict)
99
111
  best = None # (address, tier, trusted); first header wins ties
100
112
  for raw in raw_values:
101
113
  hops = [TRUTH[t.strip()] for t in raw.split(",")]
@@ -106,32 +118,43 @@ def _oracle(raw_values, leftmost, proxy_count, proxy_list, strict):
106
118
  chain.reverse()
107
119
  if not chain:
108
120
  continue
109
- proxies = len(chain) - 1
110
- if proxy_count is not None and (proxies < proxy_count or (strict and proxies != proxy_count)):
111
- continue
112
- if proxy_list:
113
- n = len(proxy_list)
114
- if proxies < n or (strict and proxies != n):
115
- continue
116
- if not all(_proxy_ok(addr, pat) for (addr, _), pat in zip(chain[-n:], proxy_list)):
117
- continue
118
- if configured:
119
- n = len(proxy_list) if proxy_list else proxy_count
120
- address, tier = chain[-(n + 1)]
121
- else:
122
- globals_ = [h for h in chain if h[1] == G]
123
- address, tier = globals_[0] if globals_ else max(chain, key=lambda h: h[1])
121
+ globals_ = [h for h in chain if h[1] == G]
122
+ address, tier = globals_[0] if globals_ else max(chain, key=lambda h: h[1])
124
123
  if tier == REJ:
125
124
  continue
126
125
  if tier == G:
127
- return ipaddress.ip_address(address), configured
126
+ return ipaddress.ip_address(address), False
128
127
  if best is None or tier > best[1]:
129
- best = (address, tier, configured)
128
+ best = (address, tier, False)
130
129
  if best is None:
131
130
  return None, False
132
131
  return ipaddress.ip_address(best[0]), best[2]
133
132
 
134
133
 
134
+ def _pinned_oracle(raw_values, leftmost, proxy_count, proxy_list, strict):
135
+ if not raw_values:
136
+ return None, False
137
+ chain = [TRUTH[t.strip()] for t in raw_values[0].split(",")] # None marks an invalid hop
138
+ if strict and any(h is None for h in chain):
139
+ return None, False
140
+ if not leftmost:
141
+ chain.reverse()
142
+ proxies = len(chain) - 1
143
+ if proxy_count is not None and (proxies < proxy_count or (strict and proxies != proxy_count)):
144
+ return None, False
145
+ if proxy_list:
146
+ n = len(proxy_list)
147
+ if proxies < n or (strict and proxies != n):
148
+ return None, False
149
+ if not all(h is not None and _proxy_ok(h[0], pat) for h, pat in zip(chain[-n:], proxy_list)):
150
+ return None, False
151
+ n = len(proxy_list) if proxy_list else proxy_count
152
+ hop = chain[-(n + 1)]
153
+ if hop is None or hop[1] == REJ:
154
+ return None, False
155
+ return ipaddress.ip_address(hop[0]), True
156
+
157
+
135
158
  class TestTierTable(unittest.TestCase):
136
159
  """The ranking every other test relies on, checked against the labels."""
137
160
 
@@ -277,6 +300,10 @@ class TestNeverWorseThanLegacy(unittest.TestCase):
277
300
  meta = {"HTTP_X_FORWARDED_FOR": ", ".join(hops)}
278
301
  for proxy_count, proxy_list in CONFIGS:
279
302
  configured = proxy_count is not None or bool(proxy_list)
303
+ # Legacy drops invalid hops, which shifts the pinned client slot;
304
+ # modern keeps their position, so those answers differ on purpose.
305
+ if configured and "unknown" in hops:
306
+ continue
280
307
  for leftmost in (True, False):
281
308
  kw = {"leftmost": leftmost, "proxy_count": proxy_count, "proxy_list": proxy_list}
282
309
  legacy, modern = IpWare(algorithm="legacy", **kw), IpWare(**kw)
@@ -1,15 +1,54 @@
1
1
  import ipaddress
2
2
  import logging
3
+ import sys
3
4
  import unittest
5
+ import warnings
4
6
  from typing import ClassVar
7
+ from unittest import mock
5
8
 
6
9
  from python_ipware import IpWare, LegacyIpWare, ModernIpWare
10
+ from python_ipware.legacy import LEGACY_DEPRECATION_MESSAGE
7
11
  from python_ipware.modern.defaults import DEFAULT_PRECEDENCE
8
12
  from python_ipware.modern.parsers import TIER_GLOBAL, TIER_REJECT, ip_tier
9
13
 
10
14
  logging.disable(logging.CRITICAL)
11
15
 
12
16
 
17
+ def setUpModule():
18
+ # Legacy is deprecated; tests that compare against it on purpose stay quiet.
19
+ # Set inside the run (unittest resets filters first); assertWarns still sees it.
20
+ warnings.filterwarnings("ignore", message=r"The legacy engine", category=DeprecationWarning)
21
+
22
+
23
+ class TestLegacyDeprecation(unittest.TestCase):
24
+ def test_router_legacy_warns_at_caller(self):
25
+ with self.assertWarns(DeprecationWarning) as cm:
26
+ IpWare(algorithm="legacy")
27
+ self.assertEqual(str(cm.warning), LEGACY_DEPRECATION_MESSAGE)
28
+ self.assertEqual(cm.filename, __file__)
29
+
30
+ def test_direct_legacy_warns_at_caller(self):
31
+ with self.assertWarns(DeprecationWarning) as cm:
32
+ LegacyIpWare()
33
+ self.assertEqual(cm.filename, __file__)
34
+
35
+ def test_modern_does_not_warn(self):
36
+ with warnings.catch_warnings():
37
+ warnings.simplefilter("error")
38
+ IpWare()
39
+ IpWare(algorithm="modern")
40
+
41
+ def test_warning_issued_without_getframe(self):
42
+ with mock.patch.object(sys, "_getframe", None), self.assertWarns(DeprecationWarning):
43
+ LegacyIpWare()
44
+
45
+ def test_legacy_still_works(self):
46
+ with warnings.catch_warnings():
47
+ warnings.simplefilter("ignore", DeprecationWarning)
48
+ ipw = IpWare(algorithm="legacy")
49
+ self.assertEqual(ipw.get_client_ip({"REMOTE_ADDR": "8.8.8.8"})[0].exploded, "8.8.8.8")
50
+
51
+
13
52
  class TestAlgorithmRouter(unittest.TestCase):
14
53
  def test_default_is_auto_modern(self):
15
54
  ipw = IpWare()
@@ -309,10 +348,12 @@ class TestModernMetaHardening(unittest.TestCase):
309
348
  ip, _ = IpWare().get_client_ip(meta)
310
349
  self.assertEqual(str(ip), "203.0.113.70")
311
350
 
312
- def test_exact_key_beats_folded_key(self):
351
+ def test_dashed_spelling_beats_underscore_spelling(self):
352
+ # Real header names use dashes; an underscore spelling can only come
353
+ # from the client, so it never outranks the dashed header.
313
354
  meta = {"X_FORWARDED_FOR": "203.0.113.71", "x-forwarded-for": "203.0.113.72"}
314
355
  ip, _ = IpWare().get_client_ip(meta)
315
- self.assertEqual(str(ip), "203.0.113.71")
356
+ self.assertEqual(str(ip), "203.0.113.72")
316
357
 
317
358
  def test_empty_proxy_entry_raises(self):
318
359
  for plist in ([""], [" "], ["10.0.0.", ""]):
@@ -417,6 +458,10 @@ class TestModernDominatesLegacy(unittest.TestCase):
417
458
  for plist in self.PROXY_LISTS:
418
459
  kw = {"leftmost": leftmost, "proxy_count": count, "proxy_list": plist}
419
460
  configured = count is not None or bool(plist)
461
+ # Legacy drops invalid hops, shifting the pinned slot;
462
+ # modern keeps their position, so these differ on purpose.
463
+ if configured and "not-an-ip" in raw:
464
+ continue
420
465
  legacy = IpWare(algorithm="legacy", **kw)
421
466
  modern = IpWare(algorithm="modern", **kw)
422
467
  for strict in (False, True):
@@ -431,7 +476,7 @@ class TestModernDominatesLegacy(unittest.TestCase):
431
476
  self.assertEqual(m_trusted, l_trusted or (configured and m_ip is not None))
432
477
  checked += 1
433
478
  improved += (m_ip, m_trusted) != (l_ip, l_trusted)
434
- self.assertGreater(checked, 3000)
479
+ self.assertGreater(checked, 2800)
435
480
  self.assertGreater(improved, 0) # the matrix really exercises the new ranking
436
481
 
437
482
 
@@ -1 +0,0 @@
1
- __version__ = "4.1.1"
@@ -1,12 +0,0 @@
1
- """Frozen v3 algorithm.
2
-
3
- This subpackage preserves the exact behavior of python-ipware 3.x. It is kept
4
- byte-for-byte stable so that projects upgrading to 4.x can pin
5
- ``algorithm="legacy"`` and get identical results to what they had before.
6
-
7
- Do not "improve" this module. New behavior belongs in ``python_ipware.modern``.
8
- """
9
-
10
- from .engine import IpWare as LegacyIpWare
11
-
12
- __all__ = ["LegacyIpWare"]
File without changes
File without changes