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: with_dynamic_directory path traversal (#9162)
Myles Scolnickd9cdc57d5e30
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex 5334006bdb..7565891255 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -108,6 +108,14 @@ 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@@ -135,16 +143,35 @@ class DynamicDirectoryMiddleware:LOGGER.debug(f"Redirecting to: {redirect_url}")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."""+ try:+ path.resolve().relative_to(self._resolved_directory)+ return True+ except (ValueError, RuntimeError, OSError):+ return False+def _find_matching_file(self, relative_path: str) -> tuple[Path, str] | None:"""Find a matching Python file in the directory structure.Returns tuple of (matching file, remaining path) if found, None otherwise."""+ # Reject path traversal segments. Normalize "\" to "/" so the check+ # also catches backslash segments, which Windows treats as path+ # separators (e.g. "..\\secret" via %5C in the URL).+ segments = relative_path.replace("\\", "/").split("/")+ if ".." in segments:+ return None+# Try direct match first, skip if relative path has an extensionif not Path(relative_path).suffix:direct_match = self.directory / f"{relative_path}.py"- if not direct_match.name.startswith("_") and direct_match.exists():+ if (+ not direct_match.name.startswith("_")+ and self._is_within_directory(direct_match)+ and direct_match.exists()+ ):return (direct_match, "")# Try nested path by progressively checking each part@@ -159,6 +186,7 @@ class DynamicDirectoryMiddleware:if (cache_key in self._app_cacheand not potential_path.name.startswith("_")+ and self._is_within_directory(potential_path)):return (potential_path.with_suffix(".py"), "/".join(remaining))diff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.pyindex ee62e66672..f514956207 100644--- a/tests/_server/test_asgi.py+++ b/tests/_server/test_asgi.py@@ -1,6 +1,7 @@from __future__ import annotationsimport os+import shutilimport sysimport tempfileimport unittest@@ -512,6 +513,55 @@ class TestDynamicDirectoryMiddleware(unittest.TestCase):assert response.status_code == 404assert response.text == "Not Found"+ def test_path_traversal_blocked(self):+ # Create a dedicated sibling directory with a unique name to hold+ # the "outside" file, so we don't clobber files in the shared+ # parent directory and are safe under parallel test runs.+ parent_dir = Path(self.temp_dir).parent+ outside_dir = Path(tempfile.mkdtemp(dir=parent_dir))+ outside_name = outside_dir.name+ (outside_dir / "secret.py").write_text(contents)+ try:+ # Raw traversal+ response = self.client.get(f"/apps/../{outside_name}/secret/")+ assert response.status_code == 404+ assert response.text == "Not Found"++ # URL-encoded traversal (%2e%2e = ..)+ response = self.client.get(f"/apps/%2e%2e/{outside_name}/secret/")+ assert response.status_code == 404+ assert response.text == "Not Found"++ # Double-encoded+ response = self.client.get(+ f"/apps/%252e%252e/{outside_name}/secret/"+ )+ assert response.status_code == 404+ assert response.text == "Not Found"++ # Nested traversal+ response = self.client.get(+ f"/apps/nested/../../{outside_name}/secret/"+ )+ assert response.status_code == 404+ assert response.text == "Not Found"+ finally:+ shutil.rmtree(outside_dir, ignore_errors=True)++ def test_path_traversal_blocked_backslash(self):+ # Windows treats "\" as a path separator, so URLs like+ # "/apps/..%5Csecret/" (%5C = "\") could bypass a naive "/"-only+ # check. Call _find_matching_file directly since httpx/starlette+ # would otherwise reject or normalize the raw URL before it+ # reaches the middleware.+ middleware = self.app_with_middleware+ assert middleware._find_matching_file("..\\secret") is None+ assert middleware._find_matching_file("foo\\..\\secret") is None+ assert middleware._find_matching_file("nested\\..\\..\\secret") is None+ # Mixed separators+ assert middleware._find_matching_file("..\\..\\secret") is None+ assert middleware._find_matching_file("foo/..\\secret") is None+def test_valid_app_path(self):response = self.client.get("/apps/test_app/")assert response.status_code == 200