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 tutorial access from UI (#7465)

Myles Scolnick887af02d0836
diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.py
index 29033bb1a0..9f0e01ac33 100644
--- a/marimo/_server/api/endpoints/home.py
+++ b/marimo/_server/api/endpoints/home.py
@@ -207,6 +207,14 @@ async def tutorial(
atexit.register(temp_dir.cleanup)
+ # Register the temp directory with the file router so it can be accessed
+ # This is needed for directory-based routers to allow temp tutorial files
+ app_state = AppState(request)
+ if isinstance(
+ app_state.session_manager.file_router, LazyListOfFilesAppFileRouter
+ ):
+ app_state.session_manager.file_router.register_temp_dir(temp_dir.name)
+
return MarimoFile(
name=os.path.basename(path.absolute_name),
path=path.absolute_name,
diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.py
index 2598f2a618..719560976a 100644
--- a/marimo/_server/file_router.py
+++ b/marimo/_server/file_router.py
@@ -195,6 +195,9 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):
self._directory = str(Path(directory))
self.include_markdown = include_markdown
self._lazy_files: Optional[list[FileInfo]] = None
+ # Track temp directories that are allowed to be accessed
+ # (e.g., for tutorials created by marimo)
+ self._allowed_temp_dirs: set[Path] = set()
@property
def directory(self) -> str:
@@ -213,6 +216,47 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):
def mark_stale(self) -> None:
self._lazy_files = None
+ def register_temp_dir(self, temp_dir: str) -> None:
+ """Register a temp directory as allowed for file access.
+
+ Args:
+ temp_dir: The absolute path to the temp directory to allow.
+ """
+ # Normalize the path to ensure consistency
+ normalized_path = Path(temp_dir).resolve()
+ self._allowed_temp_dirs.add(normalized_path)
+ LOGGER.debug("Registered allowed temp directory: %s", normalized_path)
+
+ def is_file_in_allowed_temp_dir(self, filepath: str) -> bool:
+ """Check if a file is inside an allowed temp directory.
+
+ Args:
+ filepath: The file path to check.
+
+ Returns:
+ True if the file is in an allowed temp directory, False otherwise.
+ """
+ if not self._allowed_temp_dirs:
+ return False
+
+ try:
+ file_resolved = Path(filepath).resolve(strict=False)
+ for temp_dir in list(self._allowed_temp_dirs):
+ try:
+ file_resolved.relative_to(temp_dir)
+ return True
+ except ValueError:
+ # Not a child of this temp directory, try next
+ continue
+ return False
+ except Exception as e:
+ LOGGER.warning(
+ "Error checking if file %s is in allowed temp dir: %s",
+ filepath,
+ e,
+ )
+ return False
+
def get_file_manager(
self,
key: MarimoFileKey,
@@ -238,8 +282,13 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):
directory = Path(self._directory)
filepath = Path(key)
- # Validate that filepath is inside directory
- validate_inside_directory(directory, filepath)
+ # Check if file is in an allowed temp directory (e.g., for tutorials)
+ # If so, skip the directory validation
+ is_in_allowed_temp_dir = self.is_file_in_allowed_temp_dir(key)
+
+ if not is_in_allowed_temp_dir:
+ # 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
diff --git a/tests/_server/api/endpoints/test_home.py b/tests/_server/api/endpoints/test_home.py
index d6c03024fb..9eab0183ce 100644
--- a/tests/_server/api/endpoints/test_home.py
+++ b/tests/_server/api/endpoints/test_home.py
@@ -106,3 +106,39 @@ def test_cant_open_non_tutorial(client: TestClient) -> None:
)
assert response.status_code == 400
assert response.json() == {"detail": "Tutorial not found"}
+
+
+@with_session(SESSION_ID)
+def test_tutorial_file_accessible_after_open(client: TestClient) -> None:
+ """Test that a tutorial file can be accessed after being opened.
+
+ This is an integration test for issue #7424.
+ When a tutorial is opened via the endpoint, it creates a file in a temp
+ directory. This test verifies that the file router can access that
+ file despite it being outside the base directory.
+ """
+ from marimo._server.file_router import LazyListOfFilesAppFileRouter
+
+ # Open a tutorial
+ response = client.post(
+ "/api/home/tutorial/open",
+ headers=HEADERS,
+ json={"tutorialId": "intro"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ tutorial_path = data["path"]
+
+ # Verify the temp directory was registered with the file router
+ session_manager = get_session_manager(client)
+ file_router = session_manager.file_router
+
+ # Only test for directory-based routers
+ if isinstance(file_router, LazyListOfFilesAppFileRouter):
+ assert file_router.is_file_in_allowed_temp_dir(tutorial_path)
+
+ # Try to get a file manager for the tutorial file
+ # This should not raise an HTTPException about being outside the directory
+ file_manager = session_manager.app_manager(tutorial_path)
+ assert file_manager is not None
+ assert file_manager.path == tutorial_path
diff --git a/tests/_server/test_file_router.py b/tests/_server/test_file_router.py
index 4ce410c842..37cec5a801 100644
--- a/tests/_server/test_file_router.py
+++ b/tests/_server/test_file_router.py
@@ -534,3 +534,80 @@ def test_lazy_router_counts_nested_files(tmp_path: Path):
total_files = count_files(files)
assert total_files == 2
+
+
+def test_lazy_router_allows_temp_dir_files(tmp_path: Path):
+ """Test that files in registered temp directories bypass validation"""
+ # Create a base directory
+ base_dir = tmp_path / "base"
+ base_dir.mkdir()
+
+ # Create a file in the base directory
+ base_file = base_dir / "base_app.py"
+ base_file.write_text("import marimo\napp = marimo.App()\n")
+
+ # Create a separate temp directory
+ temp_dir = tmp_path / "temp"
+ temp_dir.mkdir()
+
+ # Create a file in the temp directory
+ temp_file = temp_dir / "tutorial.py"
+ temp_file.write_text("import marimo\napp = marimo.App()\n")
+
+ # Create router for base directory
+ router = LazyListOfFilesAppFileRouter(
+ str(base_dir), include_markdown=False
+ )
+
+ # Without registering temp dir, accessing temp file should fail
+ with pytest.raises(HTTPException) as exc_info:
+ router.get_file_manager(str(temp_file))
+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN
+ assert "outside the allowed directory" in exc_info.value.detail
+
+ # Register the temp directory
+ router.register_temp_dir(str(temp_dir))
+
+ # Now accessing the temp file should succeed
+ manager = router.get_file_manager(str(temp_file))
+ assert manager is not None
+ assert manager.path == str(temp_file)
+
+
+def test_lazy_router_temp_dir_doesnt_affect_normal_files(
+ tmp_path: Path,
+):
+ """Test that temp dir registration doesn't interfere with normal file access"""
+ # Create a base directory
+ base_dir = tmp_path / "base"
+ base_dir.mkdir()
+
+ # Create a file in the base directory
+ base_file = base_dir / "base_app.py"
+ base_file.write_text("import marimo\napp = marimo.App()\n")
+
+ # Create a file outside the base directory
+ outside_file = tmp_path / "outside.py"
+ outside_file.write_text("import marimo\napp = marimo.App()\n")
+
+ # Create a different temp directory
+ other_temp_dir = tmp_path / "other_temp"
+ other_temp_dir.mkdir()
+
+ # Create router
+ router = LazyListOfFilesAppFileRouter(
+ str(base_dir), include_markdown=False
+ )
+
+ # Register a different temp directory (not containing our outside_file)
+ router.register_temp_dir(str(other_temp_dir))
+
+ # Base file should still be accessible
+ manager = router.get_file_manager(str(base_file))
+ assert manager is not None
+ assert manager.path == str(base_file)
+
+ # Outside file should still be blocked (not in registered temp dir)
+ with pytest.raises(HTTPException) as exc_info:
+ router.get_file_manager(str(outside_file))
+ assert exc_info.value.status_code == HTTPStatus.FORBIDDEN