Skip to content
Open
Show file tree
Hide file tree
Changes from 7 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
19 changes: 10 additions & 9 deletions src/limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""

import hashlib
import ipaddress
import re
import threading
import time
Expand Down Expand Up @@ -271,16 +272,16 @@ def client_ip(request: Request, ip_header: str = "") -> str:
different notions of "IP" would each be bypassable by whichever header the other
ignored.
"""
if ip_header:
forwarded = request.headers.get(ip_header, "").split(",")[0].strip()
if forwarded:
return forwarded
return request.client.host if request.client else "?"
# Not configured to read one. Note whether the request looks proxied anyway, so a
# misconfiguration is visible in /stats instead of only in a support ticket.
if any(h in request.headers for h in PROXY_IP_HEADERS):
raw = request.headers.get(ip_header, "").split(",")[0].strip() if ip_header else ""
if not ip_header and any(h in request.headers for h in PROXY_IP_HEADERS):
_proxy_evidence["proxied_requests"] += 1
return request.client.host if request.client else "?"
try:
addr = ipaddress.ip_address(raw := raw or (request.client.host if request.client else "?"))
if isinstance(addr, ipaddress.IPv6Address):
return str(addr.ipv4_mapped or ipaddress.ip_network(f"{addr}/64", False))
except ValueError:
pass
return raw


def take(request, kind, per_min, burst=None, *, ip_header="", max_buckets=MAX_BUCKETS):
Expand Down
4 changes: 2 additions & 2 deletions tests/http/test_limits.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,10 +493,10 @@ def test_rate_limit_buckets_are_bounded(client, monkeypatch):
# whole loop is one client (the test socket) and nothing rotates.
with config.override(CLIENT_IP_HEADER="cf-connecting-ip"):
for i in range(50):
client.get("/r/lobby", headers={"cf-connecting-ip": f"2001:db8::{i:x}"})
client.get("/r/lobby", headers={"cf-connecting-ip": f"2001:db8:{i:x}::1"})
assert len(app_module._buckets) <= 8
# the survivors are the most recent callers, so an active client keeps its budget
assert ("2001:db8::31", "read") in app_module._buckets
assert ("2001:db8:31::/64", "read") in app_module._buckets


def test_no_forwarded_header_is_trusted_by_default(client, monkeypatch):
Expand Down
67 changes: 67 additions & 0 deletions tests/unit/test_limit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import sys
from unittest.mock import MagicMock

if "fcntl" not in sys.modules and sys.platform == "win32":
sys.modules["fcntl"] = MagicMock()

from starlette.requests import Request

import limit


def test_client_ip_ipv6_compression():
# Helper to build a minimal Starlette request
def make_req(host: str) -> Request:
scope = {
"type": "http",
"client": (host, 12345),
"headers": [],
}
return Request(scope)

# 1. Two addresses in the same /64
req1 = make_req("2001:db8::1")
req2 = make_req("2001:db8::2")

key1 = limit.client_ip(req1)
key2 = limit.client_ip(req2)

assert key1 == key2, f"Keys differ: {key1} vs {key2}"
assert key1 == "2001:db8::/64", key1

# 2. Fully expanded representation of the same /64
req_expanded = make_req("2001:0db8:0000:0000:0000:0000:0000:0001")
key_expanded = limit.client_ip(req_expanded)
assert key_expanded == key1, f"Expanded representation differs: {key_expanded} vs {key1}"

# 3. A different /64
req3 = make_req("2001:db8:0:1::1")
key3 = limit.client_ip(req3)
assert key3 != key1, f"Different /64 collapsed to same key: {key3}"
assert key3 == "2001:db8:0:1::/64", key3

# 4. Standard IPv4
req4 = make_req("192.168.1.1")
key4 = limit.client_ip(req4)
assert key4 == "192.168.1.1"


def test_client_ip_ipv4_mapped():
def make_req(host: str) -> Request:
scope = {
"type": "http",
"client": (host, 12345),
"headers": [],
}
return Request(scope)

# 5. IPv4-mapped addresses must not coalesce
req1 = make_req("::ffff:192.0.2.1")
req2 = make_req("::ffff:198.51.100.9")

key1 = limit.client_ip(req1)
key2 = limit.client_ip(req2)

assert key1 == "192.0.2.1", f"Unexpected mapped key: {key1}"
assert key2 == "198.51.100.9", f"Unexpected mapped key: {key2}"
assert key1 != key2, "Mapped IPv4 addresses incorrectly coalesced"
Loading