Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,7 @@ docs/_build/
target/

.DS_Store
.ruff_cache
.ruff_cache
/.dojo/
/.dojo-d/
/temp/
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
## 5.0.0

Reported by Sang Nguyen (sangn6767@gmail.com).

- Stricter handling of malformed proxy header values. All users are encouraged to upgrade to 5.0.0+
- Breaking: with `proxy_count` / `proxy_list` set, only the first header present (by precedence) is used;
lower headers are no longer consulted, and empty or non-IP entries keep their position in the chain.
Pass a `precedence` naming the header your proxies write.
- Deprecate the legacy engine (`algorithm="legacy"` / `LegacyIpWare`). It now emits a `DeprecationWarning`
and will be removed in a future major release; move to the default `IpWare()`.

## 4.1.1

Reported privately by David Gilman.
Expand Down
38 changes: 26 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ Python 3.9+ is supported (tested on 3.9 – 3.14), with no upper version cap. No
On a newer Python that isn't in the test matrix yet? It should just work — if it doesn't,
[open an issue](https://github.com/un33k/python-ipware/issues) and we'll fix it.

> **Legacy:** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`.
> See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md).
> **Legacy (deprecated):** the frozen 3.x algorithm is still available with `IpWare(algorithm="legacy")`,
> but it emits a `DeprecationWarning` and will be removed in a future major release. Move to the default
> `IpWare()`. See the [legacy guide](https://github.com/un33k/python-ipware/blob/main/python_ipware/legacy/README.md).

## What it's used for

Expand Down Expand Up @@ -101,7 +102,11 @@ ip, trusted_route = ipw.get_client_ip(meta, strict=False)

### Selection rules

Headers are checked in precedence order. Every address is ranked:
Without `proxy_count` / `proxy_list`, headers are checked in precedence order. With either set,
the first header present decides on its own; lower headers are not consulted, and the result is
`(None, False)` if that header does not validate. So with proxy settings, pass a `precedence`
naming only the header your proxies write (for example `("HTTP_X_FORWARDED_FOR", "REMOTE_ADDR")`).
Every address is ranked:

| Rank | Addresses |
| --- | --- |
Expand All @@ -116,7 +121,9 @@ wins a tie.

Within one header, the client entry depends on your proxy settings:

- **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, exactly as in v3.
- **`proxy_count` / `proxy_list` set:** the entry just before your trusted proxies, as in v3. Unlike
v3, entries that are empty or not IPs (`unknown`, `for=_hidden`) still count as positions, so they
never shift which entry is the client.
- **Neither set:** the first public entry in the chain, not only the first entry. So
`10.0.0.1, 177.139.233.139` yields `177.139.233.139` (v3 returned `10.0.0.1`). With
`leftmost=False` the chain is scanned from the right. That public entry may be an upstream proxy
Expand All @@ -132,25 +139,29 @@ flowchart TD
A["Request headers (...)"] --> B["Take the next header in precedence order"]
B --> C{"Header present?"}
C -->|no| B
C -->|yes| D["Split the chain: client, proxy1, proxy2"]
D --> E{"Matches proxy_count and proxy_list?"}
E -->|no| B
E -->|yes| F["Pick the client entry"]
F --> G{"Public IP?"}
G -->|yes| H["Return (ip, trusted_route)"]
C -->|yes| K{"proxy_count or proxy_list set?"}
K -->|yes| E{"Matches proxy_count and proxy_list?"}
E -->|no| N["Return (None, False)"]
E -->|yes| F["Return the entry before the trusted proxies, True"]
K -->|no| D["Split the chain"]
D --> G{"Public IP in it?"}
G -->|yes| H["Return (ip, False)"]
G -->|no| I["Keep if it outranks the current fallback"]
I --> B
B -->|no headers left| J["Return the best fallback, else None"]
```

The legacy engine keeps v3's rules. A combination suite checks that the modern engine never returns a
worse address than legacy for the same input.
worse address than legacy for a single well-formed header.

Ports are stripped (`1.2.3.4:8080`, `[2001:db8::1]:443`). IPv4-mapped (`::ffff:1.2.3.4`) and NAT64
well-known-prefix (`64:ff9b::1.2.3.4`) addresses are returned as plain IPv4. RFC 7239 `Forwarded` elements are read by their
`for=` value (`for="[2001:db8::1]:4711";proto=https`). Malformed tokens such as `[::1`,
`[::1]junk`, or `1.2.3.4:abc` are rejected rather than truncated. Header names match
case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too.
case-insensitively, so lowercase keys (AWS Lambda / API Gateway v2) work too. When one header
appears under several spellings, a dashed name (`X-Forwarded-For`) beats an underscore one
(`X_FORWARDED_FOR`), and disagreeing spellings make the header unusable. `REMOTE_ADDR` and
`HTTP_*` keys are server variables, so a client header such as `Remote-Addr` never replaces them.

## Default header precedence

Expand Down Expand Up @@ -210,6 +221,9 @@ reachable directly, because clients can send these headers themselves:
ipw = IpWare(precedence=("HTTP_CF_CONNECTING_IP", "HTTP_X_FORWARDED_FOR", "REMOTE_ADDR"))
```

Do not combine this with `proxy_count` / `proxy_list`: with proxy settings the first header present
decides alone, and a single-IP header such as `CF-Connecting-IP` never has proxy hops to match.

## Trusted proxies

If your server sits behind known proxies, pass their IPs or prefixes:
Expand Down
2 changes: 1 addition & 1 deletion python_ipware/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "4.1.1"
__version__ = "5.0.0"
2 changes: 2 additions & 0 deletions python_ipware/legacy/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Legacy engine (v3) — how to use

> **Deprecated.** The legacy engine emits a `DeprecationWarning` and will be removed in a future major release. Use the default `IpWare()` instead.
>
> This is the original python-ipware 3.x guide, kept for reference. The legacy engine is frozen and only runs when requested explicitly with `IpWare(algorithm="legacy")`. For current usage see the [main README](../../README.md).

```python
Expand Down
63 changes: 59 additions & 4 deletions python_ipware/legacy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,67 @@
"""Frozen v3 algorithm.
"""Frozen v3 algorithm (deprecated).

This subpackage preserves the exact behavior of python-ipware 3.x. It is kept
byte-for-byte stable so that projects upgrading to 4.x can pin
byte-for-byte stable so that projects upgrading to 4.x or 5.x can pin
``algorithm="legacy"`` and get identical results to what they had before.

The legacy engine is deprecated and will be removed in a future major release.
Constructing it emits a ``DeprecationWarning``; the frozen ``engine`` module
itself is untouched, so importing ``python_ipware.legacy.engine.IpWare``
directly bypasses the warning (that private path is not supported).

Do not "improve" this module. New behavior belongs in ``python_ipware.modern``.
"""

from .engine import IpWare as LegacyIpWare
import os
import sys
import warnings
from types import FrameType
from typing import TYPE_CHECKING, Any, Optional

from .engine import IpWare as _V3IpWare

if TYPE_CHECKING:
from typing_extensions import deprecated
else:

def deprecated(_msg): # runtime no-op; the warning is issued in __init__
return lambda obj: obj


LEGACY_DEPRECATION_MESSAGE = (
"The legacy engine (algorithm='legacy' / LegacyIpWare) is deprecated and will be "
"removed in a future major release. Use the default engine: IpWare()."
)

_PACKAGE_DIR = os.path.normcase(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.sep)


def _in_package(filename: str) -> bool:
return os.path.normcase(os.path.abspath(filename)).startswith(_PACKAGE_DIR)


def _warn_deprecated() -> None:
# Point the warning at the first caller outside python_ipware, so it is
# attributed to user code whether it came via IpWare(...) or LegacyIpWare().
# The walk only aims the warning; it must never stop it from being issued.
level = 2
getframe = getattr(sys, "_getframe", None) # CPython/PyPy only
if getframe is not None:
frame: Optional[FrameType] = getframe(0)
level = 1
while frame is not None and _in_package(frame.f_code.co_filename):
frame = frame.f_back
level += 1
warnings.warn(LEGACY_DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=level)


@deprecated(LEGACY_DEPRECATION_MESSAGE)
class LegacyIpWare(_V3IpWare):
"""The frozen v3 engine. Deprecated: use ``IpWare()`` (modern)."""

def __init__(self, *args: Any, **kwargs: Any) -> None:
_warn_deprecated()
super().__init__(*args, **kwargs)


__all__ = ["LegacyIpWare"]
__all__ = ["LEGACY_DEPRECATION_MESSAGE", "LegacyIpWare"]
7 changes: 4 additions & 3 deletions python_ipware/modern/defaults.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Default header precedence for the modern engine.

Superset of the v3 list, adding widely-deployed CDN/edge headers. Headers are
scanned in order; the first one that yields a globally routable IP wins, with
private and then loopback addresses as fallbacks.
Superset of the v3 list, adding widely-deployed CDN/edge headers. Without
proxy settings, headers are scanned in order; the first one that yields a
globally routable IP wins, with private and then loopback addresses as
fallbacks. With proxy_count / proxy_list, the first header present decides.

Ordering rule: existing entries never move. New headers are added only in the
block just above ``REMOTE_ADDR``, so a new header can outrank the raw socket
Expand Down
Loading
Loading