A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: emit relative Location on login redirect (#9314)
Myles Scolnickcbe9666f467d
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex 0243caba27..496b9dc505 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -5,8 +5,9 @@ import mimetypesimport refrom pathlib import Pathfrom typing import TYPE_CHECKING, TypedDict+from urllib.parse import urlencode-from starlette.authentication import requires+from starlette.authentication import has_required_scope, requiresfrom starlette.exceptions import HTTPExceptionfrom starlette.responses import (FileResponse,@@ -139,6 +140,29 @@ def _strip_access_token_redirect(request: Request) -> RedirectResponse:)+def _login_redirect(request: Request) -> RedirectResponse:+ """Build a relative redirect to the login page for unauthenticated users.++ Starlette's built-in `@requires(redirect=...)` builds the Location from+ `request.url_for(...)` and embeds `str(request.url)` as `next=`. Both+ of those use the request's `Host` header, so behind a reverse proxy+ that doesn't rewrite `Host` the browser is sent to an internal+ address. Emitting a relative `Location` sidesteps that — browsers+ resolve it against the URL they themselves used, regardless of what+ the proxy forwarded.++ See https://github.com/marimo-team/marimo/issues/9249.+ """+ next_url = request.url.path+ if request.url.query:+ next_url = f"{next_url}?{request.url.query}"+ login_path = request.app.url_path_for("auth:login_page")+ return RedirectResponse(+ url=f"{login_path}?{urlencode({'next': next_url})}",+ status_code=303,+ )++@router.get("/og/thumbnail", include_in_schema=False)@requires("read")def og_thumbnail(*, request: Request) -> Response:@@ -256,8 +280,12 @@ async def _fetch_index_html_from_url(asset_url: str) -> str:@router.get("/")-@requires("read", redirect="auth:login_page")async def index(request: Request) -> Response:+ # Manual auth guard instead of `@requires(redirect=...)` so the+ # Location is relative — see `_login_redirect` for the reasoning.+ if not has_required_scope(request, ["read"]):+ return _login_redirect(request)+# Auth has already passed at this point — either via the session cookie# or by validating `access_token` in the query string (which also set# the cookie). If the token is still in the URL, redirect to strip itdiff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.pyindex 217b2a829b..087cb14e30 100644--- a/tests/_server/api/endpoints/test_assets.py+++ b/tests/_server/api/endpoints/test_assets.py@@ -118,7 +118,7 @@ def test_index_invalid_access_token_redirects_to_login(client: TestClient,) -> None:# An invalid token must NOT trigger the token-strip redirect (which- # would imply the token was accepted). Instead, `@requires` should+ # would imply the token was accepted). Instead, the auth guard should# redirect the unauthenticated request to the login page. Following# the redirect lands on the login HTML.response = client.get("/?access_token=wrong-token", follow_redirects=False)@@ -130,6 +130,48 @@ def test_index_invalid_access_token_redirects_to_login(assert "Login" in followed.text+def test_index_unauthenticated_redirect_is_relative(+ client: TestClient,+) -> None:+ # Regression test for https://github.com/marimo-team/marimo/issues/9249.+ # When a reverse proxy forwards an internal `Host` header, an absolute+ # Location would send the browser to an unreachable internal address.+ # The Location must be relative so the browser resolves it against the+ # public URL it originally used.+ response = client.get(+ "/",+ headers={"Host": "10.0.0.5:60830"},+ follow_redirects=False,+ )+ assert response.status_code == 303, response.text+ location = response.headers["location"]+ # Must be relative — no scheme, no host.+ assert location.startswith("/auth/login?"), location+ assert "://" not in location+ assert "10.0.0.5" not in location+++def test_index_unauthenticated_redirect_preserves_next(+ client: TestClient,+) -> None:+ # The original path (and query) must round-trip through the redirect so+ # the user lands where they were trying to go after logging in.+ response = client.get(+ "/?file=foo.py&view-as=present",+ follow_redirects=False,+ )+ assert response.status_code == 303, response.text+ location = response.headers["location"]+ assert location.startswith("/auth/login?"), location+ # next= is percent-encoded; decoding it should yield the original path+ # with its query string.+ from urllib.parse import parse_qs, urlparse++ parsed = urlparse(location)+ next_value = parse_qs(parsed.query)["next"][0]+ assert next_value == "/?file=foo.py&view-as=present"++def test_index_response_has_security_headers(client: TestClient) -> None:response = client.get("/", headers=token_header())assert response.status_code == 200, response.textdiff --git a/tests/_server/api/endpoints/test_requires_decorator.py b/tests/_server/api/endpoints/test_requires_decorator.pyindex 0b411c6f5c..330439bd83 100644--- a/tests/_server/api/endpoints/test_requires_decorator.py+++ b/tests/_server/api/endpoints/test_requires_decorator.py@@ -15,6 +15,9 @@ EXEMPT_ENDPOINTS: set[tuple[str, str]] = {("assets.py", "/public-files-sw.js"),# Static frontend assets (JS/CSS) must load before auth("assets.py", "/{path:path}"),+ # `/` does its own scope check so it can emit a relative Location on+ # unauthenticated redirects (see #9249).+ ("assets.py", "/"),}ENDPOINTS_DIR = Path(__file__).resolve().parents[4] / (