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.

feat(cache): sanitize signing config from untrusted layers (#10525)

Dylan Madisetti55e2a22f8bac
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 9fcbfe572d..b63b1bb43d 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -33,6 +33,7 @@ from marimo._config.reader import (
read_marimo_config,
read_pyproject_marimo_config,
sanitize_pyproject_dict,
+ strip_untrusted_config,
)
from marimo._config.secrets import (
mask_secrets,
@@ -42,6 +43,7 @@ from marimo._config.secrets import (
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._config.utils import (
get_or_create_user_config_path,
+ is_trusted_user_config_path,
)
from marimo._utils.env import env_to_value
@@ -228,6 +230,8 @@ class ProjectConfigManager(PartialMarimoConfigReader):
project_config = self._resolve_dotenv(project_config)
project_config = self._resolve_custom_css(project_config)
project_config = self._resolve_vimrc(project_config)
+ # A cloned repo's pyproject.toml cannot anchor cache-signing trust.
+ project_config = strip_untrusted_config(project_config)
except Exception as e:
LOGGER.warning("Failed to read project config: %s", e)
return {}
@@ -455,6 +459,8 @@ class ScriptConfigManager(PartialMarimoConfigReader):
)
if marimo_config is None:
return {}
+ # PEP 723 script metadata cannot anchor cache-signing trust.
+ marimo_config = strip_untrusted_config(marimo_config)
except Exception as e:
LOGGER.warning("Failed to read script config: %s", e)
@@ -528,6 +534,13 @@ class UserConfigManager(MarimoConfigReader):
LOGGER.error("Failed to read user config at %s", path)
LOGGER.error(str(e))
return DEFAULT_CONFIG
+ if not is_trusted_user_config_path(path):
+ # A `.marimo.toml` discovered by walking up from the cwd is
+ # project-origin, not user-owned. Strip its cache-trust keys
+ # like any other untrusted layer.
+ user_config = strip_untrusted_config(
+ user_config, is_user_layer=True
+ )
return merge_default_config(user_config)
else:
LOGGER.debug("No config found; loading default settings.")
diff --git a/marimo/_config/reader.py b/marimo/_config/reader.py
index 1acc30aa88..5c1651dacc 100644
--- a/marimo/_config/reader.py
+++ b/marimo/_config/reader.py
@@ -30,27 +30,32 @@ def read_pyproject_marimo_config(
return marimo_tool_config
+def _pop_nested_key(root: dict[str, Any], key_path: tuple[str, ...]) -> bool:
+ """Delete `root[key_path...]` if present. Returns whether it was deleted."""
+ current = root
+ for key in key_path[:-1]:
+ nxt = current.get(key)
+ if not isinstance(nxt, dict):
+ return False
+ current = nxt
+ if key_path[-1] in current:
+ del current[key_path[-1]]
+ return True
+ return False
+
+
def sanitize_pyproject_dict(
pyproject_dict: dict[str, Any], keys: tuple[tuple[str, ...], ...]
) -> dict[str, Any]:
"""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:
- missing_intermediate = True
- break
- if missing_intermediate:
- continue
- if current_level and key_path[-1] in current_level:
+ # NB. each key_path is independent — a missing parent skips that path
+ # rather than aborting the rest.
+ if _pop_nested_key(pyproject_dict, key_path):
LOGGER.warning(
"%s in script metadata is ignored for security reasons",
".".join(key_path),
)
- del current_level[key_path[-1]]
return pyproject_dict
@@ -116,6 +121,61 @@ def allowlist_script_config(
return pyproject_dict
+# Settings that an untrusted-origin config layer must not set. Both take effect
+# before any cell runs, so a layer that sets one decides something the operator
+# never agreed to:
+#
+# signing trusting a key is a code-execution grant, because a
+# cache restore is `pickle.loads`
+# cache.verification whether signatures are checked at all
+#
+# Both are anchored only in trusted user/environment config.
+_UNTRUSTED_MARIMO_KEYS: tuple[tuple[str, ...], ...] = (
+ ("signing",),
+ ("cache", "verification"),
+)
+
+# `cache.store` is not a trust anchor on its own: the verifying loaders check
+# the bytes it returns before unpickling, and the unsigned `PickleLoader`
+# refuses a store it can identify as untrusted. That identification works by
+# looking for the store in the config *overrides*, which covers the project and
+# script layers. A workspace `.marimo.toml` loads as the user layer instead, so
+# it never appears there — the loader cannot tell it apart from a store the
+# operator chose. Strip it for that layer rather than leave an unidentifiable
+# store behind.
+_UNTRUSTED_USER_LAYER_KEYS: tuple[tuple[str, ...], ...] = (
+ *_UNTRUSTED_MARIMO_KEYS,
+ ("cache", "store"),
+)
+
+
+def strip_untrusted_config(
+ config: PartialMarimoConfig, *, is_user_layer: bool = False
+) -> PartialMarimoConfig:
+ """Drop security-sensitive settings from an untrusted config layer.
+
+ Mutates and returns `config`. A cloned repo's `pyproject.toml`, a shared
+ notebook's PEP 723 header, and a workspace-discovered `.marimo.toml` are all
+ untrusted origin: cloning a repo or opening a notebook is not consent to
+ that repo's author choosing whose signed cache you unpickle.
+
+ Set `is_user_layer` for the workspace `.marimo.toml`, which additionally
+ loses `cache.store`.
+ """
+ keys = (
+ _UNTRUSTED_USER_LAYER_KEYS if is_user_layer else _UNTRUSTED_MARIMO_KEYS
+ )
+ sanitized = cast(dict[str, Any], config)
+ for key_path in keys:
+ if _pop_nested_key(sanitized, key_path):
+ LOGGER.warning(
+ "Ignored %s from a configuration file that travels with the "
+ "code. Set it in your user configuration instead.",
+ ".".join(key_path),
+ )
+ return config
+
+
def get_marimo_config_from_pyproject_dict(
pyproject_dict: dict[str, Any],
) -> PartialMarimoConfig | None:
diff --git a/marimo/_config/utils.py b/marimo/_config/utils.py
index eb2f456282..5dbde45b07 100644
--- a/marimo/_config/utils.py
+++ b/marimo/_config/utils.py
@@ -121,6 +121,35 @@ def get_user_config_path() -> str | None:
return None
+def is_trusted_user_config_path(path: str) -> bool:
+ """Whether `path` is a genuinely user-owned config location.
+
+ Only the XDG config file and `~/.marimo.toml` in the home directory itself
+ are user-owned. `get_user_config_path` also returns the first `.marimo.toml`
+ found walking up from the cwd; such a file lives inside a project/repo and
+ is untrusted origin — an attacker can commit it to a cloned repo.
+ """
+ try:
+ real = os.path.realpath(path)
+ except OSError:
+ return False
+
+ trusted: set[str] = set()
+ try:
+ trusted.add(os.path.realpath(str(marimo_config_path())))
+ except OSError:
+ pass
+ home_expansion = os.path.expanduser("~")
+ if home_expansion != "~":
+ try:
+ trusted.add(
+ os.path.realpath(os.path.join(home_expansion, CONFIG_FILENAME))
+ )
+ except OSError:
+ pass
+ return real in trusted
+
+
def deep_copy(obj: Any) -> Any:
if isinstance(obj, dict):
return {k: deep_copy(v) for k, v in obj.items()} # type: ignore
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
index 681019d814..8b8338fef1 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -165,7 +165,7 @@ def create_kernel_context(
)
from marimo._save.cache import CacheState
from marimo._save.signing_policy import get_signing_policy
- from marimo._save.stores import get_store
+ from marimo._save.stores import cache_store_is_untrusted, get_store
# Storage is chosen explicitly by the caller. None means virtual files
# are not supported; we still construct an (inert) InMemoryStorage so
@@ -185,6 +185,9 @@ def create_kernel_context(
function_registry=FunctionRegistry(),
cache=CacheState(
store=get_store(kernel.app_metadata.filename),
+ store_from_untrusted_origin=cache_store_is_untrusted(
+ kernel.app_metadata.filename
+ ),
# Resolved once for the session, from the kernel's effective config
# so session/WASM-provided trust is honored. This runs before the
# kernel loads any configured `.env`, which is what freezes the
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
index ef403f2750..5771f3de3d 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -150,7 +150,7 @@ def initialize_script_context(
)
from marimo._save.cache import CacheState
from marimo._save.signing_policy import get_signing_policy
- from marimo._save.stores import get_store
+ from marimo._save.stores import cache_store_is_untrusted, get_store
runtime_context = ScriptRuntimeContext(
_app=app,
@@ -159,6 +159,7 @@ def initialize_script_context(
function_registry=FunctionRegistry(),
cache=CacheState(
store=get_store(filename),
+ store_from_untrusted_origin=cache_store_is_untrusted(filename),
signing_policy=get_signing_policy(filename),
),
cell_lifecycle_registry=CellLifecycleRegistry(),
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
index 2302bf2087..7b05048af2 100644
--- a/marimo/_save/cache.py
+++ b/marimo/_save/cache.py
@@ -77,6 +77,10 @@ class CacheState:
"""
store: Store
+ # True when `cache.store` was set by an untrusted layer (cloned repo's
+ # pyproject.toml / notebook header). Such a store must never redirect an
+ # unverified `pickle.loads` at attacker bytes.
+ store_from_untrusted_origin: bool = False
hash_memo: dict[str, bytes] = field(default_factory=dict)
# Cache-signing policy resolved once for the session from the effective
# config (user/env only; project/script trust is stripped upstream). A
diff --git a/marimo/_save/loaders/pickle.py b/marimo/_save/loaders/pickle.py
index caebbf3dc2..654f4b297e 100644
--- a/marimo/_save/loaders/pickle.py
+++ b/marimo/_save/loaders/pickle.py
@@ -4,18 +4,46 @@ from __future__ import annotations
import pickle
from typing import TYPE_CHECKING, Any
+from marimo import _loggers
from marimo._save.cache import Cache
from marimo._save.loaders.loader import BasePersistenceLoader, LoaderError
if TYPE_CHECKING:
from marimo._save.hash import HashKey
+LOGGER = _loggers.marimo_logger()
+
class PickleLoader(BasePersistenceLoader):
"""General loader for serializable objects."""
def __init__(self, name: str, **kwargs: Any) -> None:
super().__init__(name, "pickle", **kwargs)
+ # NB. `restore_cache` pickle.loads with no verification, so an
+ # untrusted layer's store must not reach it. An explicit store is
+ # trusted caller code — only the session-configured store is guarded.
+ if kwargs.get("store") is None and self._store_is_untrusted_origin():
+ from marimo._save.stores import DEFAULT_STORE
+
+ self.store = DEFAULT_STORE()
+ LOGGER.warning(
+ "Ignoring cache.store from an untrusted config layer for the "
+ "unsigned pickle loader (it would feed pickle.loads); using the "
+ "default store. Use method='lazy' to verify a shared store, or "
+ "configure the store in user config."
+ )
+
+ @staticmethod
+ def _store_is_untrusted_origin() -> bool:
+ from marimo._runtime.context import get_context
+ from marimo._runtime.context.types import (
+ ContextNotInitializedError,
+ )
+
+ try:
+ return get_context().cache.store_from_untrusted_origin
+ except ContextNotInitializedError:
+ return False
def restore_cache(self, key: HashKey, blob: bytes) -> Cache:
del key
diff --git a/marimo/_save/stores/__init__.py b/marimo/_save/stores/__init__.py
index 8dc848f1fd..123e5583b8 100644
--- a/marimo/_save/stores/__init__.py
+++ b/marimo/_save/stores/__init__.py
@@ -2,7 +2,7 @@
from __future__ import annotations
import copy
-from typing import cast
+from typing import Any, cast
from marimo import _loggers
from marimo._config.config import CacheStoreConfig, StoreKey
@@ -30,14 +30,35 @@ _STORE_REGISTRY = EntryPointRegistry[StoreType](
)
+def _store_config(config: Any) -> CacheStoreConfig | None:
+ """Read the store config out of a (possibly partial) marimo config.
+
+ Shared by `get_store` and `cache_store_is_untrusted` so store selection and
+ the provenance check can never disagree about which key they read.
+ """
+ return cast(
+ "CacheStoreConfig | None", config.get("cache", {}).get("store")
+ )
+
+
def get_store(current_path: str | None = None) -> Store:
from marimo._config.manager import get_default_config_manager
config = get_default_config_manager(current_path=current_path).get_config()
- store_config: CacheStoreConfig | None = config.get("cache", {}).get(
- "store"
- )
- return _get_store_from_config(store_config)
+ return _get_store_from_config(_store_config(config))
+
+
+def cache_store_is_untrusted(current_path: str | None = None) -> bool:
+ """Whether `cache.store` came from a layer that travels with the code."""
+ # NB. only the overrides are inspected, because a store can reach the user
+ # layer solely through a workspace `.marimo.toml`, and that layer has its
+ # store stripped during config load for exactly this reason.
+ from marimo._config.manager import get_default_config_manager
+
+ overrides = get_default_config_manager(
+ current_path=current_path
+ ).get_config_overrides()
+ return _store_config(overrides) is not None
def _get_store_from_config(
diff --git a/tests/_config/test_config_utils.py b/tests/_config/test_config_utils.py
index 37ae87eccf..98e680c2a0 100644
--- a/tests/_config/test_config_utils.py
+++ b/tests/_config/test_config_utils.py
@@ -10,8 +10,10 @@ from unittest import mock
import pytest
from marimo._config.utils import (
+ CONFIG_FILENAME,
get_or_create_user_config_path,
get_user_config_path,
+ is_trusted_user_config_path,
)
from marimo._utils.xdg import marimo_config_path
@@ -286,3 +288,29 @@ class TestGetConfigPathParentTraversal:
):
found_config_path = get_user_config_path()
assert found_config_path == expected_path
+
+
+class TestIsTrustedUserConfigPath:
+ """`get_user_config_path` returns both user-owned and project-origin files.
+
+ Only the first kind may carry security-sensitive settings, so the predicate
+ that separates them is load-bearing.
+ """
+
+ def test_xdg_config_path_is_trusted(self) -> None:
+ assert is_trusted_user_config_path(str(marimo_config_path()))
+
+ def test_home_marimo_toml_is_trusted(self) -> None:
+ home = os.path.expanduser("~")
+ assert is_trusted_user_config_path(os.path.join(home, CONFIG_FILENAME))
+
+ def test_workspace_marimo_toml_is_untrusted(self, tmp_path: Path) -> None:
+ # Found by the cwd-walk, so it lives inside a project an attacker can
+ # commit to — not user-owned.
+ assert not is_trusted_user_config_path(str(tmp_path / CONFIG_FILENAME))
+
+ def test_subdir_marimo_toml_under_home_is_untrusted(self) -> None:
+ # Under the home tree, but not the home directory itself.
+ home = os.path.expanduser("~")
+ nested = os.path.join(home, "some_repo", CONFIG_FILENAME)
+ assert not is_trusted_user_config_path(nested)
diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.py
index 8d7a663e9a..f1e77c56ef 100644
--- a/tests/_config/test_manager.py
+++ b/tests/_config/test_manager.py
@@ -13,6 +13,7 @@ from marimo._config.manager import (
EnvConfigManager,
MarimoConfigManager,
MarimoConfigReaderWithOverrides,
+ ProjectConfigManager,
ScriptConfigManager,
SecurityConfigManager,
UserConfigManager,
@@ -857,3 +858,166 @@ def test_restrict_sharing_disabled_keeps_user_config(
assert manager.get_config_overrides(hide_secrets=False)["sharing"] == {
"wasm": True
}
+
+
+# A syntactically valid fingerprint; never used to verify anything.
+_FAKE_FP = "SHA256:kV9x2cAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+
+
+def test_script_config_manager_strips_signing_and_verification(
+ tmp_path: Path,
+) -> None:
+ """A notebook header cannot anchor trust or turn verification off."""
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = f"""
+ # /// script
+ # [tool.marimo.signing]
+ # private_key_path = "/tmp/evil.pem"
+ # [tool.marimo.signing.trusted_signers]
+ # "{_FAKE_FP}" = "attacker"
+ # [tool.marimo.cache]
+ # verification = "off"
+ # ///
+ import marimo as mo
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ config = ScriptConfigManager(str(notebook_path)).get_config()
+
+ assert "signing" not in config
+ # NB. the script allowlist (ALLOWED_SCRIPT_CONFIG_TOP_KEYS) drops the whole
+ # `cache` section from script metadata, so a notebook header cannot set a
+ # store either — stricter than the project layer below.
+ assert "cache" not in config
+
+
+def test_project_config_manager_strips_signing_and_verification(
+ tmp_path: Path,
+) -> None:
+ """A cloned repo's pyproject.toml is untrusted origin for signing config."""
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_content = f"""
+ [tool.marimo.signing]
+ private_key_path = "/tmp/evil.pem"
+
+ [tool.marimo.signing.trusted_signers]
+ "{_FAKE_FP}" = "attacker"
+
+ [tool.marimo.cache]
+ verification = "off"
+
+ [tool.marimo.cache.store]
+ type = "file"
+ """
+ pyproject_path.write_text(textwrap.dedent(pyproject_content))
+
+ config = ProjectConfigManager(str(pyproject_path)).get_config()
+
+ assert "signing" not in config
+ # `cache.store` is not a trust anchor, so a project may still choose one;
+ # the verifying loaders check its bytes before unpickling.
+ assert config.get("cache") == {"store": {"type": "file"}}
+
+
+def test_effective_config_anchors_trust_in_user_layer_only(
+ tmp_path: Path,
+) -> None:
+ """Regression: project trust never reaches the merged effective config."""
+ pyproject_path = tmp_path / "pyproject.toml"
+ project_fp = "SHA256:PROJECTPROJECTPROJECTPROJECTPROJECTPROJECT0"
+ user_fp = "SHA256:USERUSERUSERUSERUSERUSERUSERUSERUSERUSERUS0"
+ pyproject_path.write_text(
+ textwrap.dedent(
+ f"""
+ [tool.marimo.signing.trusted_signers]
+ "{project_fp}" = "attacker"
+ """
+ )
+ )
+
+ manager = MarimoConfigManager(
+ UserConfigManager(),
+ ProjectConfigManager(str(pyproject_path)),
+ ).with_overrides({"signing": {"trusted_signers": {user_fp: "me"}}})
+
+ signing = manager.get_config(hide_secrets=False).get("signing", {})
+ trusted = signing.get("trusted_signers", {})
+ assert project_fp not in trusted
+ assert user_fp in trusted
+
+
+def test_workspace_marimo_toml_strips_signing_and_verification(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A `.marimo.toml` found by walking up from the cwd is project-origin.
+
+ It loads as the user layer, so it is the one untrusted layer that reaches
+ `UserConfigManager`; it must still not anchor trust.
+ """
+ cfg = tmp_path / ".marimo.toml"
+ cfg.write_text(
+ textwrap.dedent(
+ f"""
+ [signing]
+ private_key_path = "/tmp/evil.pem"
+
+ [signing.trusted_signers]
+ "{_FAKE_FP}" = "attacker"
+
+ [cache]
+ verification = "off"
+
+ [cache.store]
+ type = "file"
+ """
+ )
+ )
+ monkeypatch.setattr(
+ "marimo._config.manager.get_or_create_user_config_path",
+ lambda: str(cfg),
+ )
+ monkeypatch.setattr(
+ "marimo._config.manager.is_trusted_user_config_path",
+ lambda _path: False,
+ )
+
+ config = UserConfigManager().get_config(hide_secrets=False)
+
+ assert "signing" not in config
+ assert config.get("cache", {}).get("verification") is None
+ # The store goes too, unlike the project and script layers. A store set
+ # here would load as the user layer, so `cache_store_is_untrusted` could
+ # not tell it apart from one the operator chose, and the unsigned pickle
+ # loader would deserialize its bytes.
+ assert config.get("cache", {}).get("store") is None
+
+
+def test_trusted_user_config_location_anchors_trust(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The genuinely user-owned config (XDG / ~/.marimo.toml) may set trust."""
+ cfg = tmp_path / "marimo.toml"
+ cfg.write_text(
+ textwrap.dedent(
+ f"""
+ [signing.trusted_signers]
+ "{_FAKE_FP}" = "me"
+
+ [cache]
+ verification = "strict"
+ """
+ )
+ )
+ monkeypatch.setattr(
+ "marimo._config.manager.get_or_create_user_config_path",
+ lambda: str(cfg),
+ )
+ monkeypatch.setattr(
+ "marimo._config.manager.is_trusted_user_config_path",
+ lambda _path: True,
+ )
+
+ config = UserConfigManager().get_config(hide_secrets=False)
+
+ assert config["signing"]["trusted_signers"] == {_FAKE_FP: "me"}
+ assert config["cache"]["verification"] == "strict"
diff --git a/tests/_save/loaders/test_lazy_signing.py b/tests/_save/loaders/test_lazy_signing.py
index b0dfbe29fc..e6dc456627 100644
--- a/tests/_save/loaders/test_lazy_signing.py
+++ b/tests/_save/loaders/test_lazy_signing.py
@@ -1203,3 +1203,97 @@ class TestWasmSignatureEviction:
assert not store.hit(blob_key)
# The rejected blob is no longer advertised for export bundling.
assert blob_key not in store.export_keys()
+
+
+# ---------------------------------------------------------------------------
+# Provenance: an untrusted config layer cannot anchor trust (RFC §1.1)
+# ---------------------------------------------------------------------------
+
+
+class TestUntrustedLayerCannotAnchorTrust(_FileStoreLoaderTest):
+ """The attack cache signing exists to stop.
+
+ A repository ships a signed cache plus a `pyproject.toml` that trusts the
+ key which signed it. If that layer could anchor trust, cloning the repo and
+ opening the notebook would `pickle.loads` the attacker's bytes. The
+ fingerprint must not survive the merge, so the entry stays unverifiable:
+ a miss under `on`, a raise under `strict` — never served.
+ """
+
+ def _committed_signed_cache(self, hash_val: str) -> str:
+ """Write a signed entry the way a hostile repo would ship one.
+
+ Returns the fingerprint of the key that signed it.
+ """
+ attacker, _ = _keypair()
+ writer = self._loader(signer=attacker)
+ assert writer.save_cache(_simple_cache(hash_val=hash_val, payload=1))
+ writer.flush()
+ return attacker.fingerprint()
+
+ def _policy_for_project(self, tmp_path: Path, attacker_fp: str) -> Any:
+ from marimo._save.signing_policy import get_signing_policy
+
+ (tmp_path / "pyproject.toml").write_text(
+ "[tool.marimo.signing.trusted_signers]\n"
+ f'"{attacker_fp}" = "totally legit CI key"\n'
+ "[tool.marimo.cache]\n"
+ 'verification = "off"\n'
+ )
+ notebook = tmp_path / "notebook.py"
+ notebook.write_text("import marimo as mo")
+ return get_signing_policy(str(notebook))
+
+ def test_pyproject_fingerprint_is_not_trusted(
+ self, tmp_path: Path
+ ) -> None:
+ attacker_fp = self._committed_signed_cache("committed")
+ policy = self._policy_for_project(tmp_path, attacker_fp)
+
+ assert attacker_fp not in policy.trusted_signers
+ # The same layer also tried to switch verification off entirely.
+ assert policy.verification != "off"
+
+ def test_committed_signed_cache_misses_under_on(
+ self, tmp_path: Path
+ ) -> None:
+ attacker_fp = self._committed_signed_cache("committed_on")
+ policy = self._policy_for_project(tmp_path, attacker_fp)
+
+ reader = self._loader(
+ signer=None,
+ trusted_signers=policy.trusted_signers,
+ verification=policy.verification,
+ )
+ assert reader.load_cache(key("committed_on")) is None
+
+ def test_committed_signed_cache_raises_under_strict(
+ self, tmp_path: Path
+ ) -> None:
+ attacker_fp = self._committed_signed_cache("committed_strict")
+ policy = self._policy_for_project(tmp_path, attacker_fp)
+ _, unrelated_verifier = _keypair()
+
+ reader = self._loader(
+ signer=unrelated_verifier,
+ trusted_signers=policy.trusted_signers,
+ verification="strict",
+ )
+ with pytest.raises(CacheSignatureError):
+ reader.load_cache(key("committed_strict"))
+
+ def test_same_fingerprint_in_user_config_does_verify(self) -> None:
+ """Control: the mechanism works, only the *layer* was rejected.
+
+ Without this, the tests above would pass even if verification were
+ broken outright.
+ """
+ attacker_fp = self._committed_signed_cache("committed_control")
+ reader = self._loader(
+ signer=None,
+ trusted_signers={attacker_fp},
+ verification="on",
+ )
+ loaded = reader.load_cache(key("committed_control"))
+ assert loaded is not None
+ assert loaded.defs["payload"] == 1
diff --git a/tests/_save/loaders/test_pickle_untrusted_store.py b/tests/_save/loaders/test_pickle_untrusted_store.py
new file mode 100644
index 0000000000..7c28b98860
--- /dev/null
+++ b/tests/_save/loaders/test_pickle_untrusted_store.py
@@ -0,0 +1,95 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""The unsigned pickle loader must not be redirected by an untrusted store."""
+
+from __future__ import annotations
+
+import types
+
+from marimo._save.loaders.pickle import PickleLoader
+from marimo._save.stores import DEFAULT_STORE
+from marimo._save.stores.file import FileStore
+
+
+def _patch_ctx(monkeypatch, store, untrusted: bool) -> None:
+ ctx = types.SimpleNamespace(
+ cache=types.SimpleNamespace(
+ store=store, store_from_untrusted_origin=untrusted
+ )
+ )
+ # BasePersistenceLoader binds get_context at import; PickleLoader's guard
+ # imports it lazily from the source module. Patch both.
+ monkeypatch.setattr("marimo._save.loaders.loader.get_context", lambda: ctx)
+ monkeypatch.setattr("marimo._runtime.context.get_context", lambda: ctx)
+
+
+def test_pickle_loader_refuses_untrusted_store(monkeypatch, tmp_path) -> None:
+ attacker_store = FileStore(save_path=str(tmp_path / "attacker"))
+ _patch_ctx(monkeypatch, attacker_store, untrusted=True)
+
+ loader = PickleLoader("ns")
+
+ # The untrusted-origin store is dropped in favor of the default store, so a
+ # cloned repo's [cache].store can't feed pickle.loads.
+ assert loader.store is not attacker_store
+ assert isinstance(loader.store, DEFAULT_STORE)
+
+
+def test_pickle_loader_keeps_trusted_store(monkeypatch, tmp_path) -> None:
+ user_store = FileStore(save_path=str(tmp_path / "user"))
+ _patch_ctx(monkeypatch, user_store, untrusted=False)
+
+ loader = PickleLoader("ns")
+
+ assert loader.store is user_store
+
+
+def test_pickle_loader_honors_explicit_store(monkeypatch, tmp_path) -> None:
+ # An explicitly-passed store is caller code (trusted), honored even if the
+ # session's configured store is flagged untrusted.
+ ctx_store = FileStore(save_path=str(tmp_path / "attacker"))
+ _patch_ctx(monkeypatch, ctx_store, untrusted=True)
+
+ explicit = FileStore(save_path=str(tmp_path / "explicit"))
+ loader = PickleLoader("ns", store=explicit)
+
+ assert loader.store is explicit
+
+
+def test_workspace_marimo_toml_store_never_reaches_the_loader(
+ monkeypatch, tmp_path
+) -> None:
+ """End-to-end: a committed `.marimo.toml` cannot choose the pickle store.
+
+ A store set there loads as the *user* layer, so it never shows up in the
+ config overrides that `cache_store_is_untrusted` inspects. Stripping it at
+ the config layer is what keeps it away from an unverified `pickle.loads`;
+ without that, this store would be treated as operator-chosen.
+ """
+ from marimo._config.manager import UserConfigManager
+ from marimo._save.stores import cache_store_is_untrusted, get_store
+
+ workspace_config = tmp_path / ".marimo.toml"
+ workspace_config.write_text(
+ '[cache.store]\ntype = "file"\nargs = { save_path = "/tmp/attacker" }\n'
+ )
+ monkeypatch.setattr(
+ "marimo._config.manager.get_or_create_user_config_path",
+ lambda: str(workspace_config),
+ )
+ monkeypatch.setattr(
+ "marimo._config.manager.is_trusted_user_config_path",
+ lambda _path: False,
+ )
+
+ # Stripped at the config layer, so nothing downstream has to identify it.
+ config = UserConfigManager().get_config(hide_secrets=False)
+ assert config.get("cache", {}).get("store") is None
+
+ # Note it is *not* reachable as an "untrusted override" either, because the
+ # user layer is not an override — which is exactly why stripping is needed.
+ assert cache_store_is_untrusted(str(tmp_path)) is False
+
+ # Store selection falls back to the default rather than the named path.
+ store = get_store(str(tmp_path))
+ assert isinstance(store, DEFAULT_STORE)
+ assert "attacker" not in str(getattr(store, "save_path", ""))
diff --git a/tests/_save/stores/test_store_config.py b/tests/_save/stores/test_store_config.py
index 978e6dd67e..90e69268ac 100644
--- a/tests/_save/stores/test_store_config.py
+++ b/tests/_save/stores/test_store_config.py
@@ -103,3 +103,38 @@ class TestGetStore:
def test_no_cache_config_uses_default(self, monkeypatch) -> None:
store = self._store_for(monkeypatch, {})
assert isinstance(store, DEFAULT_STORE)
+
+
+class TestCacheStoreProvenance:
+ """cache_store_is_untrusted flags a store set by a project/script layer."""
+
+ def _untrusted_for(self, monkeypatch, overrides) -> bool:
+ from marimo._save import stores as stores_mod
+
+ class _Mgr:
+ def get_config_overrides(self):
+ # project + script + env, merged (env never sets a store).
+ return overrides
+
+ monkeypatch.setattr(
+ "marimo._config.manager.get_default_config_manager",
+ lambda **_kwargs: _Mgr(),
+ )
+ return stores_mod.cache_store_is_untrusted()
+
+ def test_project_store_is_untrusted(self, monkeypatch) -> None:
+ assert self._untrusted_for(
+ monkeypatch, {"cache": {"store": {"type": "rest"}}}
+ )
+
+ def test_script_store_is_untrusted(self, monkeypatch) -> None:
+ assert self._untrusted_for(
+ monkeypatch, {"cache": {"store": [{"type": "file"}]}}
+ )
+
+ def test_no_override_store_is_trusted(self, monkeypatch) -> None:
+ # Store set only in the (trusted) user layer never appears in overrides.
+ assert not self._untrusted_for(monkeypatch, {})
+ assert not self._untrusted_for(
+ monkeypatch, {"cache": {"verification": "on"}}
+ )