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
refactor: MPL proxy endpoint (#6632)
Dylan Madisetti0312706d5e59
diff --git a/SECURITY.md b/SECURITY.mdindex 1c3db26357..d6db0bf3d7 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -19,3 +19,5 @@ acknowledge the contributions of the following individuals for their reporting:- @AlexanderBarabanov- @pwntester- @s-celles+ - @acepace+ - @devgidiff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex d44513387f..46ca1f8820 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -17,6 +17,8 @@ import timefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Optional, Union+from starlette.responses import HTMLResponse, Response+from marimo import _loggersfrom marimo._output.builder import hfrom marimo._output.formatting import as_html@@ -208,9 +210,10 @@ def _convert_scheme_to_ws(url: str) -> str:def _template(fig_id: str, port: int) -> str:- base_url = _get_remote_url()- base_url_and_path = f"{base_url}/mpl/{port}"- ws_base_url = _convert_scheme_to_ws(base_url_and_path)+ base_url = _get_remote_url() or f"http://localhost:{port}/"+ base_url_and_path = f"{base_url}/mpl/{fig_id}"+ base_url_and_path_ws = f"{base_url}/mpl/{port}"+ ws_base_url = _convert_scheme_to_ws(base_url_and_path_ws)return html_content % {"ws_uri": f"{ws_base_url}/ws?figure={fig_id}",@@ -219,13 +222,32 @@ def _template(fig_id: str, port: int) -> str:}+async def mpl_js(request: Request) -> Response:+ from matplotlib.backends.backend_webagg_core import (+ FigureManagerWebAgg,+ )++ del request+ return Response(+ content=patch_javascript(FigureManagerWebAgg.get_javascript()), # type: ignore[no-untyped-call]+ media_type="application/javascript",+ )+++async def mpl_custom_css(request: Request) -> Response:+ del request+ return Response(+ content=css_content,+ media_type="text/css",+ )++def create_application() -> Starlette:import matplotlib as mplfrom matplotlib.backends.backend_webagg_core import (FigureManagerWebAgg,)from starlette.applications import Starlette- from starlette.responses import HTMLResponse, Responsefrom starlette.routing import Mount, Route, WebSocketRoutefrom starlette.staticfiles import StaticFilesfrom starlette.websockets import (@@ -240,20 +262,6 @@ def create_application() -> Starlette:content = _template(figure_id, port)return HTMLResponse(content=content)- async def mpl_js(request: Request) -> Response:- del request- return Response(- content=patch_javascript(FigureManagerWebAgg.get_javascript()), # type: ignore[no-untyped-call]- media_type="application/javascript",- )-- async def mpl_custom_css(request: Request) -> Response:- del request- return Response(- content=css_content,- media_type="text/css",- )-async def download(request: Request) -> Response:figure_id = request.query_params.get("figure")assert figure_id is not Nonediff --git a/marimo/_server/api/endpoints/mpl.py b/marimo/_server/api/endpoints/mpl.pynew file mode 100644index 0000000000..5d8ad7c595--- /dev/null+++ b/marimo/_server/api/endpoints/mpl.py@@ -0,0 +1,282 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+from functools import wraps+from pathlib import Path+from typing import TYPE_CHECKING, Any, Callable, Optional++import websockets+from starlette.responses import Response++# import StaticFiles from starlette+from starlette.staticfiles import StaticFiles++if TYPE_CHECKING:+ from collections.abc import Awaitable++ from starlette.requests import Request+ from starlette.websockets import WebSocket+++from marimo import _loggers+from marimo._server.router import APIRouter++LOGGER = _loggers.marimo_logger()++router = APIRouter()++figure_endpoints: dict[int, str] = {}+++def mpl_fallback_handler(+ path_prefix: str = "",+) -> Callable[+ [Callable[[Request], Awaitable[Response]]],+ Callable[[Request], Awaitable[Response]],+]:+ """+ Args:+ path_prefix: Prefix to add to path when calling _mpl_handler (default "")+ """++ def decorator(+ func: Callable[[Request], Awaitable[Response]],+ ) -> Callable[[Request], Awaitable[Response]]:+ @wraps(func)+ async def wrapper(request: Request) -> Response:+ figure_num = request.path_params["figure"]+ path = request.path_params.get("path", "")+ response: Optional[Response] = None++ if figure_num in figure_endpoints:+ full_path = path_prefix + path if path_prefix else path+ response = await _mpl_handler(request, full_path, figure_num)++ # Fallback if no response or non-200 status+ if response is None or response.status_code != 200:+ try:+ response = await func(request)+ except Exception as e:+ LOGGER.error(f"Error in fallback handler: {e}")+ response = Response(+ content="Internal server error",+ status_code=500,+ media_type="text/plain",+ )++ return response++ return wrapper++ return decorator++[email protected]("/mpl/{figure:int}/_static/{path:path}")+@mpl_fallback_handler("_static/")+async def mpl_static(request: Request) -> Response:+ """Fallback for static files from matplotlib."""+ path = request.path_params["path"]+ from matplotlib.backends.backend_webagg_core import (+ FigureManagerWebAgg,+ )++ static_app = StaticFiles(+ directory=FigureManagerWebAgg.get_static_file_path() # type: ignore[no-untyped-call]+ )+ return await static_app.get_response(path, request.scope)++[email protected]("/mpl/{figure:int}/_images/{path:path}")+@mpl_fallback_handler(path_prefix="_images/")+async def mpl_images(request: Request) -> Response:+ """Fallback for image files from matplotlib."""+ path = request.path_params["path"]+ import matplotlib as mpl++ static_app = StaticFiles(directory=Path(mpl.get_data_path(), "images"))+ return await static_app.get_response(path, request.scope)++[email protected]("/mpl/{figure:int}/mpl.js")+@mpl_fallback_handler()+async def mpl_js(request: Request) -> Response:+ """Fallback for mpl.js from marimo's internal handler."""+ from marimo._plugins.stateless.mpl._mpl import mpl_js++ return await mpl_js(request)++[email protected]("/mpl/{figure:int}/custom.css")+@mpl_fallback_handler()+async def mpl_custom_css(request: Request) -> Response:+ """Fallback for custom.css from marimo's internal handler."""+ from marimo._plugins.stateless.mpl._mpl import mpl_custom_css++ return await mpl_custom_css(request)+++async def _mpl_handler(+ request: Request, path: str, figurenum: int+) -> Response:+ """+ Unified proxy function for matplotlib server requests.++ Args:+ request: The incoming request+ path: The remaining path to proxy+ figurenum: The figure number++ Returns:+ Response from the matplotlib server or error response+ """+ # Proxy to matplotlib server+ # Determine the target port+ port = figure_endpoints.get(figurenum, None)++ if port is None:+ LOGGER.info(+ f"Security violation: Attempt to access unauthorized figure {figurenum}"+ )+ return Response(+ content="Unauthorized access",+ status_code=403,+ media_type="text/plain",+ )++ # Construct target URL+ target_url = f"http://localhost:{port}/{path}"+ LOGGER.debug(f"Proxying {request.method} -> {target_url}")++ # Prepare headers (exclude problematic headers)+ headers = {+ k: v+ for k, v in request.headers.items()+ if k.lower() not in ("host", "content-length")+ }++ try:+ import urllib.parse+ import urllib.request+ from urllib.error import URLError++ # Construct full URL with query parameters+ if request.query_params:+ query_string = urllib.parse.urlencode(request.query_params)+ full_url = f"{target_url}?{query_string}"+ else:+ full_url = target_url++ # Prepare request data+ data = None+ if request.method in ("POST", "PUT", "PATCH"):+ data = await request.body()++ # Create urllib request+ req = urllib.request.Request(+ full_url, data=data, headers=headers, method=request.method+ )++ # Execute request in thread pool to avoid blocking+ def _make_request() -> dict[str, Any]:+ try:+ with urllib.request.urlopen(req, timeout=30.0) as response:+ return {+ "status": response.status,+ "headers": dict(response.headers),+ "content": response.read(),+ }+ except URLError as e:+ raise ConnectionError() from e++ loop = asyncio.get_event_loop()+ response_data = await loop.run_in_executor(None, _make_request)++ return Response(+ content=response_data["content"],+ status_code=response_data["status"],+ headers=response_data["headers"],+ media_type=response_data["headers"].get("content-type"),+ )++ except ConnectionError:+ LOGGER.info(f"Failed to connect to matplotlib server at port {port}")+ return Response(+ content="Matplotlib server is not available. Please rerun this cell or restart the service.",+ status_code=503,+ media_type="text/plain",+ )+ except Exception as e:+ LOGGER.error(f"Error proxying to matplotlib server: {e}")+ return Response(+ content="Internal server error",+ status_code=500,+ media_type="text/plain",+ )++[email protected]("/mpl/{figure:int}/{path:path}")+async def mpl_handler(request: Request) -> Response:+ path = request.path_params["path"]+ figurenum = request.path_params["figure"]+ return await _mpl_handler(request, path, figurenum)++[email protected]("/mpl/{port}/ws")+async def mpl_websocket(websocket: WebSocket) -> None:+ """Proxy WebSocket connections to matplotlib server."""+ global figure_endpoints+ port = str(websocket.path_params["port"])++ await websocket.accept()++ # Construct target WebSocket URL with query parameters+ query_params = dict(websocket.query_params)+ query_string = "&".join(f"{k}={v}" for k, v in query_params.items())+ target_ws_url = f"ws://localhost:{port}/ws"+ if query_string:+ target_ws_url += f"?{query_string}"++ # get figure from query params+ figure_num = None+ try:+ figure_num = query_params.get("figure")+ if figure_num is not None:+ figure_endpoints[int(figure_num)] = f"{port}"+ except (TypeError, ValueError):+ LOGGER.warning(+ f"Invalid figure number in WebSocket connection: {query_params.get('figure')}"+ )+ pass++ try:+ async with websockets.connect(target_ws_url) as mpl_ws:++ async def forward_to_mpl() -> None:+ try:+ async for message in websocket.iter_text():+ await mpl_ws.send(message)+ except Exception as e:+ LOGGER.debug(f"Client->Server forwarding ended: {e}")++ async def forward_to_client() -> None:+ try:+ async for message in mpl_ws:+ if isinstance(message, bytes):+ await websocket.send_bytes(message)+ else:+ await websocket.send_text(message)+ except Exception as e:+ LOGGER.debug(f"Server->Client forwarding ended: {e}")++ await asyncio.gather(+ forward_to_mpl(), forward_to_client(), return_exceptions=True+ )++ except Exception as e:+ LOGGER.error(f"WebSocket proxy error: {e}")+ finally:+ try:+ await websocket.close()+ except Exception:+ passdiff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.pyindex 59945332af..3fb41cca40 100644--- a/marimo/_server/api/router.py+++ b/marimo/_server/api/router.py@@ -22,6 +22,7 @@ from marimo._server.api.endpoints.files import router as files_routerfrom marimo._server.api.endpoints.health import router as health_routerfrom marimo._server.api.endpoints.home import router as home_routerfrom marimo._server.api.endpoints.login import router as login_router+from marimo._server.api.endpoints.mpl import router as mpl_routerfrom marimo._server.api.endpoints.packages import router as packages_routerfrom marimo._server.api.endpoints.secrets import router as secrets_routerfrom marimo._server.api.endpoints.sql import router as sql_router@@ -73,6 +74,7 @@ def build_routes(base_url: str = "") -> list[BaseRoute]:)app_router.include_router(health_router, name="health")app_router.include_router(ws_router, name="ws")+ app_router.include_router(mpl_router, name="mpl")app_router.include_router(assets_router, name="assets")return app_router.routesdiff --git a/marimo/_server/main.py b/marimo/_server/main.pyindex 270ed80768..36374a3a7f 100644--- a/marimo/_server/main.py+++ b/marimo/_server/main.py@@ -22,7 +22,6 @@ from marimo._server.api.middleware import (ProxyMiddleware,SkewProtectionMiddleware,TimeoutMiddleware,- create_proxy_error_handler,)from marimo._server.api.router import build_routesfrom marimo._server.api.status import (@@ -91,7 +90,6 @@ def create_starlette_app(allow_methods=["*"],allow_headers=["*"],),- _create_mpl_proxy_middleware(base_url=base_url),])@@ -128,64 +126,6 @@ def create_starlette_app(return app-def _create_mpl_proxy_middleware(base_url: str) -> Middleware:- # Construct the full proxy path with base_url- # Normalize base_url to avoid double slashes- normalized_base_url = base_url.rstrip("/")- proxy_path = f"{normalized_base_url}/mpl"-- def mpl_target_url(path: str) -> str:- # Path format: {base_url}/mpl/<port>/rest/of/path- # Remove the proxy_path prefix to get /<port>/rest/of/path- if not path.startswith(proxy_path):- raise ValueError(- f"Path {path} does not start with proxy path {proxy_path}"- )-- remaining = path[len(proxy_path) :]- if not remaining.startswith("/"):- raise ValueError(f"Invalid MPL path format: {path}")-- # Parse /<port>/rest/of/path to get the port- parts = remaining.split("/")- if len(parts) < 2 or not parts[1]:- raise ValueError(f"Invalid MPL path format: {path}")-- port = parts[1]- return f"http://localhost:{port}"-- def mpl_path_rewrite(path: str) -> str:- # Remove the {base_url}/mpl/<port>/ prefix- # Remove the proxy_path prefix first- if not path.startswith(proxy_path):- return "/"-- remaining = path[len(proxy_path) :]- if not remaining.startswith("/"):- return "/"-- # Parse /<port>/rest/of/path and return /rest/of/path- parts = remaining.split("/")- if len(parts) < 2:- return "/"-- # Skip the empty first part and the port to get the rest- rest_parts = parts[2:]- return "/" + "/".join(rest_parts) if rest_parts else "/"-- mpl_error_handler = create_proxy_error_handler(- "Matplotlib server is not available. Please rerun this cell or restart the service."- )-- return Middleware(- ProxyMiddleware,- proxy_path=proxy_path,- target_url=mpl_target_url,- path_rewrite=mpl_path_rewrite,- connection_error_handler=mpl_error_handler,- )--def _create_lsps_proxy_middleware(*, servers: list[LspServer]) -> Iterator[Middleware]:diff --git a/marimo/_smoke_tests/iplot.py b/marimo/_smoke_tests/iplot.pyindex 432a525c84..807a89cf5f 100644--- a/marimo/_smoke_tests/iplot.py+++ b/marimo/_smoke_tests/iplot.py@@ -2,7 +2,7 @@import marimo-__generated_with = "0.15.5"+__generated_with = "0.16.3"app = marimo.App()diff --git a/tests/_cli/test_endpoint.py b/tests/_cli/test_endpoint.pynew file mode 100644index 0000000000..54bfb98724--- /dev/null+++ b/tests/_cli/test_endpoint.py@@ -0,0 +1,161 @@+import contextlib+import http.server+import os+import socket+import socketserver+import subprocess+import threading+import time+import urllib.error+from typing import Any+from urllib.request import Request, urlopen++import pytest+++def _get_free_port() -> int:+ with contextlib.closing(+ socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ ) as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++class _FixedResponseHandler(http.server.BaseHTTPRequestHandler):+ RESPONSE = b"HELLO_FROM_SIMPLE_SERVER"++ def do_GET(self): # noqa: N802+ self.send_response(200)+ self.send_header("Content-Type", "text/plain; charset=utf-8")+ self.send_header("Content-Length", str(len(self.RESPONSE)))+ self.end_headers()+ self.wfile.write(self.RESPONSE)++ # Silence default logging+ def log_message(self, *args: Any) -> None: # noqa: A003+ pass+++def _start_simple_server(+ port: int,+) -> tuple[socketserver.TCPServer, threading.Thread]:+ httpd = socketserver.TCPServer(("127.0.0.1", port), _FixedResponseHandler)+ httpd.allow_reuse_address = True++ thread = threading.Thread(target=httpd.serve_forever, daemon=True)+ thread.start()+ # Wait until the socket is accepting connections+ deadline = time.time() + 5+ while time.time() < deadline:+ with contextlib.suppress(Exception):+ with urlopen(f"http://127.0.0.1:{port}/", timeout=0.25) as r: # noqa: S310+ if r.status == 200:+ break+ time.sleep(0.05)+ return httpd, thread+++def _wait_for_http_up(url: str, timeout_s: float = 10.0) -> None:+ deadline = time.time() + timeout_s+ last_err = None+ while time.time() < deadline:+ try:+ with urlopen(url, timeout=0.5) as r: # noqa: S310+ if 200 <= r.status < 500:+ return+ except Exception as e: # noqa: BLE001+ last_err = e+ time.sleep(0.05)+ raise RuntimeError(+ f"Server at {url} did not come up in time: {last_err!r}"+ )+++def test_cli_edit_mpl_endpoint_does_not_proxy_simple_server() -> None:+ """+ Launch `marimo edit` with a longer timeout, start a simple HTTP server on `other_port`,+ curl 127.0.0.1:port/mpl/other_port, and assert the response is NOT the same as the+ content from the simple server. Then tear everything down cleanly.+ """+ port = _get_free_port()+ other_port = _get_free_port()+ assert port != other_port++ # Start simple server that returns a fixed body+ simple_server, simple_thread = _start_simple_server(other_port)++ # Launch marimo in headless mode with a long inactivity timeout+ env = os.environ.copy()+ cmd = [+ "marimo",+ "edit",+ "--no-token",+ "--headless",+ "--port",+ str(port),+ "--timeout",+ "60", # long enough that it won't self-terminate during the test+ ]+ p = subprocess.Popen( # noqa: S603+ cmd,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=False,+ )++ try:+ # Wait for marimo to be up (hit root; any 2xx-4xx indicates the HTTP server is live)+ _wait_for_http_up(f"http://127.0.0.1:{port}/", timeout_s=15)++ # Fetch from the simple server directly+ with urlopen(f"http://127.0.0.1:{other_port}/", timeout=3) as r: # noqa: S310+ direct_body = r.read()++ # "curl" the marimo mpl endpoint that references the other_port+ # If marimo is secure here, it should NOT proxy arbitrary localhost ports.+ mpl_url = f"http://127.0.0.1:{port}/mpl/{other_port}"+ with contextlib.suppress(Exception):+ # Small pause to avoid racey first-request startup work, if any+ time.sleep(0.1)+ # Use a plain GET; headers minimal+ req = Request(mpl_url, headers={"User-Agent": "pytest"})+ try:+ with urlopen(req, timeout=3) as r: # noqa: S310+ marimo_body = r.read()+ except urllib.error.HTTPError as e:+ marimo_body = e.read()++ # The content MUST NOT equal the simple server's body+ assert marimo_body != direct_body, (+ f"Unexpected: marimo endpoint {mpl_url} mirrored simple server content"+ )++ # Also ensure it's not trivially the fixed marker+ assert b"HELLO_FROM_SIMPLE_SERVER" not in marimo_body++ finally:+ # Teardown marimo+ if p.poll() is None:+ with contextlib.suppress(Exception):+ p.terminate()+ try:+ p.wait(timeout=5)+ except Exception:+ with contextlib.suppress(Exception):+ p.kill()+ # Drain pipes to avoid hanging subprocess objects on some platforms+ with contextlib.suppress(Exception):+ if p.stdout:+ _ = p.stdout.read()+ with contextlib.suppress(Exception):+ if p.stderr:+ _ = p.stderr.read()++ # Teardown simple server+ with contextlib.suppress(Exception):+ simple_server.shutdown()+ with contextlib.suppress(Exception):+ simple_server.server_close()+ with contextlib.suppress(Exception):+ simple_thread.join(timeout=5)diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.pyindex c862574a28..9123ca6bf2 100644--- a/tests/_plugins/stateless/test_mpl.py+++ b/tests/_plugins/stateless/test_mpl.py@@ -182,8 +182,7 @@ def test_template_with_remote_url() -> None:result = _template("test_fig", 8080)assert "wss://example.com/mpl/8080/ws?figure=test_fig" in result- assert "test_fig" in result- assert "https://example.com/mpl/8080" in result+ assert "://example.com/mpl/test_fig" in resultdef test_template_without_remote_url() -> None:@@ -195,8 +194,7 @@ def test_template_without_remote_url() -> None:result = _template("test_fig", 8080)assert "/mpl/8080/ws?figure=test_fig" in result- assert "test_fig" in result- assert "/mpl/8080" in result+ assert "/mpl/test_fig" in resultdef test_template_contains_html_structure() -> None:diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.pyindex 871e285f11..0a78909209 100644--- a/tests/_server/api/test_middleware.py+++ b/tests/_server/api/test_middleware.py@@ -6,7 +6,7 @@ import jsonimport sysimport timefrom multiprocessing import Process-from typing import TYPE_CHECKING, Any, Callable+from typing import TYPE_CHECKING, Anyimport pytestimport uvicorn@@ -24,7 +24,6 @@ from marimo._server.api.middleware import (_URLRequest,)from marimo._server.main import (- _create_mpl_proxy_middleware,create_starlette_app,)from marimo._server.model import SessionMode@@ -673,196 +672,3 @@ class TestProxyMiddleware:assert proxy_calls[-1] == "wss://example.com/proxy/test"# Could be good to go on to test the happy path for mpl but we're already doing that with the test client above so leaving just this invalid ID test for---class TestMplProxyMiddleware:- def test_mpl_proxy_middleware_no_base_url(self):- """Test MPL proxy middleware with empty base_url."""- middleware = _create_mpl_proxy_middleware("")-- # Check that the middleware is created correctly- assert middleware.cls == ProxyMiddleware- assert middleware.kwargs["proxy_path"] == "/mpl"-- # Test target_url function- target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]- assert (- target_url_func("/mpl/8080/some/path") == "http://localhost:8080"- )-- # Test path_rewrite function- path_rewrite_func: Callable[[str], str] = middleware.kwargs[- "path_rewrite"- ]- assert path_rewrite_func("/mpl/8080/some/path") == "/some/path"- assert path_rewrite_func("/mpl/8080/") == "/"- assert path_rewrite_func("/mpl/8080") == "/"-- def test_mpl_proxy_middleware_with_base_url(self):- """Test MPL proxy middleware with base_url."""- middleware = _create_mpl_proxy_middleware("/foo")-- # Check that the middleware is created correctly- assert middleware.cls == ProxyMiddleware- assert middleware.kwargs["proxy_path"] == "/foo/mpl"-- # Test target_url function- target_url_func = middleware.kwargs["target_url"]- assert (- target_url_func("/foo/mpl/8080/some/path")- == "http://localhost:8080"- )-- # Test path_rewrite function- path_rewrite_func: Callable[[str], str] = middleware.kwargs[- "path_rewrite"- ]- assert path_rewrite_func("/foo/mpl/8080/some/path") == "/some/path"- assert path_rewrite_func("/foo/mpl/8080/") == "/"- assert path_rewrite_func("/foo/mpl/8080") == "/"-- def test_mpl_proxy_middleware_with_base_url_trailing_slash(self):- """Test MPL proxy middleware with base_url that has trailing slash."""- middleware = _create_mpl_proxy_middleware("/foo/")-- # Check that the middleware is created correctly- assert middleware.cls == ProxyMiddleware- assert middleware.kwargs["proxy_path"] == "/foo/mpl"-- # Test target_url function- target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]- assert (- target_url_func("/foo/mpl/8080/some/path")- == "http://localhost:8080"- )-- # Test path_rewrite function- path_rewrite_func = middleware.kwargs["path_rewrite"]- assert path_rewrite_func("/foo/mpl/8080/some/path") == "/some/path"-- def test_mpl_proxy_middleware_complex_paths(self):- """Test MPL proxy middleware with complex paths."""- middleware = _create_mpl_proxy_middleware("/api/v1")-- # Check that the middleware is created correctly- assert middleware.cls == ProxyMiddleware- assert middleware.kwargs["proxy_path"] == "/api/v1/mpl"-- # Test target_url function- target_url_func = middleware.kwargs["target_url"]- assert (- target_url_func("/api/v1/mpl/9000/static/css/style.css")- == "http://localhost:9000"- )-- # Test path_rewrite function- path_rewrite_func: Callable[[str], str] = middleware.kwargs[- "path_rewrite"- ]- assert (- path_rewrite_func("/api/v1/mpl/9000/static/css/style.css")- == "/static/css/style.css"- )-- def test_mpl_proxy_middleware_target_url_errors(self):- """Test error cases for target_url function."""- middleware = _create_mpl_proxy_middleware("/foo")- target_url_func = middleware.kwargs["target_url"]-- # Test with wrong prefix- with pytest.raises(- ValueError,- match="Path /bar/mpl/8080/path does not start with proxy path /foo/mpl",- ):- target_url_func("/bar/mpl/8080/path")-- # Test with no port- with pytest.raises(ValueError, match="Invalid MPL path format"):- target_url_func("/foo/mpl/")-- # Test with no slash after proxy_path- with pytest.raises(ValueError, match="Invalid MPL path format"):- target_url_func("/foo/mpl8080/path")-- def test_mpl_proxy_middleware_path_rewrite_edge_cases(self):- """Test edge cases for path_rewrite function."""- middleware = _create_mpl_proxy_middleware("/foo")- path_rewrite_func: Callable[[str], str] = middleware.kwargs[- "path_rewrite"- ]-- # Test with wrong prefix - should return "/"- assert path_rewrite_func("/bar/mpl/8080/path") == "/"-- # Test with no slash after proxy_path - should return "/"- assert path_rewrite_func("/foo/mpl8080/path") == "/"-- # Test with incomplete path - should return "/"- assert path_rewrite_func("/foo/mpl/") == "/"-- # Test with just the port - should return "/"- assert path_rewrite_func("/foo/mpl/8080") == "/"-- def test_mpl_proxy_middleware_root_base_url(self):- """Test MPL proxy middleware with root base_url."""- middleware = _create_mpl_proxy_middleware("/")-- # Check that the middleware is created correctly- assert middleware.cls == ProxyMiddleware- assert middleware.kwargs["proxy_path"] == "/mpl"-- # Test target_url function- target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]- assert (- target_url_func("/mpl/8080/some/path") == "http://localhost:8080"- )-- # Test path_rewrite function- path_rewrite_func: Callable[[str], str] = middleware.kwargs[- "path_rewrite"- ]- assert path_rewrite_func("/mpl/8080/some/path") == "/some/path"-- def test_mpl_proxy_middleware_integration_with_base_url(self):- """Test MPL proxy middleware integration with base_url in a real app."""- # Create app with base_url- app = create_starlette_app(base_url="/api/v1")- app.state.session_manager = get_mock_session_manager()- app.state.config_manager = MarimoConfigManager(UserConfigManager())-- # Mock out the server- uvicorn_server = uvicorn.Server(uvicorn.Config(app))- uvicorn_server.servers = []-- app.state.server = uvicorn_server- app.state.host = "localhost"- app.state.port = 1234- app.state.base_url = "/api/v1"-- client = TestClient(app)-- # Test that regular API routes still work with base_url- response = client.get("/api/v1/health")- assert response.status_code == 200-- # Test that routes without base_url don't work- response = client.get("/health")- assert response.status_code == 404-- # Test that the MPL proxy middleware is properly configured by- # verifying that it would handle the expected paths correctly- middleware = _create_mpl_proxy_middleware("/api/v1")- target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]- path_rewrite_func: Callable[[str], str] = middleware.kwargs[- "path_rewrite"- ]-- # These should work with the base_url- assert (- target_url_func("/api/v1/mpl/8080/static/file.js")- == "http://localhost:8080"- )- assert (- path_rewrite_func("/api/v1/mpl/8080/static/file.js")- == "/static/file.js"- )