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: preserve user defined user in mo.app_meta().request (#3789)
Myles Scolnick1a2d004f5f03
diff --git a/docs/guides/deploying/programmatically.md b/docs/guides/deploying/programmatically.mdindex 0a3c97132a..4764ad0b2d 100644--- a/docs/guides/deploying/programmatically.md+++ b/docs/guides/deploying/programmatically.md@@ -99,6 +99,12 @@ class AuthMiddleware(BaseHTTPMiddleware):"username": "example_user",# Add any other user data}++ # Optional add metadata to the request+ request.scope["meta"] = {+ "some_key": "some_value",+ }+response = await call_next(request)return response@@ -114,3 +120,4 @@ The `request` object provides access to:- `request.path_params`: Path parameters- `request.user`: User data added by authentication middleware- `request.url`: URL information including path, query parameters+- `request.meta`: Metadata added by your custom middlewarediff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 14d1741599..26e01dac35 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -51,6 +51,7 @@ class HTTPRequest(Mapping[str, Any]):query_params: dict[str, list[str]] # Raw query paramspath_params: dict[str, Any]cookies: dict[str, str]+ meta: dict[str, Any]user: Any# We don't include session or auth because they may contain@@ -114,6 +115,7 @@ class HTTPRequest(Mapping[str, Any]):path_params=request.path_params,cookies=request.cookies,user=request["user"] if "user" in request else {},+ meta=request["meta"] if "meta" in request else {},# Left out for now. This may contain information that the app author# does not want to expose.# session=request.session if "session" in request else {},diff --git a/marimo/_server/api/auth.py b/marimo/_server/api/auth.pyindex d0d00ee18b..fc04c92ce3 100644--- a/marimo/_server/api/auth.py+++ b/marimo/_server/api/auth.py@@ -10,6 +10,7 @@ import starletteimport starlette.status as statusfrom starlette.datastructures import Secretfrom starlette.exceptions import HTTPException+from starlette.middleware.authentication import AuthenticationMiddlewarefrom starlette.middleware.sessions import SessionMiddlewarefrom starlette.responses import JSONResponse@@ -215,3 +216,35 @@ class CustomSessionMiddleware(SessionMiddleware):)return await super().__call__(scope, receive, send)+++# Wrapper around starlette's AuthenticationMiddleware to+# restore the 'user' key in the request object if one was+# set by prior middleware+class CustomAuthenticationMiddleware(AuthenticationMiddleware):+ KEY = "_marimo_prev_user"++ def __init__(self, app: ASGIApp, *args: Any, **kwargs: Any) -> None:+ # The AuthenticationMiddleware sets the 'user' key in the scope, but+ # we want to keep the developer-defined user in the scope so that+ async def wrapped_app(+ scope: Scope, receive: Receive, send: Send+ ) -> None:+ # Get the developer-defined that we saved earlier+ developer_defined_user = scope.get(self.KEY)+ # Store it back in the scope+ scope["user"] = developer_defined_user+ await app(scope, receive, send)++ super().__init__(wrapped_app, *args, **kwargs)++ async def __call__(+ self, scope: Scope, receive: Receive, send: Send+ ) -> None:+ # If a developer has defined a user, store it in scope+ # so that the wrapped app can access it+ developer_defined_user = scope.get("user")+ scope[self.KEY] = developer_defined_user+ await super().__call__(scope, receive, send)+ # Delete the key from scope+ del scope[self.KEY]diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex 5043fa9e73..9dd4f31f68 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -54,8 +54,6 @@ class AuthBackend(AuthenticationBackend):async def authenticate(self, conn: HTTPConnection) -> Optional[tuple["AuthCredentials", "BaseUser"]]:- mode = AppStateBase(conn.app.state).session_manager.mode-# We may not need to authenticate. This can be disabled# because the user is running in a trusted environment# or authentication is handled by a layer above us@@ -67,6 +65,8 @@ class AuthBackend(AuthenticationBackend):if not valid:return None+ mode = AppStateBase(conn.app.state).session_manager.mode+# User's get Read access in Run modeif mode == SessionMode.RUN:return AuthCredentials(["read"]), SimpleUser("user")diff --git a/marimo/_server/main.py b/marimo/_server/main.pyindex 8f7568c876..1592e6410d 100644--- a/marimo/_server/main.py+++ b/marimo/_server/main.py@@ -6,12 +6,12 @@ from typing import TYPE_CHECKING, List, Optionalfrom starlette.applications import Starlettefrom starlette.exceptions import HTTPExceptionfrom starlette.middleware import Middleware-from starlette.middleware.authentication import AuthenticationMiddlewarefrom starlette.middleware.cors import CORSMiddlewarefrom marimo import _loggersfrom marimo._server.api.auth import (RANDOM_SECRET,+ CustomAuthenticationMiddleware,CustomSessionMiddleware,on_auth_error,)@@ -65,7 +65,7 @@ def create_starlette_app([Middleware(OpenTelemetryMiddleware),Middleware(- AuthenticationMiddleware,+ CustomAuthenticationMiddleware,backend=AuthBackend(should_authenticate=enable_auth),on_error=on_auth_error,),diff --git a/marimo/_smoke_tests/requests.py b/marimo/_smoke_tests/requests.pyindex 06afb2ba9c..0632de88d0 100644--- a/marimo/_smoke_tests/requests.py+++ b/marimo/_smoke_tests/requests.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.10.17"+__generated_with = "0.11.3"app = marimo.App(width="medium")@@ -21,7 +21,7 @@ def _(mo):def _(mo, refresh):refreshuser = mo.app_meta().request.user- [user, user.is_authenticated, user.display_name]+ [user]return (user,)diff --git a/tests/_messaging/test_context_vars.py b/tests/_messaging/test_context_vars.pyindex 59a8bbd45e..850b879156 100644--- a/tests/_messaging/test_context_vars.py+++ b/tests/_messaging/test_context_vars.py@@ -54,6 +54,7 @@ class TestHTTPRequestContext:user={"is_authenticated": True},headers={},query_params={},+ meta={},)def test_http_request_context(self, mock_request: HTTPRequest):@@ -69,6 +70,7 @@ class TestHTTPRequestContext:user={"is_authenticated": True},headers={},query_params={},+ meta={},)with http_request_context(mock_request):diff --git a/tests/_runtime/test_requests.py b/tests/_runtime/test_requests.pyindex 9c40f6cbf8..a4202a1964 100644--- a/tests/_runtime/test_requests.py+++ b/tests/_runtime/test_requests.py@@ -56,6 +56,7 @@ def test_http_request_like_basic_mapping():path_params={},cookies={},user={"is_authenticated": True},+ meta={},)assert request["url"] == {"path": "/test"}@@ -67,6 +68,7 @@ def test_http_request_like_basic_mapping():"path_params","cookies","user",+ "meta",}@@ -137,6 +139,7 @@ def test_display():path_params={},cookies={},user={"is_authenticated": True},+ meta={},)display_dict = request._display_()diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex 083b1f7858..a053230eb5 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -189,6 +189,7 @@ class TestExecutionRoutes_EditMode:"cookies","headers","user",+ "meta","path_params","query_params","url",@@ -198,8 +199,8 @@ class TestExecutionRoutes_EditMode:"marimo" not in headerfor header in app_meta_response["headers"].keys())- # Check user is True- assert app_meta_response["user"] is True+ # Check user is False+ assert app_meta_response["user"] is Falseclass TestExecutionRoutes_RunMode:diff --git a/tests/_server/api/test_auth.py b/tests/_server/api/test_auth.pyindex 4e88ab3d78..da6c721ba1 100644--- a/tests/_server/api/test_auth.py+++ b/tests/_server/api/test_auth.py@@ -5,15 +5,18 @@ from typing import Anyimport pytestfrom starlette.applications import Starlette+from starlette.authentication import SimpleUserfrom starlette.datastructures import Headers, QueryParamsfrom starlette.requests import HTTPConnectionfrom marimo._config.manager import UserConfigManagerfrom marimo._server.api.auth import (AppState,+ CustomAuthenticationMiddleware,CustomSessionMiddleware,validate_auth,)+from marimo._server.api.middleware import AuthBackendfrom marimo._server.main import create_starlette_appfrom tests._server.mocks import get_mock_session_manager@@ -140,3 +143,52 @@ async def test_validate_auth_with_no_auth(app: Starlette):# Run all middlewareawait app.build_middleware_stack()(conn.scope, mock_receive, mock_send)assert validate_auth(conn) is False+++async def test_custom_auth_middleware_preserves_user():+ app = Starlette()+ app.state.session_manager = get_mock_session_manager()++ async def test_app(scope: Any, receive: Any, send: Any) -> None:+ del receive, send+ # Verify the user was swapped during middleware execution+ assert scope["user"].username == "test_user"+ assert (+ scope[CustomAuthenticationMiddleware.KEY].username == "test_user"+ )++ middleware = CustomAuthenticationMiddleware(+ test_app, backend=AuthBackend(should_authenticate=False)+ )+ scope = {+ "type": "http",+ "user": SimpleUser("test_user"),+ "app": app,+ "path": "/",+ }++ await middleware(scope, mock_receive, mock_send)+ # Verify original user was restored and temp key was cleaned up+ assert scope["user"].username == "test_user"+ assert CustomAuthenticationMiddleware.KEY not in scope+++async def test_custom_auth_middleware_without_user():+ app = Starlette()+ app.state.session_manager = get_mock_session_manager()++ async def test_app(scope: Any, receive: Any, send: Any) -> None:+ del receive, send+ assert scope["user"] is None++ middleware = CustomAuthenticationMiddleware(+ test_app, backend=AuthBackend(should_authenticate=False)+ )+ scope = {+ "type": "http",+ "app": app,+ "path": "/",+ }++ await middleware(scope, mock_receive, mock_send)+ assert CustomAuthenticationMiddleware.KEY not in scope