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

Use X-Forwarded-Proto for WebSockets scheme when the proxy provides it #2258

Merged
merged 6 commits into from
Mar 1, 2024
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
15 changes: 13 additions & 2 deletions tests/middleware/test_proxy_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,18 @@ async def test_proxy_headers_invalid_x_forwarded_for() -> None:


@pytest.mark.anyio
@pytest.mark.parametrize(
"x_forwarded_proto,addr",
[
("http", "ws://1.2.3.4:0"),
("https", "wss://1.2.3.4:0"),
("ws", "ws://1.2.3.4:0"),
("wss", "wss://1.2.3.4:0"),
],
)
async def test_proxy_headers_websocket_x_forwarded_proto(
x_forwarded_proto: str,
addr: str,
ws_protocol_cls: "Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls: "Type[H11Protocol | HttpToolsProtocol]",
unused_tcp_port: int,
Expand All @@ -138,7 +149,7 @@ async def websocket_app(scope, receive, send):

async with run_server(config):
url = f"ws://127.0.0.1:{unused_tcp_port}"
headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"}
headers = {"X-Forwarded-Proto": x_forwarded_proto, "X-Forwarded-For": "1.2.3.4"}
async with websockets.client.connect(url, extra_headers=headers) as websocket:
data = await websocket.recv()
assert data == "wss://1.2.3.4:0"
assert data == addr
4 changes: 1 addition & 3 deletions uvicorn/middleware/proxy_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,7 @@ async def __call__(
headers[b"x-forwarded-proto"].decode("latin1").strip()
)
if scope["type"] == "websocket":
scope["scheme"] = (
"wss" if x_forwarded_proto == "https" else "ws"
)
scope["scheme"] = x_forwarded_proto.replace("http", "ws")
else:
scope["scheme"] = x_forwarded_proto

Expand Down