"""Tests for client IP resolution behind reverse proxy.""" from types import SimpleNamespace from app.services.client_ip import client_ip_from_request def _request(*, client_host: str = "10.0.0.5", xff: str | None = None): headers = {} if xff is not None: headers["x-forwarded-for"] = xff return SimpleNamespace(client=SimpleNamespace(host=client_host), headers=headers) def test_client_ip_without_forwarded_header(): assert client_ip_from_request(_request(client_host="203.0.113.10")) == "203.0.113.10" def test_client_ip_uses_last_forwarded_hop(): req = _request(client_host="127.0.0.1", xff="203.0.113.99, 198.51.100.20") assert client_ip_from_request(req) == "198.51.100.20" def test_client_ip_ignores_spoofed_first_hop(): req = _request(client_host="127.0.0.1", xff="1.2.3.4, 203.0.113.50") assert client_ip_from_request(req) == "203.0.113.50"