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
10 changes: 7 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,15 @@ include = [
[tool.ruff]
line-length = 120
target-version = "py39"
# The legacy engine and its v3 tests are frozen byte-for-byte, so newer lint rules
# must not force edits there.
extend-exclude = ["python_ipware/legacy", "tests/legacy"]

[tool.ruff.format]
# Docs keep hand-aligned comments in their code examples.
exclude = ["*.md"]

[tool.ruff.lint]
# The legacy engine and its v3 tests are frozen in behavior, so newer lint rules
# must not force edits there. They are still formatted (layout only).
exclude = ["python_ipware/legacy/*", "tests/legacy/*"]
select = [
"B",
"C4",
Expand Down
16 changes: 4 additions & 12 deletions python_ipware/legacy/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ class IpWareMeta:
the client's IP address behind load balancers and proxies.
"""

def __init__(
self, precedence: Optional[Tuple[str, ...]] = None, leftmost: bool = True
) -> None:
def __init__(self, precedence: Optional[Tuple[str, ...]] = None, leftmost: bool = True) -> None:
"""
Initializes the metadata handler with a precedence list of HTTP headers and the position of the client IP.

Expand Down Expand Up @@ -148,9 +146,7 @@ class IpWareProxy:
proxy counts and trusted proxy lists.
"""

def __init__(
self, proxy_count: Optional[int] = None, proxy_list: Optional[List[str]] = None
) -> None:
def __init__(self, proxy_count: Optional[int] = None, proxy_list: Optional[List[str]] = None) -> None:
"""
Initialize the IpWareProxy class with optional proxy count and proxy list.

Expand Down Expand Up @@ -202,9 +198,7 @@ def is_proxy_count_valid(self, ip_list: List[str], strict: bool = False) -> bool
return ip_count - 1 >= self.proxy_count
# Allow more proxies than the count, excluding client's IP.

def is_proxy_trusted_list_valid(
self, ip_list: List[str], strict: bool = False
) -> bool:
def is_proxy_trusted_list_valid(self, ip_list: List[str], strict: bool = False) -> bool:
"""
Checks if all proxies in the incoming list are trusted based on the proxy_list.

Expand All @@ -230,9 +224,7 @@ def is_proxy_trusted_list_valid(
# Verify each proxy against the trusted list by comparing each corresponding element.
return all(
str(ip).startswith(trusted_proxy_pattern)
for ip, trusted_proxy_pattern in zip(
ip_list[-proxy_list_count:], self.proxy_list
)
for ip, trusted_proxy_pattern in zip(ip_list[-proxy_list_count:], self.proxy_list)
)


Expand Down
11 changes: 3 additions & 8 deletions python_ipware/modern/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,7 @@ def __init__(
raise ValueError("proxy_count must be a non-negative integer")
# A bare string is iterable and would silently become one prefix per
# character ("10.0.0.1" -> "1", "0", ...), trusting almost anything.
if isinstance(proxy_list, str) or (
proxy_list is not None and not all(isinstance(p, str) for p in proxy_list)
):
if isinstance(proxy_list, str) or (proxy_list is not None and not all(isinstance(p, str) for p in proxy_list)):
raise ValueError("proxy_list must be a list of strings.")
proxy_list = [p.strip() for p in proxy_list or []]
# An empty prefix matches every address, which would mark any spoofed
Expand All @@ -169,9 +167,7 @@ def __init__(
# proxy_count and proxy_list may both be set and may differ (v3 API):
# the count is a hop-count requirement (minimum, or exact when strict)
# and the list pins the client position. See _pinned_from_chain.
if isinstance(precedence, str) or (
precedence is not None and not all(isinstance(h, str) for h in precedence)
):
if isinstance(precedence, str) or (precedence is not None and not all(isinstance(h, str) for h in precedence)):
raise ValueError("precedence must be a sequence of header-name strings.")

# Copy, so later changes to the caller's objects cannot leak in.
Expand Down Expand Up @@ -236,8 +232,7 @@ def _proxy_list_valid(self, chain: list[OptionalIp], strict: bool) -> bool:
return False
# Compare the trailing proxies against the trusted entries in order.
return all(
ip is not None and _proxy_matches(ip, matcher)
for ip, matcher in zip(chain[-count:], self._proxy_matchers)
ip is not None and _proxy_matches(ip, matcher) for ip, matcher in zip(chain[-count:], self._proxy_matchers)
)

# -- selection ----------------------------------------------------------
Expand Down
5 changes: 1 addition & 4 deletions python_ipware/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,4 @@ def get_client_ip(self, meta, strict: bool = False):
return self._impl.get_client_ip(meta, strict)

def __repr__(self) -> str:
return (
f"IpWare(algorithm={self.algorithm!r} -> "
f"{self.resolved_algorithm!r})"
)
return f"IpWare(algorithm={self.algorithm!r} -> {self.resolved_algorithm!r})"
4 changes: 1 addition & 3 deletions tests/legacy/tests_ipv6.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,7 @@ class TestIPv6ProxyList(unittest.TestCase):
"""IPv6 Proxy List Test"""

def setUp(self):
self.ipware = IpWare(
proxy_list=["2606:4700:4700::1111", "2001:4860:4860::8888"]
)
self.ipware = IpWare(proxy_list=["2606:4700:4700::1111", "2001:4860:4860::8888"])

def tearDown(self):
self.ipware = None
Expand Down
9 changes: 2 additions & 7 deletions tests/tests_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,7 @@ def test_invalid_algorithm(self):

def test_all_algorithms_agree_on_simple_chain(self):
meta = {"HTTP_X_FORWARDED_FOR": "177.139.233.139, 198.84.193.157, 198.84.193.158"}
results = {
algo: str(IpWare(algorithm=algo).get_client_ip(meta)[0])
for algo in ("auto", "modern", "legacy")
}
results = {algo: str(IpWare(algorithm=algo).get_client_ip(meta)[0]) for algo in ("auto", "modern", "legacy")}
self.assertEqual(set(results.values()), {"177.139.233.139"})


Expand Down Expand Up @@ -169,9 +166,7 @@ def test_legacy_unchanged(self):
class TestModernRightmost(unittest.TestCase):
"""leftmost=False must validate proxies and pick the client from the same end."""

XFF: ClassVar[dict[str, str]] = {
"HTTP_X_FORWARDED_FOR": "198.84.193.158, 198.84.193.157, 177.139.233.139"
}
XFF: ClassVar[dict[str, str]] = {"HTTP_X_FORWARDED_FOR": "198.84.193.158, 198.84.193.157, 177.139.233.139"}

def test_rightmost_proxy_list_exact(self):
ipw = IpWare(leftmost=False, proxy_list=["198.84.193.157", "198.84.193.158"])
Expand Down