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: strip access token via redirect (#9170)
Myles Scolnick727dc6707f73
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex ff04d89127..14b1f1f741 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -26,6 +26,7 @@ from marimo._runtime.virtual_file import (EMPTY_VIRTUAL_FILE,read_virtual_file_chunked,)+from marimo._server.api.auth import TOKEN_QUERY_PARAMfrom marimo._server.api.deps import AppStatefrom marimo._server.files.path_validator import PathValidatorfrom marimo._server.router import APIRouter@@ -108,6 +109,35 @@ except RuntimeError:FILE_QUERY_PARAM_KEY = "file"+# Hardening headers for HTML page responses in edit/home mode. These+# supplement the token-stripping redirect below by preventing any outbound+# fetch from the HTML page from leaking a transiently-present access_token+# via `Referer`, and by disabling MIME sniffing on the HTML response.+_HTML_SECURITY_HEADERS: dict[str, str] = {+ "Referrer-Policy": "no-referrer",+ "X-Content-Type-Options": "nosniff",+}+++def _strip_access_token_redirect(request: Request) -> RedirectResponse:+ """Build a redirect to the current URL with access_token removed.++ By the time this runs, `validate_auth` has already matched the query+ param against the server's auth token and promoted it to a session+ cookie. Redirecting before any JavaScript runs prevents a+ pre-execution XSS, a third-party subresource, or browser history from+ capturing the plaintext token.+ """+ stripped = request.url.remove_query_params(TOKEN_QUERY_PARAM)+ target = stripped.path+ if stripped.query:+ target = f"{target}?{stripped.query}"+ return RedirectResponse(+ url=target,+ status_code=303,+ headers=_HTML_SECURITY_HEADERS,+ )+@router.get("/og/thumbnail", include_in_schema=False)@requires("read")@@ -227,7 +257,15 @@ async def _fetch_index_html_from_url(asset_url: str) -> str:@router.get("/")@requires("read", redirect="auth:login_page")-async def index(request: Request) -> HTMLResponse:+async def index(request: Request) -> Response:+ # 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 it+ # before serving HTML. The Set-Cookie header rides the 303 response, so+ # the browser lands on a clean URL with an authenticated session.+ if TOKEN_QUERY_PARAM in request.query_params:+ return _strip_access_token_redirect(request)+app_state = AppState(request)index_html = root / "index.html"@@ -327,7 +365,7 @@ async def index(request: Request) -> HTMLResponse:# Inject service worker registration with the notebook IDhtml = _inject_service_worker(html, file_key)- return HTMLResponse(html)+ return HTMLResponse(html, headers=_HTML_SECURITY_HEADERS)DEFAULT_NOTEBOOK_NAME = "__marimo_notebook__.py"diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.pyindex 0aad3c8e11..3ab8b1d3d5 100644--- a/tests/_cli/test_cli.py+++ b/tests/_cli/test_cli.py@@ -109,13 +109,23 @@ def _check_shutdown(def _try_fetch(port: int, host: str = "localhost", token: str | None = None) -> bytes | None:+ import http.cookiejar+err: Exception | None = Nonefor _ in range(20):try:url = f"http://{host}:{port}"if token is not None:url = f"{url}?access_token={token}"- return urllib.request.urlopen(url).read()+ # The server 303-redirects `/?access_token=...` to strip the+ # token from the URL, attaching the session cookie to the+ # redirect. Use a cookie-aware opener so the follow-up request+ # carries that cookie and lands on the authenticated page+ # instead of the login screen.+ opener = urllib.request.build_opener(+ urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())+ )+ return opener.open(url).read()except Exception as e:err = etime.sleep(0.6)diff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.pyindex e5276df076..2a7e525847 100644--- a/tests/_server/api/endpoints/test_assets.py+++ b/tests/_server/api/endpoints/test_assets.py@@ -83,6 +83,60 @@ def test_index_when_new_file(client: TestClient) -> None:assert "<title>marimo</title>" in content+def test_index_strips_access_token_query_param(client: TestClient) -> None:+ # A valid `?access_token=` in the URL should 303 to the same path with+ # the token removed, carrying a session cookie so the follow-up request+ # is already authenticated. This prevents pre-execution XSS, Referer,+ # or browser history from capturing the plaintext token.+ response = client.get("/?access_token=fake-token", follow_redirects=False)+ assert response.status_code == 303, response.text+ assert response.headers["location"] == "/"+ assert response.headers.get("referrer-policy") == "no-referrer"+ assert response.headers.get("x-content-type-options") == "nosniff"+ # The session cookie must be set so the redirect target is authenticated+ # without the query param.+ set_cookie = response.headers.get("set-cookie", "")+ assert "session" in set_cookie+++def test_index_strips_access_token_preserves_other_params(+ client: TestClient,+) -> None:+ response = client.get(+ "/?file=foo.py&access_token=fake-token&view-as=present",+ follow_redirects=False,+ )+ assert response.status_code == 303, response.text+ location = response.headers["location"]+ assert location.startswith("/")+ assert "access_token" not in location+ assert "file=foo.py" in location+ assert "view-as=present" in location+++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+ # 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)+ assert response.status_code in (302, 303), response.text+ assert "login" in response.headers["location"].lower()+ # Following the redirect lands on the login page.+ followed = client.get("/?access_token=wrong-token")+ assert followed.status_code == 200+ assert "Login" in followed.text+++def test_index_response_has_security_headers(client: TestClient) -> None:+ response = client.get("/", headers=token_header())+ assert response.status_code == 200, response.text+ assert response.headers.get("referrer-policy") == "no-referrer"+ assert response.headers.get("x-content-type-options") == "nosniff"++def test_index_with_directory(client: TestClient, tmp_path: Path) -> None:with file_router_scope(client, AppFileRouter.from_directory(str(tmp_path))diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.pyindex 8d49c79546..58534c03e1 100644--- a/tests/_server/api/test_middleware.py+++ b/tests/_server/api/test_middleware.py@@ -266,13 +266,21 @@ class TestAuth:assert response.headers.get("Set-Cookie") is Nonedef test_auth_by_query(self, app: Starlette) -> None:- # Test authorized access by auth_token in query+ # Test authorized access by auth_token in query. The server now+ # 303-redirects `/?access_token=...` to `/` after validating the+ # token and attaching the session cookie to the redirect response,+ # so the browser lands on a clean URL without exposing the token+ # to JavaScript or Referer.client = TestClient(app)- response = client.get("/?access_token=fake-token")- assert response.status_code == 200, response.text+ response = client.get(+ "/?access_token=fake-token", follow_redirects=False+ )+ assert response.status_code == 303, response.textassert response.headers.get("Set-Cookie") is not None+ assert response.headers["Location"] == "/"- # Can access again with cookie+ # Following the redirect with the new cookie lands on the+ # authenticated page.response = client.get("/")assert response.status_code == 200, response.text