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(server): don't trigger browser auth popup for API requests (#7629)
Myles Scolnick57b71231c667
diff --git a/marimo/_server/errors.py b/marimo/_server/errors.pyindex 9d8e31cc70..8a0833eff3 100644--- a/marimo/_server/errors.py+++ b/marimo/_server/errors.py@@ -25,6 +25,21 @@ if TYPE_CHECKING:LOGGER = _loggers.marimo_logger()+def _is_api_request(request: Request) -> bool:+ """Check if the request is an API request (not a page navigation)."""+ # Check path+ path = request.scope.get("path", "")+ if path.startswith("/api/"):+ return True++ # Check Accept header for application/json (case-insensitive)+ accept = request.headers.get("accept", "")+ if "application/json" in accept.lower():+ return True++ return False++# Convert exceptions to JSON responses# In the case of a ModuleNotFoundError, we try to send a MissingPackageAlert to the client# to install the missing package@@ -32,10 +47,18 @@ async def handle_error(request: Request, response: Any) -> Any:if isinstance(response, HTTPException):# Turn 403s into 401s to collect authif response.status_code == 403:+ # Only include WWW-Authenticate header for page requests,+ # not API requests. The WWW-Authenticate header triggers+ # browser Basic Auth popup, which is undesirable for API calls.+ headers = (+ None+ if _is_api_request(request)+ else {"WWW-Authenticate": "Basic"}+ )return JSONResponse(status_code=401,content={"detail": "Authorization header required"},- headers={"WWW-Authenticate": "Basic"},+ headers=headers,)return JSONResponse({"detail": response.detail},diff --git a/tests/_server/test_errors.py b/tests/_server/test_errors.pyindex 5ce9c0ec4e..a959d5bc91 100644--- a/tests/_server/test_errors.py+++ b/tests/_server/test_errors.py@@ -11,14 +11,58 @@ from marimo._session.model import SessionModefrom marimo._utils.http import HTTPException as MarimoHTTPException-async def test_http_exception():- # Test 403 to 401 conversion+async def test_http_exception_403_page_request():+ """Page requests should get 401 with WWW-Authenticate header to trigger browser auth"""exc = HTTPException(status_code=403)- response = await handle_error(Request({"type": "http"}), exc)+ # Non-API request (page load)+ request = Request(+ {+ "type": "http",+ "path": "/",+ "headers": [(b"accept", b"text/html")],+ }+ )+ response = await handle_error(request, exc)assert response.status_code == 401assert response.body == b'{"detail":"Authorization header required"}'assert response.headers["WWW-Authenticate"] == "Basic"++async def test_http_exception_403_api_request_by_path():+ """API requests should get 401 without WWW-Authenticate header"""+ exc = HTTPException(status_code=403)+ # API request detected by path+ request = Request(+ {+ "type": "http",+ "path": "/api/kernel/code_autocomplete",+ "headers": [],+ }+ )+ response = await handle_error(request, exc)+ assert response.status_code == 401+ assert response.body == b'{"detail":"Authorization header required"}'+ assert "WWW-Authenticate" not in response.headers+++async def test_http_exception_403_api_request_by_accept_header():+ """API requests with Accept: application/json should get 401 without WWW-Authenticate"""+ exc = HTTPException(status_code=403)+ # API request detected by Accept header+ request = Request(+ {+ "type": "http",+ "path": "/some/path",+ "headers": [(b"accept", b"application/json")],+ }+ )+ response = await handle_error(request, exc)+ assert response.status_code == 401+ assert response.body == b'{"detail":"Authorization header required"}'+ assert "WWW-Authenticate" not in response.headers+++async def test_http_exception_other():# Test other HTTP exceptionsexc = HTTPException(status_code=404, detail="Not found")response = await handle_error(Request({"type": "http"}), exc)