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: keep with_dynamic_directory serving after a directory symlink swap (#10015)
Myles Scolnick4a621fafab97
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex 1eac5d9188..3a2d57a178 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -108,14 +108,6 @@ class DynamicDirectoryMiddleware:"Using path='/' or path='' is not supported.")self.directory = Path(directory)- # Precompute the resolved directory so we don't hit the filesystem- # on every request. Fall back to an absolute path if resolve()- # fails (e.g., broken symlink), so the middleware still starts- # and per-request checks can handle resolution errors.- try:- self._resolved_directory = self.directory.resolve()- except (RuntimeError, OSError):- self._resolved_directory = self.directory.absolute()self.app_builder = app_builderself._app_cache: dict[str, ASGIApp] = {}self.validate_callback = validate_callback@@ -144,9 +136,16 @@ class DynamicDirectoryMiddleware:return RedirectResponse(url=redirect_url, status_code=307)def _is_within_directory(self, path: Path) -> bool:- """Check that path resolves to a location within self.directory."""+ """Check that `path` resolves to a location within the directory.++ Resolve the directory live rather than caching it at init, so the+ check keeps working when the directory is reached through a symlink+ that is swapped at runtime (atomic deploys, k8s mounts, git-sync).+ Both sides are still fully resolved, so `..` and escaping-symlink+ traversal is still rejected.+ """try:- path.resolve().relative_to(self._resolved_directory)+ path.resolve().relative_to(self.directory.resolve())return Trueexcept (ValueError, RuntimeError, OSError):return Falsediff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.pyindex f514956207..c850dc27fa 100644--- a/tests/_server/test_asgi.py+++ b/tests/_server/test_asgi.py@@ -875,6 +875,107 @@ class TestDynamicDirectoryMiddleware(unittest.TestCase):assert response.headers["x-custom-middleware"] == "applied"+class TestDynamicDirectoryMiddlewareSymlink(unittest.TestCase):+ """Symlinked-directory behavior for DynamicDirectoryMiddleware (#10012)."""++ def setUp(self) -> None:+ self.temp_dir = Path(tempfile.mkdtemp())++ def tearDown(self) -> None:+ shutil.rmtree(self.temp_dir, ignore_errors=True)++ def _build_client(self, directory: Path) -> TestClient:+ base_app = Starlette()++ async def catch_all(request: Request) -> Response:+ del request+ return PlainTextResponse("Not Found", status_code=404)++ base_app.add_route("/{path:path}", catch_all)++ def app_builder(base_url: str, file_path: str) -> Starlette:+ del base_url+ app = Starlette()++ async def handle(request: Request) -> Response:+ del request+ return PlainTextResponse(f"App from {Path(file_path).stem}")++ app.add_route("/{path:path}", handle)+ return app++ middleware = DynamicDirectoryMiddleware(+ app=base_app,+ base_path="/apps",+ directory=str(directory),+ app_builder=app_builder,+ )+ return TestClient(middleware)++ def test_symlink_swap_continues_serving(self) -> None:+ """Notebooks keep serving after the directory symlink is swapped."""+ releases = self.temp_dir / "releases"+ (releases / "v1").mkdir(parents=True)+ (releases / "v2").mkdir(parents=True)+ (releases / "v1" / "nb.py").write_text(contents)+ (releases / "v2" / "nb.py").write_text(contents)++ served = self.temp_dir / "notebooks"+ try:+ os.symlink(releases / "v1", served, target_is_directory=True)+ except (OSError, NotImplementedError):+ pytest.skip("Symlinks not supported on this platform")++ client = self._build_client(served)++ response = client.get("/apps/nb/")+ assert response.status_code == 200+ assert response.text == "App from nb"++ # Re-point the symlink at a new release. Remove + recreate rather+ # than os.replace, which can't overwrite an existing directory+ # symlink on Windows. A directory symlink is removed with rmdir on+ # Windows and unlink on POSIX.+ if sys.platform == "win32":+ os.rmdir(served)+ else:+ served.unlink()+ os.symlink(releases / "v2", served, target_is_directory=True)++ # Still served (regressed to 404 before the fix).+ response = client.get("/apps/nb/")+ assert response.status_code == 200+ assert response.text == "App from nb"++ def test_symlink_escape_is_blocked(self) -> None:+ """A symlink that escapes the served directory is still rejected."""+ served = self.temp_dir / "served"+ served.mkdir()+ (served / "ok.py").write_text(contents)++ secret_dir = self.temp_dir / "secret"+ secret_dir.mkdir()+ (secret_dir / "secret.py").write_text(contents)++ try:+ os.symlink(secret_dir, served / "escape", target_is_directory=True)+ except (OSError, NotImplementedError):+ pytest.skip("Symlinks not supported on this platform")++ client = self._build_client(served)++ # In-tree notebook serves; the escaping one does not, even though it+ # exists through the symlink.+ response = client.get("/apps/ok/")+ assert response.status_code == 200+ assert response.text == "App from ok"++ assert (served / "escape" / "secret.py").exists()+ response = client.get("/apps/escape/secret/")+ assert response.status_code == 404+ assert response.text == "Not Found"++class TestDynamicDirectoryMiddlewareSubMount(unittest.TestCase):"""Test DynamicDirectoryMiddleware when mounted at a sub-path.