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(export): inline `public/` images in static HTML export (#9627)

Myles Scolnick92a02eefec20
diff --git a/marimo/_convert/common/dom_traversal.py b/marimo/_convert/common/dom_traversal.py
index b2dade93f1..0779b2b5d7 100644
--- a/marimo/_convert/common/dom_traversal.py
+++ b/marimo/_convert/common/dom_traversal.py
@@ -14,6 +14,7 @@ from marimo._utils.data_uri import build_data_url
if TYPE_CHECKING:
from collections.abc import Callable
+ from pathlib import Path
LOGGER = _loggers.marimo_logger()
@@ -345,3 +346,124 @@ def replace_virtual_files_with_data_uris(
)
return processed_html, replaced_files
+
+
+# Public folder file pattern: public/{path} or ./public/{path}
+_PUBLIC_FILE_PATTERN = re.compile(r"^(?:\./)?public/(.+)$")
+
+
+def _resolve_public_file(public_dir: Path, relpath: str) -> Path | None:
+ """Resolve a `public/`-prefixed path against the public dir.
+
+ Returns the resolved path if it points to an existing regular file
+ strictly inside `public_dir`, or None otherwise. Rejects path traversal
+ and symlinks that escape the public directory.
+ """
+ try:
+ # `strict=True` ensures the file exists.
+ # `RuntimeError` covers symlink loops on Python 3.10–3.12.
+ candidate = (public_dir / relpath).resolve(strict=True)
+ public_resolved = public_dir.resolve(strict=True)
+ except (OSError, RuntimeError, ValueError):
+ return None
+
+ # Containment check: the resolved file must live under the resolved
+ # public directory (catches path traversal and symlink escapes).
+ try:
+ candidate.relative_to(public_resolved)
+ except ValueError:
+ return None
+
+ if not candidate.is_file():
+ return None
+
+ return candidate
+
+
+def replace_public_files_with_data_uris(
+ html: str,
+ public_dir: Path,
+ *,
+ allowed_tags: set[str] | None = None,
+ allowed_attributes: set[str] | None = None,
+ max_inline_bytes: int | None = None,
+) -> tuple[str, set[str]]:
+ """Inline `public/`-prefixed file references as data URIs.
+
+ Scans `html` for media tag attributes (e.g. `<img src="public/...">`),
+ reads the referenced file from the notebook's `public/` folder, and
+ replaces the attribute value with a base64-encoded data URI so the
+ HTML can be served standalone. Paths that escape `public_dir` (via
+ `..` segments or symlinks) are rejected and left unchanged.
+
+ Args:
+ html: The HTML string to process.
+ public_dir: Path to the notebook's `public/` directory.
+ allowed_tags: Tags to scan. Defaults to {"img", "audio", "video",
+ "source"}.
+ allowed_attributes: Attributes to scan. Defaults to {"src"}.
+ max_inline_bytes: Maximum file size to inline. Larger files are
+ left as-is. None means no limit.
+
+ Returns:
+ Tuple of (processed_html, replaced_paths) where `replaced_paths`
+ is the set of attribute values that were successfully inlined.
+ """
+ if allowed_tags is None:
+ allowed_tags = {"img", "audio", "video", "source"}
+ if allowed_attributes is None:
+ allowed_attributes = {"src"}
+
+ replaced: set[str] = set()
+
+ # If the public directory does not exist, there is nothing to inline.
+ if not public_dir.exists():
+ return html, replaced
+
+ def replacer(value: str) -> str | None:
+ match = _PUBLIC_FILE_PATTERN.match(value)
+ if not match:
+ return None
+ relpath = match.group(1)
+ resolved = _resolve_public_file(public_dir, relpath)
+ if resolved is None:
+ return None
+ # Check size via stat() before reading so an oversized file never
+ # gets loaded into memory.
+ try:
+ file_size = resolved.stat().st_size
+ except OSError as e:
+ LOGGER.warning(
+ "Failed to stat public file %s during export: %s", value, e
+ )
+ return None
+ if max_inline_bytes is not None and file_size > max_inline_bytes:
+ LOGGER.info(
+ "Skipping public file %s (%d bytes exceeds %d byte inline"
+ " limit)",
+ value,
+ file_size,
+ max_inline_bytes,
+ )
+ return None
+ try:
+ file_bytes = resolved.read_bytes()
+ except OSError as e:
+ LOGGER.warning(
+ "Failed to read public file %s during export: %s", value, e
+ )
+ return None
+ mime_type = mimetypes.guess_type(resolved.name)[0] or "text/plain"
+ replaced.add(value)
+ return build_data_url(
+ cast(KnownMimeType, mime_type),
+ base64.b64encode(file_bytes),
+ )
+
+ processed_html = replace_html_attributes(
+ html=html,
+ allowed_tags=allowed_tags,
+ allowed_attributes=allowed_attributes,
+ replacer_fn=replacer,
+ )
+ return processed_html, replaced
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index cee285b552..4ba6c01816 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -19,6 +19,7 @@ from marimo._config.config import (
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._config.utils import deep_copy
from marimo._convert.common.dom_traversal import (
+ replace_public_files_with_data_uris,
replace_virtual_files_with_data_uris,
)
from marimo._convert.common.filename import (
@@ -55,7 +56,7 @@ from marimo._utils.paths import marimo_package_path, notebook_output_dir
from marimo._version import __version__
if TYPE_CHECKING:
- from collections.abc import Mapping
+ from collections.abc import Iterator, Mapping
from traitlets.config import Config
@@ -121,6 +122,13 @@ class Exporter:
session_snapshot
)
+ # Inline references to files in the notebook's `public/` folder so
+ # the exported HTML is self-contained. Without this, `mo.md` images
+ # like `![alt](public/image.png)` break when the HTML is opened
+ # outside the notebook's directory.
+ public_dir = Path(filename).resolve().parent / "public"
+ self._inline_public_files(session_snapshot, public_dir)
+
app_code = app.to_py()
# Prepare code for export
@@ -168,6 +176,27 @@ class Exporter:
config["display"] = display_config
return cast(MarimoConfig, config)
+ @staticmethod
+ def _iter_html_data_strings(
+ session_snapshot: NotebookSessionV1,
+ ) -> Iterator[tuple[dict[str, Any], str, str]]:
+ """Yield (output_data_dict, mime_type, data) for each `text/html`
+ string output.
+
+ Only `text/html` outputs are returned: non-HTML mime entries (e.g.
+ `text/plain`, `application/json`) must not be HTML-parsed, since
+ their content is opaque to the attribute-replacement logic.
+ """
+ for cell in session_snapshot["cells"]:
+ for output in cell["outputs"]:
+ if output["type"] != "data":
+ continue
+ for mime_type, data in output["data"].items():
+ if mime_type != "text/html":
+ continue
+ if isinstance(data, str):
+ yield output["data"], mime_type, data
+
def _inline_virtual_files(
self, session_snapshot: NotebookSessionV1
) -> tuple[NotebookSessionV1, set[str]]:
@@ -178,27 +207,45 @@ class Exporter:
"""
replaced_files: set[str] = set()
- for cell in session_snapshot["cells"]:
- for output in cell["outputs"]:
- if output["type"] != "data":
- continue
+ for data_dict, mime_type, data in self._iter_html_data_strings(
+ session_snapshot
+ ):
+ if self._VIRTUAL_FILE_PATTERN not in data:
+ continue
+ processed, files = replace_virtual_files_with_data_uris(
+ data,
+ allowed_tags=VIRTUAL_FILE_ALLOWED_TAGS,
+ allowed_attributes=VIRTUAL_FILE_ALLOWED_ATTRIBUTES,
+ max_inline_bytes=MAX_VIRTUAL_FILE_INLINE_BYTES,
+ )
+ replaced_files.update(files)
+ data_dict[mime_type] = processed
- for mime_type, data in output["data"].items():
- if not isinstance(data, str):
- continue
- if self._VIRTUAL_FILE_PATTERN not in data:
- continue
+ return session_snapshot, replaced_files
- processed, files = replace_virtual_files_with_data_uris(
- data,
- allowed_tags=VIRTUAL_FILE_ALLOWED_TAGS,
- allowed_attributes=VIRTUAL_FILE_ALLOWED_ATTRIBUTES,
- max_inline_bytes=MAX_VIRTUAL_FILE_INLINE_BYTES,
- )
- replaced_files.update(files)
- output["data"][mime_type] = processed
+ def _inline_public_files(
+ self,
+ session_snapshot: NotebookSessionV1,
+ public_dir: Path,
+ ) -> None:
+ """Replace `public/`-prefixed file paths in HTML outputs with data URIs.
- return session_snapshot, replaced_files
+ Mutates `session_snapshot` in-place.
+ """
+ if not public_dir.exists():
+ return
+
+ for data_dict, mime_type, data in self._iter_html_data_strings(
+ session_snapshot
+ ):
+ if "public/" not in data:
+ continue
+ processed, _ = replace_public_files_with_data_uris(
+ data,
+ public_dir=public_dir,
+ max_inline_bytes=MAX_VIRTUAL_FILE_INLINE_BYTES,
+ )
+ data_dict[mime_type] = processed
def _prepare_code(
self,
diff --git a/tests/_convert/common/test_dom_traversal.py b/tests/_convert/common/test_dom_traversal.py
index bf2fad06df..ad1c500e54 100644
--- a/tests/_convert/common/test_dom_traversal.py
+++ b/tests/_convert/common/test_dom_traversal.py
@@ -1,12 +1,18 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import base64
+from typing import TYPE_CHECKING
from unittest.mock import patch
+if TYPE_CHECKING:
+ from pathlib import Path
+
from marimo._convert.common.dom_traversal import (
_is_virtual_file_url,
_parse_virtual_file_url,
replace_html_attributes,
+ replace_public_files_with_data_uris,
replace_virtual_files_with_data_uris,
)
@@ -285,3 +291,342 @@ class TestVirtualFileReplacement:
assert "./@file/9999999-large.wav" not in result
assert "data:text/plain;base64," in result
assert "./@file/9999999-large.wav" not in replaced
+
+
+class TestPublicFileReplacement:
+ def test_inlines_public_image(self, tmp_path: Path) -> None:
+ """Test that public/ image references are inlined as data URIs."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ data = b"\x89PNG\r\n\x1a\nfake"
+ (public_dir / "image.png").write_bytes(data)
+
+ html = '<img src="public/image.png">'
+
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert 'src="public/image.png"' not in result
+ assert "data:image/png;base64," in result
+ assert base64.b64encode(data).decode() in result
+ assert replaced == {"public/image.png"}
+
+ def test_inlines_dot_slash_public_image(self, tmp_path: Path) -> None:
+ """Test that ./public/ prefix is also inlined."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (public_dir / "image.png").write_bytes(b"data")
+
+ html = '<img src="./public/image.png">'
+
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert "data:image/png;base64," in result
+ assert replaced == {"./public/image.png"}
+
+ def test_inlines_nested_public_file(self, tmp_path: Path) -> None:
+ """Test that nested files under public/ work."""
+ public_dir = tmp_path / "public"
+ (public_dir / "imgs").mkdir(parents=True)
+ (public_dir / "imgs" / "logo.svg").write_bytes(b"<svg/>")
+
+ html = '<img src="public/imgs/logo.svg">'
+
+ result, _ = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert "data:image/svg+xml;base64," in result
+
+ def test_blocks_path_traversal(self, tmp_path: Path) -> None:
+ """Test that path traversal escaping public/ is rejected."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (tmp_path / "secret.txt").write_bytes(b"shh")
+
+ html = '<img src="public/../secret.txt">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ # Original src is preserved; secret is not inlined.
+ assert base64.b64encode(b"shh").decode() not in result
+ assert replaced == set()
+
+ def test_ignores_external_urls(self, tmp_path: Path) -> None:
+ """Test that http(s) URLs are not touched."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+
+ html = '<img src="https://example.com/img.png">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert result == html
+ assert replaced == set()
+
+ def test_ignores_other_relative_paths(self, tmp_path: Path) -> None:
+ """Test that non-public relative paths are not touched."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (tmp_path / "other.png").write_bytes(b"data")
+
+ html = '<img src="other.png">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert result == html
+ assert replaced == set()
+
+ def test_missing_file_left_unchanged(self, tmp_path: Path) -> None:
+ """Test that references to missing files are kept as-is."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+
+ html = '<img src="public/missing.png">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert 'src="public/missing.png"' in result
+ assert replaced == set()
+
+ def test_max_inline_bytes_skips_large_file(self, tmp_path: Path) -> None:
+ """Test that files exceeding max_inline_bytes are skipped."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (public_dir / "big.png").write_bytes(b"x" * 1000)
+
+ html = '<img src="public/big.png">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir, max_inline_bytes=100
+ )
+
+ # Large file is not inlined as image; original src is preserved.
+ assert "data:image/png;base64," not in result
+ assert 'src="public/big.png"' in result
+ assert replaced == set()
+
+ def test_audio_and_video_tags(self, tmp_path: Path) -> None:
+ """Test that audio and video public references are inlined too."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (public_dir / "clip.mp4").write_bytes(b"video_data")
+
+ html = '<video src="public/clip.mp4"></video>'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert "data:video/mp4;base64," in result
+ assert replaced == {"public/clip.mp4"}
+
+ def test_no_public_dir(self, tmp_path: Path) -> None:
+ """Test that a missing public directory yields no-op."""
+ public_dir = tmp_path / "public"
+ # Note: do not create public_dir
+
+ html = '<img src="public/image.png">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert result == html
+ assert replaced == set()
+
+
+class TestPublicFileSecurity:
+ """Security-focused tests for `replace_public_files_with_data_uris`.
+
+ These pin the path-traversal and symlink-escape protections expected of
+ HTML export — matching the runtime contract documented at
+ docs/guides/outputs.md ("Only files within the public directory can be
+ accessed; symlinks are not followed; path traversal is blocked").
+ """
+
+ def test_dot_dot_traversal(self, tmp_path: Path) -> None:
+ """`public/../secret.txt` must not be inlined."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (tmp_path / "secret.txt").write_bytes(b"shh")
+
+ html = '<img src="public/../secret.txt">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert base64.b64encode(b"shh").decode() not in result
+ assert replaced == set()
+
+ def test_nested_dot_dot_traversal(self, tmp_path: Path) -> None:
+ """Repeated `..` segments must not escape `public/`."""
+ public_dir = tmp_path / "public"
+ (public_dir / "sub").mkdir(parents=True)
+ (tmp_path / "secret.txt").write_bytes(b"shh")
+
+ html = '<img src="public/sub/../../secret.txt">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert base64.b64encode(b"shh").decode() not in result
+ assert replaced == set()
+
+ def test_absolute_path_in_subpath(self, tmp_path: Path) -> None:
+ """`public//etc/passwd`-style src (pathlib joins abs paths to abs)
+ must not read outside `public_dir`."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ outside = tmp_path / "secret.txt"
+ outside.write_bytes(b"shh")
+
+ html = f'<img src="public/{outside}">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert base64.b64encode(b"shh").decode() not in result
+ assert replaced == set()
+
+ def test_symlink_inside_public_escaping(self, tmp_path: Path) -> None:
+ """A symlink inside `public/` pointing at a file outside must be
+ rejected (consistent with the runtime `serve_public_file` policy)."""
+ import os
+
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ secret = tmp_path / "secret.txt"
+ secret.write_bytes(b"shh")
+
+ link = public_dir / "escape.txt"
+ try:
+ os.symlink(secret, link)
+ except (OSError, NotImplementedError):
+ import pytest
+
+ pytest.skip("Symlinks not supported on this platform")
+
+ html = '<img src="public/escape.txt">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert base64.b64encode(b"shh").decode() not in result
+ assert replaced == set()
+
+ def test_symlink_inside_public_pointing_inside(
+ self, tmp_path: Path
+ ) -> None:
+ """A symlink that stays inside `public/` is allowed (matches the
+ runtime policy: containment, not symlink rejection)."""
+ import os
+
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ real = public_dir / "real.png"
+ real.write_bytes(b"img")
+
+ link = public_dir / "link.png"
+ try:
+ os.symlink(real, link)
+ except (OSError, NotImplementedError):
+ import pytest
+
+ pytest.skip("Symlinks not supported on this platform")
+
+ html = '<img src="public/link.png">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert "data:image/png;base64," in result
+ assert base64.b64encode(b"img").decode() in result
+ assert replaced == {"public/link.png"}
+
+ def test_directory_reference_not_inlined(self, tmp_path: Path) -> None:
+ """A src that resolves to a directory (e.g. `public/.`) must not
+ be inlined."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+
+ html = '<img src="public/.">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert "data:" not in result
+ assert replaced == set()
+
+ def test_oversized_file_is_not_read_into_memory(
+ self, tmp_path: Path
+ ) -> None:
+ """Files exceeding `max_inline_bytes` must be size-checked via
+ `stat()` and skipped *without* being read into memory."""
+ from unittest.mock import patch
+
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (public_dir / "big.bin").write_bytes(b"x" * 1000)
+
+ html = '<img src="public/big.bin">'
+
+ with patch(
+ "pathlib.Path.read_bytes",
+ side_effect=AssertionError("should not be called"),
+ ):
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir, max_inline_bytes=100
+ )
+
+ assert "data:" not in result
+ assert replaced == set()
+
+ def test_symlink_loop_does_not_crash(self, tmp_path: Path) -> None:
+ """A symlink loop under `public/` must not crash export.
+
+ On some Python versions `Path.resolve(strict=True)` raises
+ `RuntimeError` (not `OSError`) for loops, so the helper has to
+ catch it explicitly.
+ """
+ import os
+
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ loop_a = public_dir / "a"
+ loop_b = public_dir / "b"
+ try:
+ os.symlink(loop_b, loop_a)
+ os.symlink(loop_a, loop_b)
+ except (OSError, NotImplementedError):
+ import pytest
+
+ pytest.skip("Symlinks not supported on this platform")
+
+ html = '<img src="public/a">'
+ # Must not raise.
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert "data:" not in result
+ assert replaced == set()
+
+ def test_absolute_public_prefix_not_matched(self, tmp_path: Path) -> None:
+ """A bare absolute `/public/...` path (server URL form) must not
+ be interpreted as a filesystem-relative public reference."""
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ (public_dir / "image.png").write_bytes(b"img")
+
+ html = '<img src="/public/image.png">'
+ result, replaced = replace_public_files_with_data_uris(
+ html, public_dir=public_dir
+ )
+
+ assert result == html
+ assert replaced == set()
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 09da723060..6820ac727a 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -980,6 +980,182 @@ def test_export_html_replaces_audio_virtual_files(
assert expected_b64 in html
+def test_export_html_inlines_public_folder_images(
+ session_view: SessionView, tmp_path: Path
+) -> None:
+ """Test that <img src="public/..."> references are inlined as data URIs.
+
+ Regression test for marimo-team/marimo#9625: a markdown cell like
+ `mo.md("![alt](public/image.png)")` produces HTML output that points at
+ `public/image.png`. The standalone exported HTML must inline those
+ images so the file is self-contained when opened without the sibling
+ `public/` folder.
+ """
+ # Arrange: notebook file with a sibling public/image.png
+ notebook_path = tmp_path / "nb.py"
+ notebook_path.write_text("import marimo\napp = marimo.App()\n")
+ public_dir = tmp_path / "public"
+ public_dir.mkdir()
+ png_bytes = b"\x89PNG\r\n\x1a\nfakeimage"
+ (public_dir / "image.png").write_bytes(png_bytes)
+
+ app = App()
+
+ @app.cell()
+ def cell_md():
+ import marimo as mo
+
+ return mo.md("![alt](public/image.png)")
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ cell_ids = list(file_manager.app.cell_manager.cell_ids())
+
+ # Simulate the HTML output that mo.md produces at runtime: the raw
+ # `public/image.png` path is preserved (no inlining at runtime).
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
+ cell_id=cell_ids[0],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data=(
+ '<span class="markdown">'
+ '<img alt="alt" src="public/image.png">'
+ "</span>"
+ ),
+ ),
+ console=[],
+ timestamp=0,
+ )
+
+ exporter = Exporter()
+ request = ExportAsHTMLRequest(
+ download=True,
+ files=[],
+ include_code=True,
+ )
+
+ html, _filename = exporter.export_as_html(
+ filename=str(notebook_path),
+ app=file_manager.app,
+ session_view=session_view,
+ display_config=DEFAULT_CONFIG["display"],
+ request=request,
+ )
+
+ # The original path is gone; the image is embedded as a data URI.
+ assert 'src="public/image.png"' not in html
+ assert "data:image/png;base64," in html
+ assert base64.b64encode(png_bytes).decode() in html
+
+
+def test_export_html_does_not_touch_non_html_outputs(
+ session_view: SessionView, tmp_path: Path
+) -> None:
+ """text/plain (and other non-HTML) outputs must NOT be HTML-parsed.
+
+ Regression guard: previously `_iter_html_data_strings` yielded every
+ string mime entry, which meant `text/plain` data containing literal
+ `./@file/...` text was rewritten as if it were HTML.
+ """
+ notebook_path = tmp_path / "nb.py"
+ notebook_path.write_text("import marimo\napp = marimo.App()\n")
+
+ app = App()
+
+ @app.cell()
+ def _():
+ return None
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ cell_ids = list(file_manager.app.cell_manager.cell_ids())
+
+ # A plain-text output that happens to contain virtual-file and public/
+ # tokens — these must NOT be rewritten because the mime is text/plain.
+ plain = "see ./@file/100-test.png or public/image.png"
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
+ cell_id=cell_ids[0],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data=plain,
+ ),
+ console=[],
+ timestamp=0,
+ )
+
+ exporter = Exporter()
+ request = ExportAsHTMLRequest(
+ download=True,
+ files=[],
+ include_code=True,
+ )
+
+ html, _ = exporter.export_as_html(
+ filename=str(notebook_path),
+ app=file_manager.app,
+ session_view=session_view,
+ display_config=DEFAULT_CONFIG["display"],
+ request=request,
+ )
+
+ # The plain-text content is preserved verbatim (JSON-escaped in the
+ # session snapshot, hence the substring check rather than equality).
+ assert "./@file/100-test.png" in html
+ assert "public/image.png" in html
+
+
+def test_export_html_public_folder_blocks_path_traversal(
+ session_view: SessionView, tmp_path: Path
+) -> None:
+ """Test that path traversal attempts via public/ paths are rejected."""
+ notebook_path = tmp_path / "nb.py"
+ notebook_path.write_text("import marimo\napp = marimo.App()\n")
+ (tmp_path / "public").mkdir()
+ # File OUTSIDE the public/ folder that an attacker would try to read.
+ (tmp_path / "secret.txt").write_bytes(b"shh")
+
+ app = App()
+
+ @app.cell()
+ def cell_md():
+ return None
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ cell_ids = list(file_manager.app.cell_manager.cell_ids())
+
+ session_view.cell_notifications[cell_ids[0]] = CellNotification(
+ cell_id=cell_ids[0],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data='<img src="public/../secret.txt">',
+ ),
+ console=[],
+ timestamp=0,
+ )
+
+ exporter = Exporter()
+ request = ExportAsHTMLRequest(
+ download=True,
+ files=[],
+ include_code=True,
+ )
+
+ html, _ = exporter.export_as_html(
+ filename=str(notebook_path),
+ app=file_manager.app,
+ session_view=session_view,
+ display_config=DEFAULT_CONFIG["display"],
+ request=request,
+ )
+
+ # The secret file must NOT be inlined.
+ assert base64.b64encode(b"shh").decode() not in html
+
+
def test_export_html_skips_oversized_virtual_files(
session_view: SessionView,
) -> None: