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: auth page redirect when base-url is present, security headers (#4232)
Myles Scolnick5b3e32830dfe
diff --git a/marimo/_server/api/endpoints/login.py b/marimo/_server/api/endpoints/login.pyindex 5b916cc71e..e539cb16b1 100644--- a/marimo/_server/api/endpoints/login.py+++ b/marimo/_server/api/endpoints/login.py@@ -11,6 +11,7 @@ from starlette.responses import ()from marimo._server.api.auth import validate_auth+from marimo._server.api.deps import AppStatefrom marimo._server.router import APIRouterif TYPE_CHECKING:@@ -24,6 +25,7 @@ LOGIN_PAGE = """<html lang="en"><head><meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0"><title>marimo</title></head><body style="@@ -33,7 +35,7 @@ LOGIN_PAGE = """align-items: center;height: 100vh;margin: 0;">- <form method="POST" action="/auth/login" style="+ <form method="POST" action="{base_url}auth/login" style="padding: 20px;background-color: white;border-radius: 8px;@@ -97,16 +99,18 @@ async def login_submit(request: Request) -> Response:schema:type: string"""+ base_url = AppState(request).base_url or "/"+ base_url = _with_trailing_slash(base_url)+error = ""- redirect_url = request.query_params.get("next", "/")+ redirect_url = request.query_params.get("next", base_url)- # Ensure redirect URL uses same protocol as request+ # Validate redirect URL to prevent open redirect vulnerabilitiesparsed = urlparse(redirect_url)- if parsed.scheme:- redirect_url = parsed._replace(scheme=request.url.scheme).geturl()-- if request.user.is_authenticated:- return RedirectResponse("/", 302)+ if parsed.scheme and parsed.netloc:+ if parsed.netloc != request.url.netloc:+ # Fall back to base URL if external redirect+ redirect_url = base_urlif request.method == "POST":body = (await request.body()).decode()@@ -120,11 +124,34 @@ async def login_submit(request: Request) -> Response:return RedirectResponse(redirect_url, 302)else:error = "Invalid password"+ elif request.user.is_authenticated:+ return RedirectResponse(redirect_url, 302)- return HTMLResponse(content=LOGIN_PAGE.format(error=error))+ base_url = AppState(request).base_url+ html = LOGIN_PAGE.format(error=error, base_url=base_url)+ return HTMLResponse(+ content=html,+ headers={+ "X-Frame-Options": "DENY",+ "X-Content-Type-Options": "nosniff",+ },+ )@router.get("/login", name="login_page")async def login_page(request: Request) -> HTMLResponse:- del request- return HTMLResponse(content=LOGIN_PAGE.format(error=""))+ base_url = AppState(request).base_url+ base_url = _with_trailing_slash(base_url)+ return HTMLResponse(+ content=LOGIN_PAGE.format(error="", base_url=base_url),+ headers={+ "X-Frame-Options": "DENY",+ "X-Content-Type-Options": "nosniff",+ },+ )+++def _with_trailing_slash(url: str) -> str:+ if not url.endswith("/"):+ return url + "/"+ return urldiff --git a/openapi/api.yaml b/openapi/api.yamlindex 97e383f3ae..55c48acf4d 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1305,8 +1305,14 @@ components:type: stringbase_url:type: string+ ca_bundle_path:+ type: string+ client_pem:+ type: stringmodel:type: string+ ssl_verify:+ type: booleantype: objectrules:type: string@@ -2396,7 +2402,7 @@ components:type: objectinfo:title: marimo API- version: 0.11.23+ version: 0.11.26openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex f1ef4836c5..a7f628f0ff 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2773,7 +2773,10 @@ export interface components {open_ai?: {api_key?: string;base_url?: string;+ ca_bundle_path?: string;+ client_pem?: string;model?: string;+ ssl_verify?: boolean;};rules?: string;};diff --git a/tests/_server/api/endpoints/test_login.py b/tests/_server/api/endpoints/test_login.pynew file mode 100644index 0000000000..b32383c4fa--- /dev/null+++ b/tests/_server/api/endpoints/test_login.py@@ -0,0 +1,161 @@+from __future__ import annotations++from unittest.mock import patch++import pytest+from starlette.applications import Starlette+from starlette.authentication import (+ SimpleUser,+)+from starlette.middleware import Middleware+from starlette.middleware.authentication import (+ AuthenticationMiddleware,+)+from starlette.middleware.sessions import SessionMiddleware+from starlette.testclient import TestClient++from marimo._server.api.endpoints.login import router as auth_router+from marimo._server.api.middleware import AuthBackend+from marimo._server.router import APIRouter+from marimo._server.tokens import AuthToken+from tests._server.mocks import get_mock_session_manager++AUTH_TOKEN = AuthToken("test_password")+++def create_app(base_url: str = "") -> Starlette:+ router = APIRouter(prefix=base_url)+ router.include_router(auth_router)+ app = Starlette(+ routes=router.routes,+ middleware=[+ Middleware(+ SessionMiddleware,+ secret_key="test_secret",+ session_cookie="test_session",+ ),+ Middleware(+ AuthenticationMiddleware,+ backend=AuthBackend(should_authenticate=True),+ ),+ ],+ )+ app.state.session_manager = get_mock_session_manager()+ app.state.session_manager.auth_token = AUTH_TOKEN+ app.state.base_url = base_url+ return app+++def client() -> TestClient:+ return TestClient(create_app(base_url=""), follow_redirects=False)+++def test_login_page_returns_html(client: TestClient):+ response = client.get("/login")+ assert response.status_code == 200+ assert "Access Token / Password" in response.text+++def test_login_submit_with_valid_password(client: TestClient):+ response = client.post("/login", data={"password": str(AUTH_TOKEN)})+ assert response.status_code == 302, response.text+ assert response.headers["location"] == "/"+++def test_login_submit_with_invalid_password(client: TestClient):+ response = client.post("/login", data={"password": "wrong_password"})+ assert response.status_code == 200+ assert "Invalid password" in response.text+++def test_login_submit_with_empty_password(client: TestClient):+ response = client.post("/login", data={"password": ""})+ assert response.status_code == 200+ assert "Password is required" in response.text+++def test_login_submit_with_authenticated_user(client: TestClient):+ with patch(+ "starlette.requests.Request", return_value=True+ ) as mock_request:+ mock_request.user = SimpleUser("test_user")+ response = client.post("/login", data={"password": str(AUTH_TOKEN)})+ assert response.status_code == 302, response.text+ assert response.headers["location"] == "/"+++def test_login_submit_with_next_url(client: TestClient):+ response = client.post(+ "/login?next=/dashboard",+ data={"password": str(AUTH_TOKEN)},+ )+ assert response.status_code == 302, response.text+ assert response.headers["location"] == "/dashboard"+++def test_login_page_with_base_url():+ app = create_app(base_url="/app")+ client = TestClient(app, follow_redirects=False)+ response = client.get("/app/login")+ assert response.status_code == 200, response.text+ assert "Access Token / Password" in response.text+ assert 'action="/app/auth/login"' in response.text+++def test_login_submit_with_base_url():+ app = create_app(base_url="/app")+ client = TestClient(app, follow_redirects=False)+ response = client.post("/app/login", data={"password": str(AUTH_TOKEN)})+ assert response.status_code == 302, response.text+ assert response.headers["location"] == "/app/"+++def test_login_submit_with_base_url_trailing_slash():+ app = create_app(base_url="/app/")+ client = TestClient(app, follow_redirects=False)+ response = client.post("/app/login", data={"password": str(AUTH_TOKEN)})+ assert response.status_code == 302, response.text+ assert response.headers["location"] == "/app/"+++def test_login_submit_with_next_url_and_base_url():+ app = create_app(base_url="/app")+ client = TestClient(app, follow_redirects=False)+ response = client.post(+ "/app/login?next=/app/dashboard",+ data={"password": str(AUTH_TOKEN)},+ )+ assert response.status_code == 302, response.text+ assert response.headers["location"] == "/app/dashboard"+++def test_login_page_security_headers(client: TestClient):+ response = client.get("/login")+ assert response.status_code == 200+ assert response.headers["X-Frame-Options"] == "DENY"+ assert response.headers["X-Content-Type-Options"] == "nosniff"+++def test_login_submit_with_external_redirect(client: TestClient):+ response = client.post(+ "/login?next=https://evil.com",+ data={"password": str(AUTH_TOKEN)},+ )+ assert response.status_code == 302+ assert response.headers["location"] == "/"+++def test_login_submit_with_malformed_data(client: TestClient):+ response = client.post(+ "/login",+ content=b"invalid=form=data", # type: ignore+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert response.status_code == 200+ assert "Password is required" in response.text+++def test_login_page_method_not_allowed(client: TestClient):+ response = client.put("/login")+ assert response.status_code == 405