Skip to content

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.

fix: preserve symlinks in path validation check (#7671)

Myles Scolnick9abb348a260d
diff --git a/marimo/_server/files/path_validator.py b/marimo/_server/files/path_validator.py
index eccf8b9844..e6a251c8fa 100644
--- a/marimo/_server/files/path_validator.py
+++ b/marimo/_server/files/path_validator.py
@@ -36,7 +36,9 @@ class PathValidator:
temp_dir: The absolute path to the temp directory to allow.
"""
# Normalize the path to ensure consistency
- normalized_path = Path(temp_dir).resolve()
+ normalized_path = self._normalize_path_without_resolving_symlinks(
+ Path(temp_dir), Path.cwd()
+ )
self._allowed_temp_dirs.add(normalized_path)
LOGGER.debug("Registered allowed temp directory: %s", normalized_path)
@@ -53,10 +55,12 @@ class PathValidator:
return False
try:
- file_resolved = Path(filepath).resolve(strict=False)
+ file_normalized = self._normalize_path_without_resolving_symlinks(
+ Path(filepath), Path.cwd()
+ )
for temp_dir in list(self._allowed_temp_dirs):
try:
- file_resolved.relative_to(temp_dir)
+ file_normalized.relative_to(temp_dir)
return True
except ValueError:
# Not a child of this temp directory, try next
@@ -70,6 +74,69 @@ class PathValidator:
)
return False
+ def _normalize_path_without_resolving_symlinks(
+ self, path: Path, base: Path
+ ) -> Path:
+ """Normalize a path without resolving symlinks.
+
+ Makes the path absolute relative to base and normalizes .. components,
+ but does NOT resolve symlinks.
+
+ Args:
+ path: The path to normalize
+ base: The base directory for relative paths
+
+ Returns:
+ Normalized absolute path without symlink resolution
+ """
+ import os
+
+ # Make absolute relative to base if needed
+ if not path.is_absolute():
+ path = base / path
+
+ # Use os.path.normpath to normalize .. and . without resolving symlinks
+ # Then convert back to Path
+ normalized = Path(os.path.normpath(str(path)))
+
+ # Ensure the normalized path is still absolute. While normpath generally
+ # preserves absoluteness, we enforce this invariant explicitly for safety.
+ if not normalized.is_absolute():
+ LOGGER.error(
+ "Normalized path is not absolute: %s (original: %s, base: %s)",
+ normalized,
+ path,
+ base,
+ )
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Invalid path: normalized path is not absolute",
+ )
+
+ return normalized
+
+ def _check_containment(
+ self,
+ directory_abs: Path,
+ filepath_abs: Path,
+ directory: Path,
+ filepath: Path,
+ ) -> None:
+ """Check that filepath is inside directory."""
+ if filepath_abs == directory_abs:
+ raise HTTPException(
+ status_code=HTTPStatus.FORBIDDEN,
+ detail=f"Access denied: File {filepath} is the same as directory {directory}",
+ )
+
+ try:
+ filepath_abs.relative_to(directory_abs)
+ except ValueError:
+ raise HTTPException(
+ status_code=HTTPStatus.FORBIDDEN,
+ detail=f"Access denied: File {filepath} is outside the allowed directory {directory}",
+ ) from None
+
def validate_inside_directory(
self, directory: Path, filepath: Path
) -> None:
@@ -77,7 +144,7 @@ class PathValidator:
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.
+ and filepath. By default, symlinks are preserved.
Args:
directory: The directory path (can be absolute or relative)
@@ -113,50 +180,27 @@ class PathValidator:
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}",
+ # Normalize without resolving symlinks
+ directory_normalized = (
+ self._normalize_path_without_resolving_symlinks(
+ directory, Path.cwd()
)
-
- # 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
+ )
+ filepath_normalized = (
+ self._normalize_path_without_resolving_symlinks(
+ filepath, directory_normalized
+ )
+ )
+ self._check_containment(
+ directory_normalized,
+ filepath_normalized,
+ directory,
+ filepath,
+ )
except OSError as e:
- # Handle errors like broken symlinks, permission errors, etc.
+ # Handle errors like permission errors, etc.
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail=f"Error resolving path {filepath}: {str(e)}",
diff --git a/tests/_server/test_file_router.py b/tests/_server/test_file_router.py
index baa2be55cd..323ca50336 100644
--- a/tests/_server/test_file_router.py
+++ b/tests/_server/test_file_router.py
@@ -281,59 +281,54 @@ class TestValidateInsideDirectory(unittest.TestCase):
def test_symlink_inside_directory(self):
"""Test: symlink pointing to file inside directory"""
- directory = Path(self.test_dir).resolve()
+ directory = Path(self.test_dir)
# 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
+ # Should not raise - symlink path is inside directory
PathValidator().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()
+ directory = Path(self.test_dir)
# 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:
- PathValidator().validate_inside_directory(directory, symlink_path)
- assert exc_info.value.status_code == HTTPStatus.FORBIDDEN
+ # Symlink path itself is inside directory, so this should pass
+ # (we preserve symlinks, not resolve them)
+ PathValidator().validate_inside_directory(directory, symlink_path)
symlink_path.unlink()
def test_broken_symlink(self):
"""Test: broken symlink"""
- directory = Path(self.test_dir).resolve()
+ directory = Path(self.test_dir)
# 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)
+ # The symlink path itself is inside the directory, so validation passes
+ # (symlinks are preserved, target is not checked)
PathValidator().validate_inside_directory(directory, broken_symlink)
-
- # Test: broken symlink that resolves outside
broken_symlink.unlink()
+
+ def test_broken_symlink_path_traversal(self):
+ """Test: broken symlink with path traversal"""
+ directory = Path(self.test_dir)
broken_symlink = Path(self.test_dir) / "broken.py"
- # Create symlink that would resolve outside
+ # Create symlink that would resolve outside via path traversal
broken_symlink.symlink_to("../../etc/passwd")
- # Should fail because resolved path is outside
- with pytest.raises(HTTPException) as exc_info:
- PathValidator().validate_inside_directory(
- directory, broken_symlink
- )
- assert exc_info.value.status_code == HTTPStatus.FORBIDDEN
+ # Symlink path itself is inside directory, so this passes
+ # (we preserve symlinks, path traversal in target is not checked)
+ PathValidator().validate_inside_directory(directory, broken_symlink)
broken_symlink.unlink()
def test_symlink_to_directory(self):
"""Test: symlink pointing to directory inside"""
- directory = Path(self.test_dir).resolve()
+ directory = Path(self.test_dir)
# 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
+ # Should not raise - symlink path is inside directory
PathValidator().validate_inside_directory(directory, symlink_path)
symlink_path.unlink()
@@ -615,3 +610,37 @@ def test_lazy_router_temp_dir_doesnt_affect_normal_files(
with pytest.raises(HTTPException) as exc_info:
router.get_file_manager(str(outside_file))
assert exc_info.value.status_code == HTTPStatus.FORBIDDEN
+
+
+def test_lazy_router_symlink_directory_outside_allowed(tmp_path: Path):
+ """Test that files through symlinked directories are allowed.
+
+ Since symlinks are preserved (not resolved), the path through the
+ symlink is inside the base directory.
+ """
+ # Create base directory with a notebook
+ base_dir = tmp_path / "base"
+ base_dir.mkdir()
+ base_file = base_dir / "base.py"
+ base_file.write_text("import marimo\napp = marimo.App()\n")
+
+ # Create outside directory with a notebook
+ outside_dir = tmp_path / "outside"
+ outside_dir.mkdir()
+ outside_file = outside_dir / "outside.py"
+ outside_file.write_text("import marimo\napp = marimo.App()\n")
+
+ # Create symlink inside base_dir pointing to outside_dir
+ symlink_path = base_dir / "shared"
+ symlink_path.symlink_to(outside_dir)
+
+ # File path through the symlink
+ file_through_symlink = symlink_path / "outside.py"
+
+ # Symlinks are preserved (not resolved), so the path
+ # base_dir/shared/outside.py is inside base_dir
+ router = LazyListOfFilesAppFileRouter(
+ str(base_dir), include_markdown=False
+ )
+ manager = router.get_file_manager(str(file_through_symlink))
+ assert manager is not None
diff --git a/tests/_server/test_path_validator.py b/tests/_server/test_path_validator.py
index 04bb04eadc..918112b74c 100644
--- a/tests/_server/test_path_validator.py
+++ b/tests/_server/test_path_validator.py
@@ -64,21 +64,24 @@ class TestPathValidator(unittest.TestCase):
def test_symlink_inside_directory(self):
"""Test that symlinks pointing inside directory are allowed."""
validator = PathValidator()
- directory = Path(self.test_dir).resolve()
+ directory = Path(self.test_dir)
symlink_path = Path(self.test_dir) / "symlink.py"
symlink_path.symlink_to(self.test_file)
validator.validate_inside_directory(directory, symlink_path)
symlink_path.unlink()
- def test_symlink_escape_prevented(self):
- """Test that symlinks pointing outside directory are blocked."""
+ def test_symlink_to_outside_allowed(self):
+ """Test that symlinks pointing outside directory are allowed.
+
+ Since symlinks are preserved (not resolved), the symlink path itself
+ is inside the directory, so access is allowed.
+ """
validator = PathValidator()
- directory = Path(self.test_dir).resolve()
+ directory = Path(self.test_dir)
symlink_path = Path(self.test_dir) / "symlink.py"
symlink_path.symlink_to(self.outside_file)
- with pytest.raises(HTTPException) as exc_info:
- validator.validate_inside_directory(directory, symlink_path)
- assert exc_info.value.status_code == HTTPStatus.FORBIDDEN
+ # Should not raise - symlink path is inside directory
+ validator.validate_inside_directory(directory, symlink_path)
symlink_path.unlink()
def test_temp_directory_registration(self):
@@ -104,3 +107,25 @@ class TestPathValidator(unittest.TestCase):
with pytest.raises(HTTPException) as exc_info:
validator.validate_file_access(filepath)
assert exc_info.value.status_code == HTTPStatus.FORBIDDEN
+
+ def test_symlink_directory_outside_allowed(self):
+ """Test that files through symlinked directories are allowed.
+
+ Since symlinks are preserved (not resolved), the path through the
+ symlink is inside the base directory.
+ """
+ # Create a symlink to the outside directory inside the test directory
+ symlink_path = Path(self.test_dir) / "shared"
+ symlink_path.symlink_to(self.outside_dir)
+
+ # Create a file reference through the symlink
+ file_through_symlink = symlink_path / "outside.py"
+
+ # Symlinks are preserved (not resolved), so the path
+ # /test_dir/shared/outside.py is inside /test_dir/
+ validator = PathValidator()
+ validator.validate_inside_directory(
+ Path(self.test_dir), file_through_symlink
+ ) # Should not raise
+
+ symlink_path.unlink()