| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable, Optional |
| 4 |
from urllib.parse import urlunsplit |
| 5 |
|
| 6 |
from ..typing import ASGIFramework, HTTPScope, Scope, WebsocketScope, WWWScope |
| 7 |
|
| 8 |
|
| 9 |
class HTTPToHTTPSRedirectMiddleware: |
| 10 |
def __init__(self, app: ASGIFramework, host: Optional[str]) -> None: |
| 11 |
self.app = app |
| 12 |
self.host = host |
| 13 |
|
| 14 |
async def __call__(self, scope: Scope, receive: Callable, send: Callable) -> None: |
| 15 |
if scope["type"] == "http" and scope["scheme"] == "http": |
| 16 |
await self._send_http_redirect(scope, send) |
| 17 |
elif scope["type"] == "websocket" and scope["scheme"] == "ws": |
| 18 |
# If the server supports the WebSocket Denial Response |
| 19 |
# extension we can send a redirection response, if not we |
| 20 |
# can only deny the WebSocket connection. |
| 21 |
if "websocket.http.response" in scope.get("extensions", {}): |
| 22 |
await self._send_websocket_redirect(scope, send) |
| 23 |
else: |
| 24 |
await send({"type": "websocket.close"}) |
| 25 |
else: |
| 26 |
return await self.app(scope, receive, send) |
| 27 |
|
| 28 |
async def _send_http_redirect(self, scope: HTTPScope, send: Callable) -> None: |
| 29 |
new_url = self._new_url("https", scope) |
| 30 |
await send( |
| 31 |
{ |
| 32 |
"type": "http.response.start", |
| 33 |
"status": 307, |
| 34 |
"headers": [(b"location", new_url.encode())], |
| 35 |
} |
| 36 |
) |
| 37 |
await send({"type": "http.response.body"}) |
| 38 |
|
| 39 |
async def _send_websocket_redirect(self, scope: WebsocketScope, send: Callable) -> None: |
| 40 |
# If the HTTP version is 2 we should redirect with a https |
| 41 |
# scheme not wss. |
| 42 |
scheme = "wss" |
| 43 |
if scope.get("http_version", "1.1") == "2": |
| 44 |
scheme = "https" |
| 45 |
|
| 46 |
new_url = self._new_url(scheme, scope) |
| 47 |
await send( |
| 48 |
{ |
| 49 |
"type": "websocket.http.response.start", |
| 50 |
"status": 307, |
| 51 |
"headers": [(b"location", new_url.encode())], |
| 52 |
} |
| 53 |
) |
| 54 |
await send({"type": "websocket.http.response.body"}) |
| 55 |
|
| 56 |
def _new_url(self, scheme: str, scope: WWWScope) -> str: |
| 57 |
host = self.host |
| 58 |
if host is None: |
| 59 |
for key, value in scope["headers"]: |
| 60 |
if key == b"host": |
| 61 |
host = value.decode("latin-1") |
| 62 |
break |
| 63 |
if host is None: |
| 64 |
raise ValueError("Host to redirect to cannot be determined") |
| 65 |
|
| 66 |
path = scope.get("root_path", "") + scope["raw_path"].decode() |
| 67 |
return urlunsplit((scheme, host, path, scope["query_string"].decode(), "")) |