python-ipware 4.1.1__py3-none-any.whl → 5.0.0__py3-none-any.whl
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.
- python_ipware/__version__.py +1 -1
- python_ipware/legacy/README.md +2 -0
- python_ipware/legacy/__init__.py +59 -4
- python_ipware/modern/defaults.py +4 -3
- python_ipware/modern/engine.py +110 -52
- python_ipware/modern/parsers.py +45 -14
- python_ipware/router.py +7 -5
- {python_ipware-4.1.1.dist-info → python_ipware-5.0.0.dist-info}/METADATA +28 -14
- python_ipware-5.0.0.dist-info/RECORD +15 -0
- {python_ipware-4.1.1.dist-info → python_ipware-5.0.0.dist-info}/WHEEL +1 -1
- python_ipware-4.1.1.dist-info/RECORD +0 -15
- {python_ipware-4.1.1.dist-info → python_ipware-5.0.0.dist-info}/licenses/LICENSE +0 -0
python_ipware/__version__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "
|
|
1
|
+
__version__ = "5.0.0"
|
python_ipware/legacy/README.md
CHANGED
|
@@ -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
|
python_ipware/legacy/__init__.py
CHANGED
|
@@ -1,12 +1,67 @@
|
|
|
1
|
-
"""Frozen v3 algorithm.
|
|
1
|
+
"""Frozen v3 algorithm (deprecated).
|
|
2
2
|
|
|
3
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
|
|
4
|
+
byte-for-byte stable so that projects upgrading to 4.x or 5.x can pin
|
|
5
5
|
``algorithm="legacy"`` and get identical results to what they had before.
|
|
6
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
|
+
|
|
7
12
|
Do not "improve" this module. New behavior belongs in ``python_ipware.modern``.
|
|
8
13
|
"""
|
|
9
14
|
|
|
10
|
-
|
|
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
|
+
|
|
11
66
|
|
|
12
|
-
__all__ = ["LegacyIpWare"]
|
|
67
|
+
__all__ = ["LEGACY_DEPRECATION_MESSAGE", "LegacyIpWare"]
|
python_ipware/modern/defaults.py
CHANGED
|
@@ -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.
|
|
4
|
-
scanned in order; the first one that yields a
|
|
5
|
-
private and then loopback addresses as
|
|
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
|
python_ipware/modern/engine.py
CHANGED
|
@@ -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
|
|
12
|
-
|
|
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
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
-
|
|
107
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
199
|
+
entries: list[Optional[str]] = []
|
|
166
200
|
for key in self.precedence:
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
#
|
|
171
|
-
|
|
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
|
-
|
|
174
|
-
# Header values are text; anything else (
|
|
175
|
-
#
|
|
176
|
-
if isinstance(value, str)
|
|
177
|
-
|
|
178
|
-
|
|
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[
|
|
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[
|
|
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
|
|
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
|
|
260
|
+
return ip
|
|
221
261
|
if tier > best_tier:
|
|
222
262
|
best, best_tier = ip, tier
|
|
223
|
-
return best
|
|
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
|
-
|
|
229
|
-
|
|
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
|
-
|
|
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,
|
|
286
|
+
return ip, False
|
|
253
287
|
if tier > fallback_tier:
|
|
254
|
-
fallback, fallback_tier
|
|
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
|
-
|
|
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
|
python_ipware/modern/parsers.py
CHANGED
|
@@ -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
|
|
124
|
-
|
|
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
|
|
210
|
-
"""Split a
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
-
|
|
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
|
|
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]
|
python_ipware/router.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Public ``IpWare`` facade with an algorithm router.
|
|
2
2
|
|
|
3
|
-
python-ipware 4.x
|
|
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
|
|
16
|
-
|
|
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,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: python-ipware
|
|
3
|
-
Version:
|
|
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
|
-
>
|
|
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
|
-
|
|
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,
|
|
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|
|
|
178
|
-
|
|
179
|
-
E -->|no|
|
|
180
|
-
E -->|yes| F["
|
|
181
|
-
|
|
182
|
-
|
|
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
|
|
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
|
-
[
|
|
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
|
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
python_ipware/__init__.py,sha256=BuZ3sY_v_GTeXmATXqNc_GqRGVDLGP0mj8pWj_StKrA,199
|
|
2
|
+
python_ipware/__version__.py,sha256=DgiwC5i6Qn9S9SAS5v73GdLwuTrTF6Uxx0LBYewmzI8,22
|
|
3
|
+
python_ipware/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
python_ipware/router.py,sha256=cPBuxQUjMjvTibxygMNelpiRmMnEpTTyKi3u6wUdTuA,3314
|
|
5
|
+
python_ipware/legacy/README.md,sha256=ayGJ24ci4Y3szcT_hbf8_GPfL10sUvvRP02525JsD5c,14669
|
|
6
|
+
python_ipware/legacy/__init__.py,sha256=4zRwsYqA3kYJxIvKNbinusQgBC9IEIpUJxVfUNpAOBY,2395
|
|
7
|
+
python_ipware/legacy/engine.py,sha256=IotMZQIGSOu2XCbmdYH4WuhBvXm-lJVJHe3FXylSMvc,12725
|
|
8
|
+
python_ipware/modern/__init__.py,sha256=uzxoWK47NOaeYVizW2-G7pQSXzQ1Zq9fSu2kru9sR70,109
|
|
9
|
+
python_ipware/modern/defaults.py,sha256=RGLhejE1fjXyVUq8MPmLFQlVZUTOieYvP79hCsK_zPo,2121
|
|
10
|
+
python_ipware/modern/engine.py,sha256=syaQyuM_EOiGQIEl-3vXnyPUfWZt-dgS5sK8MSMKleA,13697
|
|
11
|
+
python_ipware/modern/parsers.py,sha256=J6nXLEuvxZUCeaXWS_Rr4HJT_bpiemhDa6gN-Uv5MdU,10066
|
|
12
|
+
python_ipware-5.0.0.dist-info/METADATA,sha256=-l6VANbfb2ekBz0sQrWdSEmbT1_j5irVtVqU8YDlMLA,16847
|
|
13
|
+
python_ipware-5.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
python_ipware-5.0.0.dist-info/licenses/LICENSE,sha256=MLpNxpqfTc4TLdcDk3x6k7Vz4lJGBNLV-SxQZlFMDU8,1103
|
|
15
|
+
python_ipware-5.0.0.dist-info/RECORD,,
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
python_ipware/__init__.py,sha256=BuZ3sY_v_GTeXmATXqNc_GqRGVDLGP0mj8pWj_StKrA,199
|
|
2
|
-
python_ipware/__version__.py,sha256=NtWqZUv_8plp1gndoYX_eAqe7K65oPMh-hIvB4Evdc8,22
|
|
3
|
-
python_ipware/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
-
python_ipware/router.py,sha256=ZLEBbBW3xoOfrvwFfBx_V8Bp2rF1tA1jAEjSY5Rnbqo,3097
|
|
5
|
-
python_ipware/legacy/README.md,sha256=h33u11bhkvmU3IJMnPE0p6lXI3f6QiYN1RrI3eIFHsk,14519
|
|
6
|
-
python_ipware/legacy/__init__.py,sha256=NuIwZ_yvPVJudz4WttTc9piiPlvxAlS1iooRyX2Kc1w,397
|
|
7
|
-
python_ipware/legacy/engine.py,sha256=IotMZQIGSOu2XCbmdYH4WuhBvXm-lJVJHe3FXylSMvc,12725
|
|
8
|
-
python_ipware/modern/__init__.py,sha256=uzxoWK47NOaeYVizW2-G7pQSXzQ1Zq9fSu2kru9sR70,109
|
|
9
|
-
python_ipware/modern/defaults.py,sha256=pZkXt6iMVUwfklpBzFQFF36Xd2n1_8Xej7VViBW3spY,2032
|
|
10
|
-
python_ipware/modern/engine.py,sha256=7CQL7O9z4dY85k_YmoyW4TxDjtdHODKS9wIZz2Amnjw,10942
|
|
11
|
-
python_ipware/modern/parsers.py,sha256=P2ZLdMGB1CqPKI0y8EM1jRtougATzu_7i9y6lz9U4ic,8978
|
|
12
|
-
python_ipware-4.1.1.dist-info/METADATA,sha256=Hqt9b48DczV_PBemNGnwH-dIShI9VCTabnZOM10DSLY,15650
|
|
13
|
-
python_ipware-4.1.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
14
|
-
python_ipware-4.1.1.dist-info/licenses/LICENSE,sha256=MLpNxpqfTc4TLdcDk3x6k7Vz4lJGBNLV-SxQZlFMDU8,1103
|
|
15
|
-
python_ipware-4.1.1.dist-info/RECORD,,
|
|
File without changes
|