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 path resolution for .resolve() and .absolute() for correctness and security (#7703)
Myles Scolnick794b5459a7d1
diff --git a/marimo/_cli/export/cloudflare.py b/marimo/_cli/export/cloudflare.pyindex 2b2c91511b..f3168c1ff8 100644--- a/marimo/_cli/export/cloudflare.py+++ b/marimo/_cli/export/cloudflare.py@@ -5,6 +5,7 @@ from pathlib import Pathfrom marimo._cli.print import bold, echo, greenfrom marimo._server.print import _utf8+from marimo._utils.paths import normalize_pathdef create_cloudflare_files(title: str, out_dir: Path) -> None:@@ -17,7 +18,7 @@ def create_cloudflare_files(title: str, out_dir: Path) -> None:if index_js.exists():echo(- f"Cloudflare {index_js.name} already exists at {green(str(index_js.absolute()))}. Skipping..."+ f"Cloudflare {index_js.name} already exists at {green(str(normalize_path(index_js)))}. Skipping...")else:created_files = True@@ -41,7 +42,7 @@ export default {if wrangler_jsonc.exists():echo(- f"Cloudflare {wrangler_jsonc.name} already exists at {green(str(wrangler_jsonc.absolute()))}. Skipping..."+ f"Cloudflare {wrangler_jsonc.name} already exists at {green(str(normalize_path(wrangler_jsonc)))}. Skipping...")else:created_files = True@@ -65,7 +66,7 @@ export default {if created_files:echo(- f"Cloudflare configuration files created at {green(str(parent_dir.absolute()))}."+ f"Cloudflare configuration files created at {green(str(normalize_path(parent_dir)))}.")echo(diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.pyindex d0b37963db..fc3d243cc0 100644--- a/marimo/_plugins/ui/_impl/file_browser.py+++ b/marimo/_plugins/ui/_impl/file_browser.py@@ -20,6 +20,7 @@ from marimo._plugins.ui._core.ui_element import UIElementfrom marimo._plugins.validators import validate_one_offrom marimo._runtime.functions import Functionfrom marimo._utils.files import natural_sort+from marimo._utils.paths import normalize_pathLOGGER = _loggers.marimo_logger()@@ -155,13 +156,24 @@ class file_browser() -> None:validate_one_of(selection_mode, ["file", "directory"])+ # Save the Path class of the initial path+ self._path_cls: type[Path]+ if isinstance(initial_path, str):+ self._path_cls = Path+ else:+ self._path_cls = initial_path.__class__++ # Make a Path objectif not initial_path:initial_path = Path.cwd()elif isinstance(initial_path, str):initial_path = Path(initial_path)+ self._initial_path = initial_path++ # Frontend can't handle relative paths, so normalize it and make it absolute+ # Use normalize_path to avoid symlink resolution+ self._initial_path = self._create_path(normalize_path(initial_path))- # frontend plugin can't handle relative paths- initial_path = initial_path.resolve()# initial path must be a directoryif not initial_path.is_dir():raise ValueError(@@ -183,13 +195,6 @@ class file_browser(self._filetypes = set()self._restrict_navigation = restrict_navigationself._ignore_empty_dirs = ignore_empty_dirs- self._initial_path: Path = initial_path-- self._path_cls: type[Path]- if isinstance(initial_path, str):- self._path_cls = Path- else:- self._path_cls = initial_path.__class__# Smart default limit based on path typeif limit is None:@@ -222,7 +227,7 @@ class file_browser(on_change=on_change,)- def _create_path(self, path_str: str) -> Path:+ def _create_path(self, path_str: str | Path) -> Path:"""Create a path object with the same class and client as the initial path."""kwargs: dict[str, Any] = {}diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 96f4791c8d..7995ff43c7 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -204,6 +204,7 @@ from marimo._types.ids import CellId_t, UIElementId, VariableNamefrom marimo._types.lifespan import Lifespanfrom marimo._utils.assert_never import assert_neverfrom marimo._utils.lifespans import Lifespans+from marimo._utils.paths import normalize_pathfrom marimo._utils.platform import is_pyodidefrom marimo._utils.signals import restore_signalsfrom marimo._utils.typed_connection import TypedConnection@@ -396,12 +397,12 @@ def notebook_dir() -> pathlib.Path | None:except ContextNotInitializedError:# If we are not running in a notebook (e.g. exported to Jupyter),# return the current working directory- return pathlib.Path().absolute()+ return pathlib.Path().cwd()# NB: __file__ is patched by runner, so always bound to be correct.filename = ctx.globals.get("__file__", None) or ctx.filenameif filename is not None:- path = pathlib.Path(filename).resolve()+ path = normalize_path(pathlib.Path(filename))while not path.is_dir():path = path.parentreturn path@@ -598,7 +599,9 @@ class Kernel:# we need to update sys.path.try:notebook_directory = str(- pathlib.Path(self.app_metadata.filename).parent.absolute()+ normalize_path(+ pathlib.Path(self.app_metadata.filename).parent+ ))if notebook_directory not in sys.path:sys.path.insert(0, notebook_directory)diff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex 4e66ce91db..753d747466 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -34,7 +34,6 @@ from marimo._session.model import SessionModefrom marimo._tracer import LOGGERfrom marimo._utils.lifespans import Lifespansfrom marimo._utils.net import find_free_port-from marimo._utils.paths import marimo_package_pathDEFAULT_PORT = 2718PROXY_REGEX = re.compile(r"^(.*):(\d+)$")@@ -338,17 +337,6 @@ def start(app,port=port,host=host,- # TODO: cannot use reload unless the app is an import string- # although cannot use import string because it breaks the- # session manager- # reload=development_mode,- reload_dirs=(- [- str((marimo_package_path() / "_static").resolve()),- ]- if development_mode- else None- ),log_level=log_level,# uvicorn times out HTTP connections (i.e. TCP sockets) every 5# seconds by default; for some reason breaks the server indiff --git a/marimo/_session/file_watcher_integration.py b/marimo/_session/file_watcher_integration.pyindex 9bf10e7abe..917ec3678a 100644--- a/marimo/_session/file_watcher_integration.py+++ b/marimo/_session/file_watcher_integration.py@@ -18,6 +18,7 @@ from marimo._session.events import (from marimo._session.extensions.types import SessionExtensionfrom marimo._session.session import Sessionfrom marimo._utils.file_watcher import FileWatcherManager+from marimo._utils.paths import normalize_pathLOGGER = _loggers.marimo_logger()@@ -92,8 +93,8 @@ class SessionFileWatcherExtension(SessionExtension, SessionEventListener):)def _canonicalize_path(self, path: str) -> Path:- """Canonicalize a path."""- return Path(path).absolute()+ """Canonicalize a path without resolving symlinks."""+ return normalize_path(Path(path))async def on_session_notebook_renamed(self, session: Session, old_path: str | Nonediff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.pyindex aa8ecf5074..82fc9a9e51 100644--- a/marimo/_utils/inline_script_metadata.py+++ b/marimo/_utils/inline_script_metadata.py@@ -7,6 +7,7 @@ from typing import Any, castfrom marimo import _loggersfrom marimo._cli.file_path import FileContentReader+from marimo._utils.paths import normalize_pathfrom marimo._utils.scripts import read_pyproject_from_scriptLOGGER = _loggers.marimo_logger()@@ -184,7 +185,7 @@ def _pyproject_toml_to_requirements_txt(# If path is relative and we have a config path, resolve it relative to the config pathif not source_path.is_absolute() and config_path:config_dir = Path(config_path).parent- source_path = (config_dir / source_path).resolve()+ source_path = normalize_path(config_dir / source_path)new_dependency = f"{dependency} @ {str(source_path)}"# Handle URLsdiff --git a/marimo/_utils/paths.py b/marimo/_utils/paths.pyindex 59ddfb22f5..58327c1c28 100644--- a/marimo/_utils/paths.py+++ b/marimo/_utils/paths.py@@ -42,3 +42,31 @@ def maybe_make_dirs(filepath: Path) -> None:Create directories if they don't exist."""filepath.parent.mkdir(parents=True, exist_ok=True)+++def normalize_path(path: Path) -> Path:+ """Normalize a path without resolving symlinks.++ This function:+ - Converts relative paths to absolute paths+ - Normalizes .. and . components+ - Does NOT resolve symlinks (unlike Path.resolve())++ Args:+ path: The path to normalize++ Returns:+ Normalized absolute path without symlink resolution++ Example:+ >>> normalize_path(Path("foo/../bar"))+ Path("/current/working/dir/bar")+ """+ # Make absolute if relative (relative to current working directory)+ if not path.is_absolute():+ path = Path.cwd() / path++ # Use os.path.normpath to normalize .. and . without resolving symlinks+ normalized = Path(os.path.normpath(str(path)))++ return normalizeddiff --git a/tests/_plugins/ui/_impl/test_file_browser.py b/tests/_plugins/ui/_impl/test_file_browser.pyindex d8b1fd1636..85af0518b6 100644--- a/tests/_plugins/ui/_impl/test_file_browser.py+++ b/tests/_plugins/ui/_impl/test_file_browser.py@@ -1,7 +1,7 @@from __future__ import annotations+import osimport sys-import tempfilefrom pathlib import Pathfrom typing import Any, Optional@@ -13,30 +13,30 @@ from marimo._plugins.ui._impl.file_browser import (ListDirectoryResponse,file_browser,)+from marimo._utils.paths import normalize_path-def test_file_browser_init() -> None:- # Use a temporary directory for testing- with tempfile.TemporaryDirectory() as temp_dir:- fb = file_browser(initial_path=temp_dir)- assert isinstance(fb._initial_path, Path)- assert str(fb._initial_path) == str(Path(temp_dir).resolve())- assert fb._selection_mode == "file"- assert fb._filetypes == set()- assert fb._restrict_navigation is False-- # Test with custom filetypes- custom_filetypes = [".txt", ".csv"]- fb = file_browser(- initial_path=temp_dir,- filetypes=custom_filetypes,- selection_mode="directory",- restrict_navigation=True,- )- assert fb._initial_path == Path(temp_dir).resolve()- assert fb._filetypes == set(custom_filetypes)- assert fb._selection_mode == "directory"- assert fb._restrict_navigation is True+def test_file_browser_init(tmp_path: Path) -> None:+ # Use tmp_path fixture for testing+ fb = file_browser(initial_path=tmp_path)+ assert isinstance(fb._initial_path, Path)+ assert str(fb._initial_path) == str(normalize_path(tmp_path))+ assert fb._selection_mode == "file"+ assert fb._filetypes == set()+ assert fb._restrict_navigation is False++ # Test with custom filetypes+ custom_filetypes = [".txt", ".csv"]+ fb = file_browser(+ initial_path=tmp_path,+ filetypes=custom_filetypes,+ selection_mode="directory",+ restrict_navigation=True,+ )+ assert fb._initial_path == normalize_path(tmp_path)+ assert fb._filetypes == set(custom_filetypes)+ assert fb._selection_mode == "directory"+ assert fb._restrict_navigation is Truedef test_list_directory() -> None:@@ -837,3 +837,117 @@ def test_ignore_empty_dirs_symlink_loop_protection(tmp_path: Path) -> None:assert "empty_dir" not in directory_names# Test should complete without hanging (no infinite loop)+++def test_file_browser_symlink(tmp_path: Path) -> None:+ """Test that file browser doesn't follow symlinks outside initial directory."""+ # Create a safe directory inside temp+ safe_dir = tmp_path / "safe"+ safe_dir.mkdir()++ # Create a file in the safe directory+ safe_file = safe_dir / "safe.txt"+ safe_file.write_text("safe content")++ # Create a directory outside that we don't want to access+ outside_dir = tmp_path / "outside"+ outside_dir.mkdir()+ secret_file = outside_dir / "secret.txt"+ secret_file.write_text("secret content")++ # Create a symlink inside safe_dir that points outside+ symlink_to_outside = safe_dir / "link_to_outside"+ try:+ symlink_to_outside.symlink_to(outside_dir)+ except OSError:+ # On Windows, creating symlinks might require admin privileges+ pytest.skip("Cannot create symlinks on this system")++ # Create file browser restricted to safe_dir+ fb = file_browser(initial_path=safe_dir, restrict_navigation=True)++ # The initial path should not have followed the symlink+ # It should be the normalized path, not resolved+ expected_initial = normalize_path(safe_dir)+ assert fb._initial_path == expected_initial++ # List directory - should see the symlink but as a directory+ response = fb._list_directory(ListDirectoryArgs(path=str(safe_dir)))++ file_names = [f["name"] for f in response.files]+ assert "safe.txt" in file_names+ # The symlink should be visible but treated as a directory+ assert "link_to_outside" in file_names+++def test_file_browser_normalize_path_not_resolve(tmp_path: Path) -> None:+ """Test that file browser uses normalize_path, not resolve."""+ # Create a real directory+ real_dir = tmp_path / "real_directory"+ real_dir.mkdir()++ # Create a file in the real directory+ real_file = real_dir / "test.txt"+ real_file.write_text("test content")++ # Create a symlink to the real directory+ symlink_dir = tmp_path / "symlinked_directory"+ try:+ symlink_dir.symlink_to(real_dir)+ except OSError:+ # On Windows, creating symlinks might require admin privileges+ pytest.skip("Cannot create symlinks on this system")++ # Create file browser with symlinked directory+ fb = file_browser(initial_path=symlink_dir)++ # The initial path should contain "symlinked_directory"+ # NOT "real_directory" (which is what resolve() would give)+ assert "symlinked_directory" in str(fb._initial_path)+ assert "real_directory" not in str(fb._initial_path)+++def test_file_browser_path_with_parent_references(tmp_path: Path) -> None:+ """Test that file browser normalizes paths with .. components."""+ # Create nested directories+ nested = tmp_path / "level1" / "level2"+ nested.mkdir(parents=True)++ # Create a file+ test_file = nested / "test.txt"+ test_file.write_text("content")++ # Create path with .. that goes up and back down+ path_with_parent = tmp_path / "level1" / "level2" / ".." / "level2"++ # Create file browser - should normalize the path+ fb = file_browser(initial_path=path_with_parent)++ # The path should be normalized (no .. in it)+ assert ".." not in str(fb._initial_path)++ # Should end with level2+ assert fb._initial_path == nested+++def test_file_browser_relative_path_normalization(tmp_path: Path) -> None:+ """Test that file browser normalizes relative paths to absolute."""+ # Create a subdirectory+ sub_dir = tmp_path / "subdir"+ sub_dir.mkdir()++ # Save current directory and change to tmp_path+ original_cwd = Path.cwd()+ try:+ os.chdir(tmp_path)++ # Create file browser with relative path+ fb = file_browser(initial_path="./subdir")++ # Should be absolute now+ assert fb._initial_path.is_absolute()+ assert fb._initial_path == sub_dir++ finally:+ # Restore original directory+ os.chdir(original_cwd)diff --git a/tests/_utils/test_paths.py b/tests/_utils/test_paths.pynew file mode 100644index 0000000000..cc4e5ce244--- /dev/null+++ b/tests/_utils/test_paths.py@@ -0,0 +1,81 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import tempfile+from pathlib import Path++import pytest++from marimo._utils.paths import normalize_path+++def test_normalize_path_makes_absolute() -> None:+ """Test that relative paths are converted to absolute paths."""+ relative_path = Path("foo") / "bar"+ result = normalize_path(relative_path)++ assert result.is_absolute()+ assert result == Path.cwd() / "foo" / "bar"+++def test_normalize_path_removes_parent_and_current_refs() -> None:+ """Test that .. and . components are normalized."""+ path_with_refs = Path("foo") / "bar" / ".." / "baz" / "." / "qux"+ result = normalize_path(path_with_refs)++ assert result.is_absolute()+ assert ".." not in str(result)+ assert str(result) == str(Path.cwd() / "foo" / "baz" / "qux")+++def test_normalize_path_handles_already_absolute() -> None:+ """Test that absolute paths stay absolute and get normalized."""+ with tempfile.TemporaryDirectory() as temp_dir:+ temp_path = Path(temp_dir)+ # Create a path with .. in absolute path+ absolute_with_parents = temp_path / "foo" / "bar" / ".." / "baz"+ result = normalize_path(absolute_with_parents)++ assert result.is_absolute()+ assert ".." not in str(result)+ # Should resolve to temp_path/foo/baz+ assert result == temp_path / "foo" / "baz"+++def test_normalize_path_does_not_resolve_symlinks() -> None:+ """Test that symlinks are NOT resolved (key security feature)."""+ with tempfile.TemporaryDirectory() as temp_dir:+ temp_path = Path(temp_dir)++ # Create a real directory+ real_dir = temp_path / "real_directory"+ real_dir.mkdir()++ # Create a file in the real directory+ real_file = real_dir / "test.txt"+ real_file.write_text("test content")++ # Create a symlink to the real directory+ symlink_dir = temp_path / "symlinked_directory"+ try:+ symlink_dir.symlink_to(real_dir)+ except OSError:+ # On Windows, creating symlinks might require admin privileges+ pytest.skip("Cannot create symlinks on this system")++ # Path through symlink+ path_through_symlink = symlink_dir / "test.txt"++ # normalize_path should NOT resolve the symlink+ normalized = normalize_path(path_through_symlink)++ # Should contain the symlink name, not the real directory+ assert "symlinked_directory" in str(normalized)+ assert "real_directory" not in str(normalized)++ # Compare with resolve() which DOES follow symlinks+ resolved = path_through_symlink.resolve()+ assert "real_directory" in str(resolved)++ # They should be different+ assert normalized != resolved