1818import re
1919from pathlib import Path
2020from typing import Any , ClassVar , NamedTuple , Optional
21+ from urllib .parse import unquote
2122
2223from starlette .applications import Starlette
2324from starlette .datastructures import MutableHeaders
2425from starlette .middleware import Middleware
2526from starlette .requests import Request
2627from starlette .responses import FileResponse , JSONResponse , Response
28+ from starlette ._utils import get_route_path
2729from starlette .routing import Route
2830
2931from ..agent_env_environment import (
4143from .clock import CLOCK_EXTENSION_URI , UNIVERSE_NOW_HEADER , UniverseClock , clock_patch_script , iso
4244from .errors import NotFound
4345from .readiness import WEBSITE_EXTENSION_URI , WEBSITE_READY_OP , WebsiteReadiness
44- from .routes import ApiContext , ApiRoute , endpoint , error_response , openapi , openapi_path , request_role , reserved_path , routes_of
46+ from .routes import (ApiContext , ApiRoute , endpoint , error_response , forwarded_prefix , openapi , openapi_path , request_role ,
47+ reserved_path , routes_of )
4548from .session import SESSION_COOKIE , SessionSigner , expires_at
4649from .state import WEBSITE_STATE_OP , WebsiteState
4750from .store import Collections
@@ -320,9 +323,11 @@ def _check_health(cls: type) -> None:
320323
321324
322325class _Forwarded :
323- """Puts the address the browser reached the site at in the scope, from ``X-Forwarded-Host`` and
324- ``X-Forwarded-Proto``, before anything routes it, so redirects, ``request.url`` and a mounted app's ``url_for``
325- name that address and not the internal one the proxy reached the server at."""
326+ """Puts the address the browser reached the site at in the scope, from ``X-Forwarded-Host``,
327+ ``X-Forwarded-Proto`` and ``X-Forwarded-Prefix``, before anything routes it, so redirects, ``request.url`` and a
328+ mounted app's ``url_for`` name that address and not the internal one the proxy reached the server at. A prefix
329+ becomes the scope's ``root_path`` and leads its ``path``, as ASGI has a mounted app's, so routing still sees the
330+ site's own path."""
326331
327332 def __init__ (self , app : Any ) -> None :
328333 self .app = app
@@ -337,6 +342,12 @@ async def __call__(self, scope: dict, receive: Any, send: Any) -> None:
337342 scope ["headers" ] = [(k , v ) for k , v in scope ["headers" ] if k != b"host" ] + [(b"host" , host .encode ())]
338343 if proto in ("http" , "https" ):
339344 scope ["scheme" ] = proto if scope ["type" ] == "http" else {"http" : "ws" , "https" : "wss" }[proto ]
345+ prefix = forwarded_prefix (_first (headers .get (b"x-forwarded-prefix" )))
346+ if prefix :
347+ scope ["root_path" ] = unquote (prefix ) + scope .get ("root_path" , "" )
348+ scope ["path" ] = unquote (prefix ) + scope ["path" ]
349+ if scope .get ("raw_path" ) is not None :
350+ scope ["raw_path" ] = prefix .encode ("latin-1" ) + scope ["raw_path" ]
340351 await self .app (scope , receive , send )
341352
342353
@@ -416,7 +427,7 @@ async def __call__(self, scope: dict, receive: Any, send: Any) -> None:
416427 if self .app is not None :
417428 await self .app (scope , receive , send )
418429 return
419- path , reading = scope [ "path" ] , scope ["method" ] in ("GET" , "HEAD" )
430+ path , reading = get_route_path ( scope ) or "/" , scope ["method" ] in ("GET" , "HEAD" )
420431 if reserved_path (path ):
421432 return await error_response (NotFound ("not found" ))(scope , receive , send )
422433 if reading and (file := self ._file (path )) is not None :
0 commit comments