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: 'marimo edit' for absolute directory (#7291)
Myles Scolnick31f63cc8060a
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex 06075972ab..fa8574fa36 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -16,6 +16,7 @@ from marimo._config.manager import get_default_config_managerfrom marimo._output.utils import uri_decode_component, uri_encode_componentfrom marimo._runtime.virtual_file import EMPTY_VIRTUAL_FILE, read_virtual_filefrom marimo._server.api.deps import AppState+from marimo._server.file_router import validate_inside_directoryfrom marimo._server.router import APIRouterfrom marimo._server.templates.templates import (home_page_template,@@ -270,8 +271,8 @@ async def serve_public_file(request: Request) -> Response:# Security check: ensure file is inside public directorytry:- file_path.relative_to(public_dir.resolve())- except ValueError:+ validate_inside_directory(public_dir, file_path)+ except HTTPException:return Response(status_code=403, content="Access denied")if file_path.is_file() and not file_path.is_symlink():diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.pyindex a46c117d68..f3d64b7fcc 100644--- a/marimo/_server/file_router.py+++ b/marimo/_server/file_router.py@@ -3,9 +3,9 @@ from __future__ import annotationsimport abcimport os-import pathlibimport signalfrom contextlib import contextmanager+from pathlib import Pathfrom typing import TYPE_CHECKING, Optionalfrom marimo import _loggers@@ -189,7 +189,7 @@ class ListOfFilesAppFileRouter(AppFileRouter):class LazyListOfFilesAppFileRouter(AppFileRouter):def __init__(self, directory: str, include_markdown: bool) -> None:# pass through Path to canonicalize, strips trailing slashes- self._directory = str(pathlib.Path(directory))+ self._directory = str(Path(directory))self.include_markdown = include_markdownself._lazy_files: Optional[list[FileInfo]] = None@@ -210,6 +210,53 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):def mark_stale(self) -> None:self._lazy_files = None+ def get_file_manager(+ self,+ key: MarimoFileKey,+ default_width: WidthType | None = None,+ default_auto_download: list[ExportType] | None = None,+ default_sql_output: SqlOutputType | None = None,+ ) -> AppFileManager:+ """+ Given a key, return an AppFileManager.++ For directory routers, if the key is a relative path, resolve it+ relative to the router's directory. Absolute paths must be within+ the router's directory for security.+ """+ if key.startswith(AppFileRouter.NEW_FILE):+ return AppFileManager(+ None,+ default_width=default_width,+ default_auto_download=default_auto_download,+ default_sql_output=default_sql_output,+ )++ directory = Path(self._directory)+ filepath = Path(key)++ # Validate that filepath is inside directory+ validate_inside_directory(directory, filepath)++ # Resolve filepath for use+ # If directory is absolute and filepath is relative, resolve relative to directory+ if directory.is_absolute() and not filepath.is_absolute():+ filepath = directory / filepath+ # Note: We don't call resolve() here to preserve the original path format++ if filepath.exists():+ return AppFileManager(+ str(filepath),+ default_width=default_width,+ default_auto_download=default_auto_download,+ default_sql_output=default_sql_output,+ )++ raise HTTPException(+ status_code=HTTPStatus.NOT_FOUND,+ detail=f"File {key} not found",+ )+@propertydef files(self) -> list[FileInfo]:if self._lazy_files is None:@@ -332,3 +379,104 @@ def timeout(seconds: int, message: str) -> Generator[None, None, None]:finally:signal.alarm(0)signal.signal(signal.SIGALRM, original_handler)+++def validate_inside_directory(directory: Path, filepath: Path) -> None:+ """+ Validate that a filepath is inside a directory.++ Handles all combinations of absolute/relative paths for both directory+ and filepath. Resolves symlinks and prevents path traversal attacks.++ Args:+ directory: The directory path (can be absolute or relative)+ filepath: The file path to validate (can be absolute or relative)++ Raises:+ HTTPException: If the filepath is outside the directory or if there's+ an error resolving paths (e.g., broken symlinks, permission errors)+ """+ try:+ # Handle empty paths - Path("") resolves to ".", so check for that+ if str(directory) == "." and str(filepath) == ".":+ # Both are current directory - this is ambiguous+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Empty or ambiguous directory or filepath provided",+ )++ # Resolve directory to absolute path+ # If directory is relative, resolve it relative to current working directory+ directory_resolved = directory.resolve(strict=False)++ # If directory doesn't exist, we can't validate - this is an error+ if not directory_resolved.exists():+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail=f"Directory {directory} does not exist",+ )++ if not directory_resolved.is_dir():+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail=f"Path {directory} is not a directory",+ )++ # Resolve filepath to absolute path+ # If directory is absolute and filepath is relative, resolve relative to directory+ # (matches behavior in get_file_manager)+ # Otherwise, resolve relative to current working directory+ if not filepath.is_absolute() and directory_resolved.is_absolute():+ # Resolve relative filepath relative to the directory+ filepath_resolved = (directory_resolved / filepath).resolve(+ strict=False+ )+ elif filepath.is_absolute():+ # Absolute filepath - resolve it directly (resolves symlinks)+ filepath_resolved = filepath.resolve(strict=False)+ else:+ # Both are relative - resolve relative to current working directory+ filepath_resolved = filepath.resolve(strict=False)++ # Check if filepath is inside directory+ # Use resolve() to handle symlinks and normalize paths+ try:+ # Ensure both paths are fully resolved (handles symlinks)+ # resolve(strict=False) resolves symlinks even if final path doesn't exist+ filepath_absolute = filepath_resolved.resolve(strict=False)+ directory_absolute = directory_resolved.resolve(strict=False)++ # A directory is not inside itself+ if filepath_absolute == directory_absolute:+ raise HTTPException(+ status_code=HTTPStatus.FORBIDDEN,+ detail=f"Access denied: File {filepath} is the same as directory {directory}",+ )++ # Check if filepath is inside directory using relative_to+ # This prevents path traversal attacks+ try:+ filepath_absolute.relative_to(directory_absolute)+ except ValueError:+ # filepath is not inside directory+ raise HTTPException(+ status_code=HTTPStatus.FORBIDDEN,+ detail=f"Access denied: File {filepath} is outside the allowed directory {directory}",+ ) from None++ except OSError as e:+ # Handle errors like broken symlinks, permission errors, etc.+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail=f"Error resolving path {filepath}: {str(e)}",+ ) from e++ except HTTPException:+ # Re-raise HTTPException as-is+ raise+ except Exception as e:+ # Catch any other unexpected errors+ raise HTTPException(+ status_code=HTTPStatus.SERVER_ERROR,+ detail=f"Unexpected error validating path: {str(e)}",+ ) from ediff --git a/tests/_server/test_file_manager_absolute_path.py b/tests/_server/test_file_manager_absolute_path.pynew file mode 100644index 0000000000..2f40d37027--- /dev/null+++ b/tests/_server/test_file_manager_absolute_path.py@@ -0,0 +1,564 @@+# Copyright 2024 Marimo. All rights reserved.+"""Test file manager with absolute directory paths."""++from __future__ import annotations++import os+from pathlib import Path++import pytest++from marimo._server.api.status import HTTPException, HTTPStatus+from marimo._server.file_router import AppFileRouter+++class TestAbsoluteDirectoryPath:+ """Test that absolute directory paths work correctly."""++ def test_absolute_directory_path_file_manager(+ self, tmp_path: Path+ ) -> None:+ """Test that files can be opened from absolute directory paths."""+ # Create a test directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ # Create a test file+ test_file = test_dir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ return++if __name__ == "__main__":+ app.run()+"""+ )++ # Test with absolute path+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # The directory should be stored correctly+ assert router.directory == absolute_dir++ # Get the files - they should have absolute paths+ files = router.files+ assert len(files) > 0+ file_info = files[0]+ assert file_info.is_marimo_file+ assert file_info.path == str(test_file)++ # Try to get a file manager using the file path+ file_manager = router.get_file_manager(file_info.path)+ assert file_manager is not None+ assert file_manager.filename == str(test_file)+ assert file_manager.is_notebook_named++ def test_relative_directory_path_file_manager(+ self, tmp_path: Path+ ) -> None:+ """Test that files can be opened from relative directory paths."""+ # Create a test directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ # Create a test file+ test_file = test_dir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ return++if __name__ == "__main__":+ app.run()+"""+ )++ # Change to the tmp_path directory+ original_cwd = os.getcwd()+ try:+ os.chdir(tmp_path)++ # Test with relative path+ relative_dir = "test_dir"+ router = AppFileRouter.from_directory(relative_dir)++ # The directory should be stored correctly+ assert router.directory == relative_dir++ # Get the files+ files = router.files+ assert len(files) > 0+ file_info = files[0]+ assert file_info.is_marimo_file++ # Try to get a file manager using the file path+ file_manager = router.get_file_manager(file_info.path)+ assert file_manager is not None+ assert file_manager.is_notebook_named+ finally:+ os.chdir(original_cwd)++ def test_absolute_vs_relative_directory_consistency(+ self, tmp_path: Path+ ) -> None:+ """Test that absolute and relative paths behave consistently."""+ # Create a test directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ # Create a test file+ test_file = test_dir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ x = 1+ return x++if __name__ == "__main__":+ app.run()+"""+ )++ # Test with absolute path+ absolute_dir = str(test_dir.absolute())+ absolute_router = AppFileRouter.from_directory(absolute_dir)+ absolute_files = absolute_router.files+ assert len(absolute_files) > 0++ # Get file manager with absolute path+ absolute_file_path = absolute_files[0].path+ absolute_file_manager = absolute_router.get_file_manager(+ absolute_file_path+ )++ # Change to the parent directory+ original_cwd = os.getcwd()+ try:+ os.chdir(tmp_path)++ # Test with relative path+ relative_dir = "test_dir"+ relative_router = AppFileRouter.from_directory(relative_dir)+ relative_files = relative_router.files+ assert len(relative_files) > 0++ # Get file manager with relative path+ relative_file_path = relative_files[0].path+ relative_file_manager = relative_router.get_file_manager(+ relative_file_path+ )++ # Both should reference the same file+ assert (+ Path(absolute_file_manager.filename or "").resolve()+ == Path(relative_file_manager.filename or "").resolve()+ )++ # Both should be able to read the file+ absolute_content = absolute_file_manager.read_file()+ relative_content = relative_file_manager.read_file()+ assert absolute_content == relative_content+ assert "x = 1" in absolute_content+ finally:+ os.chdir(original_cwd)++ def test_file_manager_with_relative_file_in_absolute_dir(+ self, tmp_path: Path+ ) -> None:+ """Test opening a file with a relative path within an absolute directory.++ This is the specific case that the user reported as broken:+ - Run: marimo edit /absolute/path/to/dir+ - Then open a file like 'notebook.py' (relative to the directory)+ """+ # Create a test directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ # Create a test file+ test_file = test_dir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ return++if __name__ == "__main__":+ app.run()+"""+ )++ # Set up router with absolute directory+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # Simulate the case where the client sends a relative filename+ # This might happen if the frontend sends just the filename+ relative_filename = "notebook.py"++ # Try to construct the full path+ # This is what should happen in the server code+ full_path = os.path.join(absolute_dir, relative_filename)++ # Verify the file exists+ assert os.path.exists(full_path)++ # Try to get a file manager+ file_manager = router.get_file_manager(full_path)+ assert file_manager is not None+ assert file_manager.is_notebook_named+ assert file_manager.read_file() is not None++ def test_absolute_dir_with_cwd_change(self, tmp_path: Path) -> None:+ """Test that absolute directory paths work even when cwd changes.++ This simulates the scenario where:+ 1. User runs: marimo edit /absolute/path/to/dir+ 2. The server might change its working directory+ 3. Files should still be accessible+ """+ # Create a test directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()+ other_dir = tmp_path / "other_dir"+ other_dir.mkdir()++ # Create a test file+ test_file = test_dir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ return++if __name__ == "__main__":+ app.run()+"""+ )++ # Set up router with absolute directory+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # Get the files before changing directory+ files_before = router.files+ assert len(files_before) > 0++ # Save original cwd+ original_cwd = os.getcwd()+ try:+ # Change to a completely different directory+ os.chdir(other_dir)++ # Files should still be accessible+ files_after = router.files+ assert len(files_after) == len(files_before)+ assert files_after[0].path == files_before[0].path++ # Try to get a file manager+ file_path = files_after[0].path+ file_manager = router.get_file_manager(file_path)+ assert file_manager is not None+ assert file_manager.is_notebook_named+ content = file_manager.read_file()+ assert content is not None+ assert "marimo.App" in content+ finally:+ os.chdir(original_cwd)++ def test_relative_file_path_resolved_properly(+ self, tmp_path: Path+ ) -> None:+ """Test that a relative file path is properly resolved.++ When a router is created with an absolute directory, relative file+ paths should be resolved against that directory.+ """+ # Create a test directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ # Create a test file+ test_file = test_dir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ return++if __name__ == "__main__":+ app.run()+"""+ )++ # Set up router with absolute directory+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # Change to a different directory+ original_cwd = os.getcwd()+ try:+ os.chdir(tmp_path)++ # Try to open just 'notebook.py' (relative path)+ # This should now succeed because it's resolved relative to+ # the router's directory+ relative_filename = "notebook.py"++ file_manager = router.get_file_manager(relative_filename)+ assert file_manager is not None+ assert file_manager.is_notebook_named+ # Verify it opened the correct file+ assert (+ Path(file_manager.filename or "").resolve()+ == test_file.resolve()+ )+ finally:+ os.chdir(original_cwd)+++class TestAbsoluteDirectoryPathOpening:+ """Test that files can be opened correctly from absolute directory paths."""++ def test_open_file_with_basename_from_absolute_dir(+ self, tmp_path: Path+ ) -> None:+ """Test opening a file using just its basename when router has absolute dir.++ This reproduces the bug:+ 1. Run: marimo edit /absolute/path/to/dir+ 2. Frontend shows list of files+ 3. User clicks on a file like 'notebook.py'+ 4. Frontend might send just the basename as the file_key+ 5. Server should resolve this relative to the router's directory+ """+ # Create a test directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ # Create a test file+ test_file = test_dir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ return++if __name__ == "__main__":+ app.run()+"""+ )++ # Simulate: marimo edit /absolute/path/to/dir+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # Change to a different directory to simulate the server running elsewhere+ original_cwd = os.getcwd()+ try:+ other_dir = tmp_path / "other_dir"+ other_dir.mkdir()+ os.chdir(other_dir)++ # The files list should show absolute paths+ files = router.files+ assert len(files) > 0+ file_info = files[0]++ # This should work - using the full absolute path+ file_manager = router.get_file_manager(file_info.path)+ assert file_manager is not None+ assert file_manager.is_notebook_named++ # Now simulate the frontend sending just the basename+ # (This is what might be happening in the bug)+ basename = "notebook.py"++ # This currently fails but should succeed+ # The router should resolve the basename relative to its directory+ try:+ file_manager_from_basename = router.get_file_manager(basename)+ assert file_manager_from_basename is not None+ assert file_manager_from_basename.is_notebook_named+ except HTTPException as e:+ # This is the bug - it should have resolved relative to router.directory+ pytest.fail(+ f"Should be able to open file with basename '{basename}' "+ f"when router has absolute directory '{absolute_dir}'"+ )+ finally:+ os.chdir(original_cwd)++ def test_open_file_with_relative_path_from_absolute_dir(+ self, tmp_path: Path+ ) -> None:+ """Test opening a file using a relative path from absolute dir router.++ Scenario:+ 1. marimo edit /absolute/path/to/dir+ 2. Frontend sends 'subdir/notebook.py' as file_key+ 3. Should resolve to /absolute/path/to/dir/subdir/notebook.py+ """+ # Create a test directory structure with subdirectory+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()+ subdir = test_dir / "subdir"+ subdir.mkdir()++ # Create a test file in subdirectory+ test_file = subdir / "notebook.py"+ test_file.write_text(+ """+import marimo+app = marimo.App()++def __():+ return++if __name__ == "__main__":+ app.run()+"""+ )++ # Simulate: marimo edit /absolute/path/to/dir+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # Change to a different directory+ original_cwd = os.getcwd()+ try:+ other_dir = tmp_path / "other_dir"+ other_dir.mkdir()+ os.chdir(other_dir)++ # Try to open with relative path+ relative_path = "subdir/notebook.py"++ try:+ file_manager = router.get_file_manager(relative_path)+ assert file_manager is not None+ assert file_manager.is_notebook_named+ except HTTPException as e:+ pytest.fail(+ f"Should be able to open file with relative path '{relative_path}' "+ f"when router has absolute directory '{absolute_dir}'"+ )+ finally:+ os.chdir(original_cwd)++ def test_files_list_shows_correct_paths_for_absolute_dir(+ self, tmp_path: Path+ ) -> None:+ """Verify that router.files returns the correct paths for absolute dirs."""+ # Create test files+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ test_file1 = test_dir / "notebook1.py"+ test_file1.write_text("import marimo\napp = marimo.App()")++ test_file2 = test_dir / "notebook2.py"+ test_file2.write_text("import marimo\napp = marimo.App()")++ # Test with absolute directory+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ files = router.files+ assert len(files) == 2++ # All paths should be absolute+ for file_info in files:+ assert Path(file_info.path).is_absolute()+ assert file_info.path.startswith(absolute_dir)++ # Verify each file can be opened using its path+ for file_info in files:+ file_manager = router.get_file_manager(file_info.path)+ assert file_manager is not None+ assert file_manager.is_notebook_named++ def test_absolute_path_outside_directory_denied(+ self, tmp_path: Path+ ) -> None:+ """Test that absolute paths outside the router's directory are denied."""+ # Create two separate directories+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ other_dir = tmp_path / "other_dir"+ other_dir.mkdir()++ # Create files in both directories+ test_file = test_dir / "notebook.py"+ test_file.write_text("import marimo\napp = marimo.App()")++ other_file = other_dir / "other_notebook.py"+ other_file.write_text("import marimo\napp = marimo.App()")++ # Create router for test_dir+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # Should be able to open file within the directory+ file_manager = router.get_file_manager(str(test_file.absolute()))+ assert file_manager is not None++ # Should NOT be able to open file outside the directory+ with pytest.raises(HTTPException) as exc_info:+ router.get_file_manager(str(other_file.absolute()))++ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN+ assert "Access denied" in exc_info.value.detail+ assert "outside the allowed directory" in exc_info.value.detail++ def test_absolute_path_with_symlink_attack_denied(+ self, tmp_path: Path+ ) -> None:+ """Test that symlink attacks to escape the directory are denied."""+ # Create directory structure+ test_dir = tmp_path / "test_dir"+ test_dir.mkdir()++ secret_dir = tmp_path / "secret"+ secret_dir.mkdir()++ secret_file = secret_dir / "secrets.py"+ secret_file.write_text("import marimo\napp = marimo.App()")++ # Create router for test_dir+ absolute_dir = str(test_dir.absolute())+ router = AppFileRouter.from_directory(absolute_dir)++ # Try to access the secret file using absolute path+ with pytest.raises(HTTPException) as exc_info:+ router.get_file_manager(str(secret_file.absolute()))++ assert exc_info.value.status_code == HTTPStatus.FORBIDDENdiff --git a/tests/_server/test_file_router.py b/tests/_server/test_file_router.pyindex 9023d247fe..2529dfea73 100644--- a/tests/_server/test_file_router.py+++ b/tests/_server/test_file_router.py@@ -4,12 +4,17 @@ import osimport shutilimport tempfileimport unittest+from pathlib import Path+import pytest++from marimo._server.api.status import HTTPException, HTTPStatusfrom marimo._server.file_router import (AppFileRouter,LazyListOfFilesAppFileRouter,ListOfFilesAppFileRouter,NewFileAppFileRouter,+ validate_inside_directory,)from marimo._server.models.home import MarimoFile@@ -151,3 +156,249 @@ class TestAppFileRouter(unittest.TestCase):assert os.path.exists(file_manager.filename)assert file_manager.filename.startswith(self.test_dir)assert "nested" in file_manager.filename+++class TestValidateInsideDirectory(unittest.TestCase):+ def setUp(self):+ # Create a temporary directory structure+ self.test_dir = tempfile.mkdtemp()+ self.test_file = Path(self.test_dir) / "test.py"+ self.test_file.write_text("test")++ # Create nested directory+ self.nested_dir = Path(self.test_dir) / "nested"+ self.nested_dir.mkdir()+ self.nested_file = self.nested_dir / "nested.py"+ self.nested_file.write_text("test")++ # Create directory outside test_dir+ self.outside_dir = tempfile.mkdtemp()+ self.outside_file = Path(self.outside_dir) / "outside.py"+ self.outside_file.write_text("test")++ # Save current working directory+ self.original_cwd = os.getcwd()++ def tearDown(self):+ # Clean up+ shutil.rmtree(self.test_dir, ignore_errors=True)+ shutil.rmtree(self.outside_dir, ignore_errors=True)+ os.chdir(self.original_cwd)++ def test_absolute_directory_absolute_filepath_inside(self):+ """Test: absolute directory, absolute filepath, file inside directory"""+ directory = Path(self.test_dir).resolve()+ filepath = Path(self.test_file).resolve()+ # Should not raise+ validate_inside_directory(directory, filepath)++ def test_absolute_directory_absolute_filepath_outside(self):+ """Test: absolute directory, absolute filepath, file outside directory"""+ directory = Path(self.test_dir).resolve()+ filepath = Path(self.outside_file).resolve()+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN++ def test_absolute_directory_relative_filepath_inside(self):+ """Test: absolute directory, relative filepath, file inside directory"""+ directory = Path(self.test_dir).resolve()+ filepath = Path("test.py")+ # Change to test_dir so relative path resolves correctly+ os.chdir(self.test_dir)+ # Should not raise+ validate_inside_directory(directory, filepath)++ def test_absolute_directory_relative_filepath_outside(self):+ """Test: absolute directory, relative filepath, file outside directory"""+ directory = Path(self.test_dir).resolve()+ # When directory is absolute and filepath is relative, filepath is resolved+ # relative to directory. So "outside.py" would resolve to test_dir/outside.py+ # which doesn't exist but would be inside test_dir. To test outside, we need+ # to use a path that goes outside even when resolved relative to directory.+ filepath = Path("..") / ".." / "etc" / "passwd"+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN++ def test_relative_directory_absolute_filepath_inside(self):+ """Test: relative directory, absolute filepath, file inside directory"""+ os.chdir(self.test_dir)+ directory = Path(".")+ filepath = Path(self.test_file).resolve()+ # Should not raise+ validate_inside_directory(directory, filepath)++ def test_relative_directory_absolute_filepath_outside(self):+ """Test: relative directory, absolute filepath, file outside directory"""+ os.chdir(self.test_dir)+ directory = Path(".")+ filepath = Path(self.outside_file).resolve()+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN++ def test_relative_directory_relative_filepath_inside(self):+ """Test: relative directory, relative filepath, file inside directory"""+ os.chdir(self.test_dir)+ directory = Path(".")+ filepath = Path("test.py")+ # Should not raise+ validate_inside_directory(directory, filepath)++ def test_relative_directory_relative_filepath_outside(self):+ """Test: relative directory, relative filepath, file outside directory"""+ os.chdir(self.outside_dir)+ directory = Path(".")+ # Try to access file in test_dir using relative path+ relative_path = os.path.relpath(self.test_file, self.outside_dir)+ filepath = Path(relative_path)+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN++ def test_path_traversal_dotdot(self):+ """Test: path traversal attack using .."""+ directory = Path(self.test_dir).resolve()+ # Try to escape using ../+ filepath = Path(self.test_dir) / ".." / ".." / "etc" / "passwd"+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN++ def test_path_traversal_nested_dotdot(self):+ """Test: path traversal using nested ../"""+ directory = Path(self.nested_dir).resolve()+ # Try to escape to parent directory+ filepath = (+ Path(self.nested_dir) / ".." / ".." / ".." / "etc" / "passwd"+ )+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN++ def test_symlink_inside_directory(self):+ """Test: symlink pointing to file inside directory"""+ directory = Path(self.test_dir).resolve()+ # Create symlink inside directory pointing to file inside directory+ symlink_path = Path(self.test_dir) / "symlink.py"+ symlink_path.symlink_to(self.test_file)+ # Should not raise+ validate_inside_directory(directory, symlink_path)+ symlink_path.unlink()++ def test_symlink_outside_directory(self):+ """Test: symlink pointing to file outside directory"""+ directory = Path(self.test_dir).resolve()+ # Create symlink inside directory pointing to file outside directory+ symlink_path = Path(self.test_dir) / "symlink.py"+ symlink_path.symlink_to(self.outside_file)+ # Should raise - symlink resolves to outside file+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, symlink_path)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN+ symlink_path.unlink()++ def test_broken_symlink(self):+ """Test: broken symlink"""+ directory = Path(self.test_dir).resolve()+ # Create broken symlink+ broken_symlink = Path(self.test_dir) / "broken.py"+ broken_symlink.symlink_to("nonexistent_file")+ # Broken symlinks can be resolved with resolve(strict=False), but if they+ # point outside the directory, should still fail+ # First test: broken symlink inside directory (should work if resolved path is inside)+ # The symlink itself is inside, so it should pass validation+ # (the actual file doesn't need to exist for validation)+ validate_inside_directory(directory, broken_symlink)++ # Test: broken symlink that resolves outside+ broken_symlink.unlink()+ broken_symlink = Path(self.test_dir) / "broken.py"+ # Create symlink that would resolve outside+ broken_symlink.symlink_to("../../etc/passwd")+ # Should fail because resolved path is outside+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, broken_symlink)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN+ broken_symlink.unlink()++ def test_symlink_to_directory(self):+ """Test: symlink pointing to directory inside"""+ directory = Path(self.test_dir).resolve()+ # Create symlink to nested directory+ symlink_path = Path(self.test_dir) / "nested_link"+ symlink_path.symlink_to(self.nested_dir)+ # Should not raise - symlink resolves to directory inside+ validate_inside_directory(directory, symlink_path)+ symlink_path.unlink()++ def test_nested_file(self):+ """Test: nested file inside directory"""+ directory = Path(self.test_dir).resolve()+ filepath = Path(self.nested_file).resolve()+ # Should not raise+ validate_inside_directory(directory, filepath)++ def test_nonexistent_directory(self):+ """Test: directory doesn't exist"""+ directory = Path(self.test_dir) / "nonexistent"+ filepath = Path(self.test_file).resolve()+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST++ def test_file_as_directory(self):+ """Test: directory path is actually a file"""+ directory = Path(self.test_file).resolve()+ filepath = Path(self.test_file).resolve()+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST++ def test_same_path(self):+ """Test: filepath is the same as directory"""+ directory = Path(self.test_dir).resolve()+ filepath = Path(self.test_dir).resolve()+ # Directory is not inside itself+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN++ def test_empty_paths(self):+ """Test: empty paths (Path("") resolves to ".")"""+ # Path("") resolves to ".", which is ambiguous+ directory = Path("")+ filepath = Path("")+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST++ def test_absolute_path_with_dotdot_resolved(self):+ """Test: absolute path with .. that resolves inside"""+ directory = Path(self.test_dir).resolve()+ # Create path with .. that still resolves inside+ filepath = Path(self.nested_file).resolve() / ".." / "test.py"+ # Should not raise - resolves to test.py inside directory+ validate_inside_directory(directory, filepath.resolve())++ def test_relative_path_with_dotdot(self):+ """Test: relative path with .. that resolves inside"""+ directory = Path(self.test_dir).resolve()+ # When directory is absolute and filepath is relative, filepath is resolved+ # relative to directory. So "../test.py" from nested_dir would be+ # resolved as (test_dir / "../test.py") which goes outside.+ # Instead, test with a path that stays inside when resolved relative to directory+ nested_rel_path = Path("nested") / ".." / "test.py"+ filepath = nested_rel_path+ # Should not raise - resolves to test.py inside directory+ validate_inside_directory(directory, filepath)++ def test_relative_path_with_dotdot_outside(self):+ """Test: relative path with .. that goes outside"""+ os.chdir(self.nested_dir)+ directory = Path(self.nested_dir).resolve()+ filepath = Path("..") / ".." / ".." / "etc" / "passwd"+ with pytest.raises(HTTPException) as exc_info:+ validate_inside_directory(directory, filepath)+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN