Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add trusted networks #2387

Closed
wants to merge 2 commits into from
Closed
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
40 changes: 40 additions & 0 deletions tests/middleware/test_proxy_headers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import ipaddress
from typing import TYPE_CHECKING

import httpx
Expand Down Expand Up @@ -58,6 +59,45 @@ async def test_proxy_headers_trusted_hosts(trusted_hosts: list[str] | str, respo
assert response.text == response_text


@pytest.mark.anyio
@pytest.mark.parametrize(
("trusted_networks", "response_text"),
[
([ipaddress.IPv4Network("192.168.0.0/24")], "Remote: https://10.0.2.1:0"),
(
[
ipaddress.IPv4Network("192.168.0.0/24"),
ipaddress.IPv4Network("10.0.0.0/16"),
ipaddress.IPv6Network("2001:db8::/64"),
],
"Remote: https://1.2.3.4:0",
),
(
[
ipaddress.IPv4Network("192.168.0.0/24"),
ipaddress.IPv4Network("10.0.0.0/16"),
],
"Remote: https://2001:db8::1:0",
),
],
)
async def test_proxy_headers_trusted_networks(
trusted_networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network],
response_text: str,
) -> None:
app_with_middleware = ProxyHeadersMiddleware(app, trusted_networks=trusted_networks)
transport = httpx.ASGITransport(app=app_with_middleware) # type: ignore
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
headers = {
"X-Forwarded-Proto": "https",
"X-Forwarded-For": "1.2.3.4, 2001:db8::1, 10.0.2.1, 192.168.0.2",
}
response = await client.get("/", headers=headers)

assert response.status_code == 200
assert response.text == response_text


@pytest.mark.anyio
@pytest.mark.parametrize(
("trusted_hosts", "response_text"),
Expand Down
35 changes: 33 additions & 2 deletions uvicorn/middleware/proxy_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,42 @@

from __future__ import annotations

import ipaddress
from typing import Union, cast

from uvicorn._types import ASGI3Application, ASGIReceiveCallable, ASGISendCallable, HTTPScope, Scope, WebSocketScope
from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGISendCallable,
HTTPScope,
Scope,
WebSocketScope,
)


def _address_to_network(
host: str,
) -> ipaddress.IPv4Network | ipaddress.IPv6Network:
address = ipaddress.ip_address(host)
return ipaddress.ip_network(int(address))


def _networks_contain_address(
networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network],
address: ipaddress.IPv4Address | ipaddress.IPv6Address,
) -> bool:
for network in networks:
if address in network:
return True
return False


class ProxyHeadersMiddleware:
def __init__(
self,
app: ASGI3Application,
trusted_hosts: list[str] | str = "127.0.0.1",
trusted_networks: (list[ipaddress.IPv4Network | ipaddress.IPv6Network] | None) = None,
) -> None:
self.app = app
if isinstance(trusted_hosts, str):
Expand All @@ -29,12 +55,17 @@ def __init__(
self.trusted_hosts = set(trusted_hosts)
self.always_trust = "*" in self.trusted_hosts

self.trusted_networks = trusted_networks or []

if not self.always_trust:
self.trusted_networks += [_address_to_network(host) for host in self.trusted_hosts]

def get_trusted_client_host(self, x_forwarded_for_hosts: list[str]) -> str | None:
if self.always_trust:
return x_forwarded_for_hosts[0]

for host in reversed(x_forwarded_for_hosts):
if host not in self.trusted_hosts:
if not _networks_contain_address(self.trusted_networks, ipaddress.ip_address(host)):
return host

return None # pragma: full coverage
Expand Down
Loading