python-ipware 4.1.0__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.
- {python_ipware-4.1.0 → python_ipware-5.0.0}/.gitignore +4 -1
- {python_ipware-4.1.0 → python_ipware-5.0.0}/CHANGELOG.md +19 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/PKG-INFO +28 -14
- {python_ipware-4.1.0 → python_ipware-5.0.0}/README.md +27 -13
- python_ipware-5.0.0/python_ipware/__version__.py +1 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/legacy/README.md +2 -0
- python_ipware-5.0.0/python_ipware/legacy/__init__.py +67 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/modern/defaults.py +4 -3
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/modern/engine.py +110 -52
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/modern/parsers.py +67 -16
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/router.py +7 -5
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/legacy/run_against_legacy.py +4 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/tests_modern_config.py +175 -3
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/tests_modern_matrix.py +44 -17
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/tests_router.py +120 -3
- python_ipware-4.1.0/python_ipware/__version__.py +0 -1
- python_ipware-4.1.0/python_ipware/legacy/__init__.py +0 -12
- {python_ipware-4.1.0 → python_ipware-5.0.0}/LICENSE +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/SECURITY.md +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/pyproject.toml +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/__init__.py +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/legacy/engine.py +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/modern/__init__.py +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/python_ipware/py.typed +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/__init__.py +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/legacy/__init__.py +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/legacy/tests_ipv4.py +0 -0
- {python_ipware-4.1.0 → python_ipware-5.0.0}/tests/legacy/tests_ipv6.py +0 -0
|
@@ -1,3 +1,22 @@
|
|
|
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
|
+
|
|
12
|
+
## 4.1.1
|
|
13
|
+
|
|
14
|
+
Reported privately by David Gilman.
|
|
15
|
+
|
|
16
|
+
Harden (modern engine only; legacy is unchanged):
|
|
17
|
+
- A port longer than five significant digits is rejected, same as port `99999`, instead of calling `int()` on an unbounded digit string. A client-controlled header of about 4.3 KB could otherwise make `get_client_ip()` raise `ValueError` (Python's `int` string-digit limit). Zero-padded ports such as `000080` are still accepted.
|
|
18
|
+
- IPv6 zone ids longer than 255 characters are rejected. RFC 4007 sets no maximum; 255 matches the longest common OS interface-name limit so a multi-kilobyte scope is not returned, logged, or stored. The legacy engine still accepts any length.
|
|
19
|
+
|
|
1
20
|
## 4.1.0
|
|
2
21
|
|
|
3
22
|
Best match (modern engine only; legacy is unchanged). Results can differ from 4.0.0 on well-formed input,
|
|
@@ -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
|
|
|
@@ -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
|
-
>
|
|
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
|
-
|
|
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,
|
|
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|
|
|
136
|
-
|
|
137
|
-
E -->|no|
|
|
138
|
-
E -->|yes| F["
|
|
139
|
-
|
|
140
|
-
|
|
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
|
|
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
|
-
[
|
|
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.
|
|
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
|
|
@@ -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
|