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
refactor(cache): introduce SigningPolicy and rename mode to verification (#10524)
Dylan Madisetti3dbe26fecd6d
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.pyindex 44cf94d77e..681019d814 100644--- a/marimo/_runtime/context/kernel_context.py+++ b/marimo/_runtime/context/kernel_context.py@@ -164,6 +164,7 @@ def create_kernel_context(VirtualFileStorage,)from marimo._save.cache import CacheState+ from marimo._save.signing_policy import get_signing_policyfrom marimo._save.stores import get_store# Storage is chosen explicitly by the caller. None means virtual files@@ -182,7 +183,22 @@ def create_kernel_context(ui_element_registry=UIElementRegistry(),state_registry=StateRegistry(),function_registry=FunctionRegistry(),- cache=CacheState(store=get_store(kernel.app_metadata.filename)),+ cache=CacheState(+ store=get_store(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+ # signing identity to the inherited environment. An embedded child+ # context inherits the parent's policy rather than resolving a+ # second one, which by then would read a post-dotenv environment.+ signing_policy=(+ parent.cache.signing_policy+ if parent is not None+ else get_signing_policy(+ kernel.app_metadata.filename, config=kernel.user_config+ )+ ),+ ),cell_lifecycle_registry=CellLifecycleRegistry(),app_kernel_runner_registry=(parent.app_kernel_runner_registrydiff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.pyindex 7feed3faf3..ef403f2750 100644--- a/marimo/_runtime/context/script_context.py+++ b/marimo/_runtime/context/script_context.py@@ -149,6 +149,7 @@ def initialize_script_context(VirtualFileRegistry,)from marimo._save.cache import CacheState+ from marimo._save.signing_policy import get_signing_policyfrom marimo._save.stores import get_storeruntime_context = ScriptRuntimeContext(@@ -156,7 +157,10 @@ def initialize_script_context(ui_element_registry=UIElementRegistry(),state_registry=StateRegistry(),function_registry=FunctionRegistry(),- cache=CacheState(store=get_store(filename)),+ cache=CacheState(+ store=get_store(filename),+ signing_policy=get_signing_policy(filename),+ ),cell_lifecycle_registry=CellLifecycleRegistry(),app_kernel_runner_registry=AppKernelRunnerRegistry(),virtual_file_registry=VirtualFileRegistry(storage=InMemoryStorage()),diff --git a/marimo/_save/cache.py b/marimo/_save/cache.pyindex 8f84553f53..2302bf2087 100644--- a/marimo/_save/cache.py+++ b/marimo/_save/cache.py@@ -42,6 +42,7 @@ if TYPE_CHECKING:from marimo._save.hash import HashKeyfrom marimo._save.loaders import Loaderfrom marimo._save.loaders.lazy import LazyLoader+ from marimo._save.signing_policy import SigningPolicyfrom marimo._save.stores import Store# NB. Increment on cache breaking changes.@@ -77,6 +78,10 @@ class CacheState:store: Storehash_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+ # `LazyLoader` reads it as the default trust/identity source.+ signing_policy: SigningPolicy | None = None# Lazy-store session state; see `loaders/lazy.py:_cache_state`.active_lazy_loaders: dict[str, LazyLoader] = field(default_factory=dict)poisoned_keys: set[str] = field(default_factory=set)diff --git a/marimo/_save/loaders/lazy.py b/marimo/_save/loaders/lazy.pyindex b612e9ed4d..5f623defc6 100644--- a/marimo/_save/loaders/lazy.py+++ b/marimo/_save/loaders/lazy.py@@ -1,7 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import base64import hashlibimport importlibimport inspect@@ -31,11 +30,15 @@ from marimo._save.encode import common_container_to_bytes, data_to_bufferfrom marimo._save.hash import DEFAULT_HASH, HashKeyfrom marimo._save.loaders.loader import BasePersistenceLoaderfrom marimo._save.signing import (+ DEFAULT_VERIFICATION,CacheSignatureError,CacheSigner,_get_default_signer,+ _get_machine_signer,_sha256hex,fingerprint,+ normalize_fingerprints,+ normalize_verification,)from marimo._save.stores import DEFAULT_STORE, FileStore, Store@@ -64,81 +67,17 @@ LOGGER = _loggers.marimo_logger()class _Unset:- """Sentinel for LazyLoader.signer default — distinguishes 'not provided'- from explicit `None` (which opts out of signing entirely)."""+ """Sentinel distinguishing 'not provided' from an explicit value.--_SIGNER_UNSET = _Unset()--# Verification posture. `off`: no signing or verification (legacy / opt-out).-# `verify` (default): sign on write, and on read serve only entries that-# verify against a trusted key — unverifiable entries miss and recompute-# (fail-safe). `strict`: like verify, but an unverifiable entry raises-# (fail-closed).-_VALID_MODES = ("off", "verify", "strict")---# Fingerprint digests use standard base64 (matching `ssh-keygen -lf`-# presentation). Accept a urlsafe-encoded paste too and canonicalize it so it-# still matches fingerprint() output.-_FP_URLSAFE_TO_STD = str.maketrans("-_", "+/")---def _normalize_fingerprint(fp: str) -> str:- """Validate and canonicalize one `"SHA256:<base64>"` fingerprint.-- Accepts standard or urlsafe base64, padded or unpadded, and returns the- canonical form produced by :func:`marimo._save.signing.fingerprint`- (standard base64, no padding). Raising on a malformed digest here turns a- fat-fingered fingerprint into a configuration-time error rather than a- permanent, silent cache miss (the digest would validate on prefix alone but- never match a real key).+ For `signer`, `None` opts out of signing, so an unset default cannot also be+ `None`. An unset `signer`, `trusted_signers` or `verification` falls back to+ the session policy rather than to a hardcoded default."""- import binascii-- if not isinstance(fp, str) or not fp.startswith("SHA256:"):- raise ValueError(- f"Invalid trusted_signers fingerprint {fp!r}; expected "- "'SHA256:<base64>' as produced by "- "marimo._save.signing.fingerprint()."- )- body = fp[len("SHA256:") :].translate(_FP_URLSAFE_TO_STD).rstrip("=")- try:- raw = base64.b64decode(body + "=" * (-len(body) % 4), validate=True)- except (binascii.Error, ValueError) as e:- raise ValueError(- f"Invalid trusted_signers fingerprint {fp!r}; the digest is not "- "valid base64."- ) from e- if len(raw) != 32:- raise ValueError(- f"Invalid trusted_signers fingerprint {fp!r}; expected a SHA-256 "- f"(32-byte) digest, got {len(raw)} byte(s)."- )- # Re-encode from the decoded bytes rather than returning `body` verbatim.- # base64 of 32 bytes has 2 unused ("slack") bits in the final character, so- # several distinct final characters decode to the same digest; returning- # the raw text would let such a variant validate here yet never match the- # canonical form emitted by signing.fingerprint() — a permanent silent miss.- return "SHA256:" + base64.b64encode(raw).decode("ascii").rstrip("=")--def _normalize_fingerprints(value: Iterable[str] | None) -> set[str]:- """Validate and collect `trusted_signers` fingerprint strings.- Rejects a bare `str` (which would otherwise iterate into single- characters — a silent-miss footgun) and canonicalizes each entry via- :func:`_normalize_fingerprint` so a padded or urlsafe paste still matches- :func:`marimo._save.signing.fingerprint` output.- """- if value is None:- return set()- if isinstance(value, str):- raise TypeError(- "trusted_signers must be an iterable of fingerprint strings, not "- "a single str. Wrap it in a set/list: trusted_signers={fp}."- )- return {_normalize_fingerprint(fp) for fp in value}+_SIGNER_UNSET = _Unset()+_VERIFICATION_UNSET = _Unset()+_TRUSTED_UNSET = _Unset()class _BlobStatus(Enum):@@ -191,16 +130,21 @@ def _is_local_file_store(store: Store) -> bool:return isinstance(store, FileStore)+def _is_wasm_same_origin_store(store: Store) -> bool:+ """True when a store's blobs share the notebook's own origin."""+ # NB. WebAssembly blobs are fetched from the notebook location, so swapping+ # them requires control of the notebook code served from that origin.+ # Verification adds nothing there, which is why it is the only store+ # exempted while signing is available.+ return isinstance(store, WasmLazyStore)++def _is_trusted_origin_store(store: Store) -> bool:- """True when a verify capability gap may degrade to `off` (serve- unverified) instead of missing every read."""- # NB. WASM blobs are fetched same-origin from the notebook location; an- # attacker who can swap them already controls the notebook code served- # from that origin, so verification adds nothing. Shared/remote stores are- # what signing protects, so they are never trusted (no degrade).- if isinstance(store, WasmLazyStore):- return True- return _is_local_file_store(store)+ """True when a store's bytes are reachable only by controlling the code."""+ # NB. a local cache directory sits behind the same filesystem access as the+ # notebook file. Shared and remote stores are what signing protects, so+ # they never qualify.+ return _is_wasm_same_origin_store(store) or _is_local_file_store(store)def _verify_signed_blob(@@ -215,7 +159,7 @@ def _verify_signed_blob(manifest, a *missing* hash is itself a signature error: the signed manifestand the blob set must agree, so a hash-less reference means writer drift ortampering rather than a reason to skip the check (which would otherwise let- a blob reach `pickle.loads` unverified — even in strict mode).+ a blob reach `pickle.loads` unverified — even under `strict`)."""if effective_signer is None:return@@ -664,11 +608,16 @@ class LazyLoader(BasePersistenceLoader):name: str,store: Store | None = None,signer: CacheSigner | None | _Unset = _SIGNER_UNSET,- trusted_signers: Iterable[str] | None = None,- mode: str = "verify",+ trusted_signers: Iterable[str] | None | _Unset = _TRUSTED_UNSET,+ verification: str | _Unset = _VERIFICATION_UNSET,) -> None:"""Create a LazyLoader.+ `signer`, `trusted_signers`, and `verification`, when left at their+ defaults, fall back to the session's config-derived policy+ (`SigningPolicy` on the cache state); an explicitly passed value always+ takes precedence.+Args:name: Cache namespace / directory name.store: Backing store. Defaults to `LazyStore` (file-based).@@ -677,32 +626,59 @@ class LazyLoader(BasePersistenceLoader):always trusts its own signer's key, so the common case — onesigner that both signs and verifies — needs nothing else.Pass `signer=None` to explicitly disable signing. When- omitted, a signer is resolved automatically: env vars- `MARIMO_CACHE_SIGNING_PRIVATE_KEY` /- `MARIMO_CACHE_SIGNING_PUBLIC_KEY` take precedence, then a- saved key in `marimo_state_dir()/cache_signing_key.pem`; if- neither exists a fresh key is generated and saved there (local- file stores only — shared/remote stores use only an explicitly- configured key, since an auto key is unverifiable elsewhere).- Resolves to `None` (unsigned) when the `cryptography`- package is not installed.+ omitted, the signer comes from the session's frozen+ `SigningPolicy` (resolved once, before any `.env` loads, from+ the config `private_key_path` or+ `MARIMO_CACHE_SIGNING_PRIVATE_KEY`); if none is configured, a+ machine-local key in `marimo_state_dir()/cache_signing_key.pem`+ is loaded or generated for local file stores only — shared/remote+ stores use only an explicitly configured key, since an auto key+ is unverifiable elsewhere. Resolves to `None` (unsigned) when+ the `cryptography` package is not installed.trusted_signers: Fingerprint strings (`"SHA256:<base64>"` from:func:`~marimo._save.signing.fingerprint`) that this loadertrusts, in addition to its own signer (always trusted for itsown writes). An entry verifies when it is signed directly by atrusted fingerprint's key. Padded or urlsafe fingerprints arenormalized to canonical form.- mode: Verification posture — `"off"`, `"verify"` (default), or- `"strict"`. `off` neither signs nor verifies (legacy- opt-out). `verify` signs on write and, on read, serves only- entries that verify against a trusted key; an unverifiable- entry misses and is recomputed (fail-safe). `strict` is like- `verify` but raises+ verification: Posture — `"off"`, `"on"` (default), or `"strict"`.+ `off` neither signs nor verifies (legacy opt-out). `on` signs+ on write and, on read, serves only entries that verify against+ a trusted key; an unverifiable entry misses and is recomputed+ (fail-safe). `strict` is like `on` but raises:class:`~marimo._save.signing.CacheSignatureError` on anunverifiable entry (fail-closed). `strict` also requires a- signing/verification capability at construction; `verify`- degrades to `off` (with a one-time warning) when none exists.+ signing/verification capability at construction. When no+ capability exists (no `cryptography`, or neither a signer nor+ `trusted_signers`), `on` keeps verifying — every read misses+ and every write is skipped, with a one-time warning — rather+ than serving unsigned data. Two stores are exempt: WebAssembly+ blobs served from the notebook's own origin, and, when+ `cryptography` is not installed at all, a local file store."""+ state = _cache_state()+ # An unset arg falls back to the session's config-derived policy (trust+ # anchored in user/env config only; see SigningPolicy). Explicit args+ # always win: `trusted_signers=set()` means "no trust", not "use policy".+ policy = state.signing_policy+ if isinstance(verification, _Unset):+ verification = (+ policy.verification+ if policy is not None+ else DEFAULT_VERIFICATION+ )+ else:+ verification = normalize_verification(verification, strict=True)+ if isinstance(trusted_signers, _Unset):+ trusted_signers = (+ policy.trusted_signers if policy is not None else None+ )+ if (+ isinstance(signer, _Unset)+ and policy is not None+ and policy.signer is not None+ ):+ signer = policy.signerif (not isinstance(signer, (_Unset, CacheSigner))and signer is not None@@ -711,12 +687,7 @@ class LazyLoader(BasePersistenceLoader):"signer must be a CacheSigner or None, got "f"{type(signer).__name__}.")- if mode not in _VALID_MODES:- raise ValueError(- f"Invalid cache signing mode {mode!r}; expected one of "- f"{', '.join(_VALID_MODES)}."- )- loaders = _cache_state().active_lazy_loaders+ loaders = state.active_lazy_loadersif store is None:# Reuse the store across recreations of a named loader (State GC,# partial reconstruction) so cached data survives.@@ -724,15 +695,15 @@ class LazyLoader(BasePersistenceLoader):store = prev.store if prev is not None else self._store_cls()super().__init__(name, "jsonl", store)self._pending: list[threading.Thread] = []- self._trusted_fingerprints = _normalize_fingerprints(trusted_signers)- self._mode = mode+ self._trusted_fingerprints = normalize_fingerprints(trusted_signers)+ self._verification = verificationself._degrade_warned = Falseself._write_skip_warned = False# Store the signer unresolved (the `signer` property auto-resolves an- # `_Unset` sentinel on first access). Deferring means mode='off' — which- # never signs or verifies — doesn't load or mint a machine-local key- # (avoiding a stray cache_signing_key.pem and read-only-state-dir- # warnings for a caller who opted out). verify/strict resolve it below.+ # `_Unset` sentinel on first access). Deferring means verification='off'+ # — which never signs or verifies — doesn't load or mint a machine-local+ # key (avoiding a stray cache_signing_key.pem and read-only-state-dir+ # warnings for a caller who opted out). on/strict resolve it below.self._signer: CacheSigner | _Unset | None = signer# Fail fast on an impossible strict configuration (no crypto, or no# signer and no trusted_signers). This reads `self.signer` for@@ -740,7 +711,7 @@ class LazyLoader(BasePersistenceLoader):# Register only afterwards so a rejected loader never lingers in the# active registry (which would otherwise be returned to a later# same-named lookup).- self._effective_mode()+ self._effective_verification()loaders[name] = selfdef _resolve_unset_signer(self) -> CacheSigner | None:@@ -753,103 +724,116 @@ class LazyLoader(BasePersistenceLoader):off signing of our own writes (which would otherwise leave the loaderread-only). Shared/remote stores don't auto-generate — an auto key isunverifiable by other machines — so they use only an explicitly- configured (env/config) key.+ configured key."""- return _get_default_signer(- auto_generate=_is_local_file_store(self.store)- )-- def _effective_mode(self) -> str:- """Resolve the verification mode after capability checks.-- `verify` degrades to `off` (with a one-time warning) when there is- nothing to verify with — no `cryptography` package, or neither a- signer nor `trusted_signers`. `strict` instead raises, so a- fail-closed loader never silently serves unverified data. Recomputed- on each load/save (not cached) so a reconfigure via `setattr` — which- applies kwargs in caller order — is always honored.+ auto_generate = _is_local_file_store(self.store)+ policy = _cache_state().signing_policy+ if policy is not None:+ # The env identity was frozen into policy.signer before any `.env`+ # loaded; here only the machine-local auto key remains, resolved at+ # the frozen path so a polluted env can't redirect it.+ return _get_machine_signer(+ policy.state_key_path, auto_generate=auto_generate+ )+ # No session policy (library use outside the kernel): no `.env` freeze+ # window exists, so full resolution including env is safe.+ return _get_default_signer(auto_generate=auto_generate)++ def _effective_verification(self) -> str:+ """Resolve the verification posture after capability checks.++ With nothing to verify with, `strict` raises. `on` keeps verifying —+ every read misses, every write is skipped — instead of serving unsigned+ bytes, except for the stores named at each branch below. Recomputed each+ call (not cached) so a `setattr` reconfigure that applies kwargs in+ caller order is always honored."""- if self._mode == "off":+ if self._verification == "off":return "off"from marimo._dependencies.dependencies import DependencyManagerif not DependencyManager.cryptography.has():- if self._mode == "strict":+ if self._verification == "strict":raise ValueError(- "mode='strict' cache signing requires the 'cryptography' "+ "verification='strict' cache signing requires the "+ "'cryptography' ""package, which is not installed.")- reason = "the 'cryptography' package is not installed"- # NB. A trusted-origin store degrades to 'off'; a shared/remote- # store keeps 'verify' (so every read misses and writes are skipped)- # rather than serving the unverified bytes signing protects.- if _is_trusted_origin_store(self.store):- self._warn_degraded(reason)- return "off"- self._warn_no_trust_anchor(reason)- return "verify"+ # NB. nothing in this install can verify, so keeping `on` turns+ # off the cache outright. Degrade for a store whose bytes are+ # already gated on control of the notebook code.+ return self._degrade_or_keep_on(+ "the 'cryptography' package is not installed",+ degradable=_is_trusted_origin_store(self.store),+ )if self.signer is None and not self._trusted_fingerprints:- if self._mode == "strict":+ if self._verification == "strict":raise ValueError(- "mode='strict' requires a signer or trusted_signers to "+ "verification='strict' requires a signer or trusted_signers to ""verify against, but neither is configured. Pass ""signer=CacheSigner.from_public_key_pem(...) or ""trusted_signers={fingerprint, ...}.")- # Same trusted-origin split as the no-cryptography branch.- if _is_trusted_origin_store(self.store):- self._warn_degraded(- "no signer or trusted_signers is configured"- )- return "off"- self._warn_no_trust_anchor("no signer or trusted_signers is set")- return "verify"- return self._mode+ # NB. signing works here, and a local file store auto-mints its+ # own key, so reaching this branch means the caller asked for+ # verification and passed `signer=None`. A local cache directory+ # travels with a cloned repository, so it keeps verifying.+ return self._degrade_or_keep_on(+ "no signer or trusted_signers is set",+ degradable=_is_wasm_same_origin_store(self.store),+ )+ return self._verification++ def _degrade_or_keep_on(self, reason: str, *, degradable: bool) -> str:+ if degradable:+ self._warn_degraded(reason)+ return "off"+ self._warn_no_trust_anchor(reason)+ return "on"def _warn_degraded(self, reason: str) -> None:if not self._degrade_warned:self._degrade_warned = TrueLOGGER.warning(- "LazyLoader mode=%r degraded to 'off' because %s; cache "+ "LazyLoader verification=%r degraded to 'off' because %s; cache ""entries are neither signed nor verified.",- self._mode,+ self._verification,reason,)def _warn_no_trust_anchor(self, reason: str) -> None:- """One-time warning: a shared/remote store has no way to verify.+ """One-time warning: the loader currently cannot verify anything.- Unlike the local degrade-to-off path, 'verify' is kept so unverified- bytes are never served — the consequence is that every read misses and- every write is skipped until the loader can verify again (`reason`- names what's missing).+ 'on' is kept (never downgraded to 'off') so unverified bytes are+ never served — the consequence is that every read misses and every+ write is skipped until the loader can verify again (`reason` names+ what's missing)."""if not self._degrade_warned:self._degrade_warned = TrueLOGGER.warning(- "LazyLoader mode=%r cannot verify cache entries for a "- "shared/remote store (%s): every read misses and writes are "- "skipped. Install 'cryptography' and set "- "MARIMO_CACHE_SIGNING_PRIVATE_KEY (to sign+verify) or "+ "LazyLoader verification=%r cannot verify cache entries (%s): every "+ "read misses and writes are skipped. Install 'cryptography' "+ "and set MARIMO_CACHE_SIGNING_PRIVATE_KEY (to sign+verify) or ""MARIMO_CACHE_SIGNING_PUBLIC_KEY (to verify only), or pass "- "trusted_signers=..., to use the cache; or mode='off' to cache "+ "trusted_signers=..., to use the cache; or verification='off' to cache ""without signing.",- self._mode,+ self._verification,reason,)# Property accessors so LoaderPartial.create_or_reconfigure() can update- # signer / trusted_signers / mode via setattr() using the constructor+ # signer / trusted_signers / verification via setattr() using the constructor# argument names.@propertydef signer(self) -> CacheSigner | None:- # Auto-resolve the _Unset sentinel on first access. In 'off' mode we+ # Auto-resolve the _Unset sentinel on first access. When 'off' we# never sign or verify, so don't load or mint a key — return None# without caching it, so a later reconfigure to verify/strict still# resolves (see __init__).if isinstance(self._signer, _Unset):- if self._mode == "off":+ if self._verification == "off":return Noneself._signer = self._resolve_unset_signer()return self._signer@@ -864,37 +848,32 @@ class LazyLoader(BasePersistenceLoader):f"{type(value).__name__}.")# NB. store the sentinel unresolved; the `signer` property defers- # resolution (and skips it in 'off' mode). Resolving here would- # mint/load a machine-local key when reconfiguring an off-mode loader.+ # resolution (and skips it when 'off'). Resolving here would+ # mint/load a machine-local key when reconfiguring an 'off' loader.self._signer = value@propertydef trusted_signers(self) -> frozenset[str]:# Frozen copy so mutating the return value can't bypass- # _normalize_fingerprints — assign to the property to change trust.+ # normalize_fingerprints — assign to the property to change trust.return frozenset(self._trusted_fingerprints)@trusted_signers.setterdef trusted_signers(self, value: Iterable[str] | None) -> None:- self._trusted_fingerprints = _normalize_fingerprints(value)+ self._trusted_fingerprints = normalize_fingerprints(value)@property- def mode(self) -> str:- return self._mode+ def verification(self) -> str:+ return self._verification- @mode.setter- def mode(self, value: str) -> None:+ @verification.setter+ def verification(self, value: str) -> None:# No capability fail-fast here: create_or_reconfigure() applies kwargs# via setattr in caller order, so a signer set in the same reconfigure- # may not be applied yet. _effective_mode() enforces the capability- # invariant at load/save time; __init__ enforces it for direct- # construction.- if value not in _VALID_MODES:- raise ValueError(- f"Invalid cache signing mode {value!r}; expected one of "- f"{', '.join(_VALID_MODES)}."- )- self._mode = value+ # may not be applied yet. _effective_verification() enforces the+ # capability invariant at load/save time; __init__ enforces it for+ # direct construction.+ self._verification = normalize_verification(value, strict=True)def flush(self) -> None:"""Wait for all pending background writes to complete."""@@ -937,10 +916,10 @@ class LazyLoader(BasePersistenceLoader):glbls: dict[str, Any] | None = None,) -> Cache | None:del glbls- # Resolve the effective mode before the try so an impossible strict+ # Resolve the effective posture before the try so an impossible strict# configuration surfaces as a ValueError rather than being swallowed# as a generic miss by the except clause below.- mode = self._effective_mode()+ verification = self._effective_verification()manifest_key = str(self.build_path(key))# Invalidated for re-execution this session.if manifest_key in _cache_state().stale_keys:@@ -961,7 +940,7 @@ class LazyLoader(BasePersistenceLoader):# here (bad signature, unsigned, or an untrusted key), so it is# never served unverified — see _resolve_effective_signer.self._on_restore_failure(key, blob)- if mode == "strict":+ if verification == "strict":raise# verify (fail-safe): degrade to cache miss rather than crashing;# the entry is recomputed rather than served unverified.@@ -1010,11 +989,11 @@ class LazyLoader(BasePersistenceLoader):return candidatesdef _resolve_effective_signer(- self, cache_data: CacheSchema, mode: str+ self, cache_data: CacheSchema, verification: str) -> CacheSigner | None:"""Verify the manifest and return the signer that validated it.- In `off` mode returns `None` without checking (data served as-is).+ In `off` returns `None` without checking (data served as-is).In `verify`/`strict` the entry must verify against a trusted key:this loader's own signer (implicitly trusted for its own writes), orthe manifest's declared signer key when its fingerprint is in@@ -1032,14 +1011,15 @@ class LazyLoader(BasePersistenceLoader):(`MARIMO_CACHE_SIGNING_*`) or add the writer's fingerprint to`trusted_signers`."""- if mode == "off":+ if verification == "off":return Nonesig = cache_data.meta.signatureif sig is None:raise CacheSignatureError(f"A cache entry is unsigned, but this loader verifies cache "- f"signatures (mode={self._mode!r}). The entry may predate "+ f"signatures (verification={self._verification!r}). The entry "+ "may predate "f"signing or was tampered with; it will be recomputed.\n"f"To recover, call cache_clear() on the cached function or "f"context manager."@@ -1062,15 +1042,16 @@ class LazyLoader(BasePersistenceLoader):)def restore_cache(self, key: HashKey, blob: bytes) -> Cache:- mode = self._effective_mode()+ verification = self._effective_verification()try:cache_data = msgspec.json.decode(blob, type=CacheSchema)except msgspec.DecodeError as e:# NB. under strict an undecodable/tampered manifest is a trust# anomaly (fail-closed), not the silent miss verify/off treat it as.- if mode == "strict":+ if verification == "strict":raise CacheSignatureError(- "A cache manifest could not be decoded (mode='strict'). "+ "A cache manifest could not be decoded "+ "(verification='strict'). ""The cache may be corrupted or was modified outside of ""marimo.\n""To recover, call cache_clear() on the cached function or "@@ -1082,14 +1063,15 @@ class LazyLoader(BasePersistenceLoader):# before any blob I/O or deserialization (otherwise it is only caught# in cache_attempt() after every blob has already been# pickle.loads()-ed). The hash is inside the signed bytes, so under a- # verifying mode a mismatch is a trust anomaly (a corrupt, misfiled, or+ # verifying a mismatch is a trust anomaly (a corrupt, misfiled, or# substituted manifest): strict surfaces it (fail-closed), while# verify/off treat it as a generic miss (recompute).if cache_data.hash != key.hash:- if mode == "strict":+ if verification == "strict":raise CacheSignatureError(f"A cache manifest's hash {cache_data.hash!r} does not "- f"match the requested key {key.hash!r} (mode='strict'). "+ f"match the requested key {key.hash!r} "+ "(verification='strict'). "f"The cache may be corrupted or was modified outside of "f"marimo.\n"f"To recover, call cache_clear() on the cached function or "@@ -1102,10 +1084,12 @@ class LazyLoader(BasePersistenceLoader):# Manifest verification (synchronous, before any blob I/O). Returns the# signer that validated the manifest (which enables blob-hash checking- # below), or None in 'off' mode. Raises CacheSignatureError when a+ # below), or None when 'off'. Raises CacheSignatureError when a# verify/strict loader cannot verify the entry — load_cache then misses# (verify) or re-raises (strict).- effective_signer = self._resolve_effective_signer(cache_data, mode)+ effective_signer = self._resolve_effective_signer(+ cache_data, verification+ )base = Path(self.name) / cache_data.hashblob_hash_map = cache_data.meta.blob_hashes # {} for unsigned entries@@ -1270,7 +1254,7 @@ class LazyLoader(BasePersistenceLoader):results: queue.Queue[tuple[str, Any]] = queue.Queue()# Threads append here on a signed-hash mismatch. list.append is# thread-safe under the GIL. Surfaced as the first error after join so- # a strict-mode loader raises rather than degrading to a+ # a strict loader raises rather than degrading to a# generic cache miss.errors: list[CacheSignatureError] = []@@ -1333,8 +1317,8 @@ class LazyLoader(BasePersistenceLoader):t.join()# Precedence: a hash mismatch or a genuinely-missing blob under a# verified manifest is a trust anomaly (strict raises); an- # authentic-but-unreadable blob is a plain miss (recompute) in every- # mode, matching the deserializers' documented recompute fallback.+ # authentic-but-unreadable blob is a plain miss (recompute) under every+ # posture, matching the deserializers' documented recompute fallback.if errors:raise errors[0]if missing:@@ -1404,24 +1388,26 @@ class LazyLoader(BasePersistenceLoader):# Use property to normalise any stale _Unset sentinel.signer = self.signer- mode = self._effective_mode()+ verification = self._effective_verification()# Sign only when verifying: 'off' writes unsigned (legacy), and a# signer without a private key can't sign at all.- signing = mode != "off" and signer is not None and signer.can_sign+ signing = (+ verification != "off" and signer is not None and signer.can_sign+ )- if mode != "off" and not signing:+ if verification != "off" and not signing:# NB. skip rather than write: an unsigned entry only pollutes the# store with data every verifying reader rejects on load.if not self._write_skip_warned:self._write_skip_warned = TrueLOGGER.warning(- "LazyLoader mode=%r cannot sign cache entries (no private "+ "LazyLoader verification=%r cannot sign cache entries (no private ""signing key is available), so this write was skipped — an ""unsigned entry would be rejected on load. Install ""'cryptography' and set MARIMO_CACHE_SIGNING_PRIVATE_KEY ""(or pass a private-key signer) to write signed entries, or "- "use mode='off' to write unsigned.",- mode,+ "use verification='off' to write unsigned.",+ verification,)return Falsediff --git a/marimo/_save/signing.py b/marimo/_save/signing.pyindex bb7f961229..cf80853367 100644--- a/marimo/_save/signing.py+++ b/marimo/_save/signing.py@@ -10,7 +10,19 @@ from __future__ import annotationsimport base64import hashlib-from typing import Any+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from collections.abc import Iterable++# Verification posture, shared by the config resolver (`signing_policy`) and+# the loader (`loaders.lazy`). `off`: no signing or verification (legacy+# opt-out). `on` (default): sign on write, and on read serve only entries that+# verify against a trusted key — unverifiable entries miss and recompute+# (fail-safe). `strict`: like `on`, but an unverifiable entry raises+# (fail-closed).+VALID_VERIFICATIONS = ("off", "on", "strict")+DEFAULT_VERIFICATION = "on"class CacheSignatureError(Exception):@@ -27,6 +39,33 @@ def _sha256hex(data: bytes) -> str:return hashlib.sha256(data).hexdigest()+def normalize_verification(raw: Any, *, strict: bool = False) -> str:+ """Validate a verification posture.++ With `strict=False` (config files) an unrecognized value warns and degrades+ to the default rather than breaking the session; with `strict=True` (a+ caller-supplied kwarg) it raises. The default is fail-safe — unverifiable+ entries recompute — so the degrade path never widens what gets+ deserialized.+ """+ if isinstance(raw, str) and raw in VALID_VERIFICATIONS:+ return raw+ expected = ", ".join(VALID_VERIFICATIONS)+ if strict:+ raise ValueError(+ f"Invalid cache verification {raw!r}; expected one of {expected}."+ )+ from marimo import _loggers++ _loggers.marimo_logger().warning(+ "Invalid cache verification %r; expected one of %s. Falling back to %r.",+ raw,+ expected,+ DEFAULT_VERIFICATION,+ )+ return DEFAULT_VERIFICATION++class CacheSigner:"""Ed25519 signing and verification for LazyLoader cache manifests.@@ -46,7 +85,7 @@ class CacheSigner:)# Consumer — verifies signed entries; unverifiable entries miss- # (recompute) rather than being served (fail-safe, mode="verify")+ # (recompute) rather than being served (fail-safe, verification="on")reader = LazyLoader.partial(signer=CacheSigner.from_public_key_pem(public_pem))@@ -54,7 +93,7 @@ class CacheSigner:# Consumer — strict: raises on any unsigned/unverifiable entryreader_strict = LazyLoader.partial(signer=CacheSigner.from_public_key_pem(public_pem),- mode="strict",+ verification="strict",)Keys can also be loaded from environment variables::@@ -279,6 +318,66 @@ def fingerprint(public_key_pem: str) -> str:).decode().rstrip("=")+_FP_URLSAFE_TO_STD = str.maketrans("-_", "+/")+++def normalize_fingerprint(fp: str) -> str:+ """Validate and canonicalize one `"SHA256:<base64>"` fingerprint.++ Accepts standard or urlsafe base64, padded or unpadded, and returns the+ canonical form produced by :func:`fingerprint` (standard base64, no+ padding). Raising on a malformed digest here turns a fat-fingered+ fingerprint into a configuration-time error rather than a permanent, silent+ cache miss (the digest would validate on prefix alone but never match a+ real key).+ """+ import binascii++ if not isinstance(fp, str) or not fp.startswith("SHA256:"):+ raise ValueError(+ f"Invalid trusted_signers fingerprint {fp!r}; expected "+ "'SHA256:<base64>' as produced by "+ "marimo._save.signing.fingerprint()."+ )+ body = fp[len("SHA256:") :].translate(_FP_URLSAFE_TO_STD).rstrip("=")+ try:+ raw = base64.b64decode(body + "=" * (-len(body) % 4), validate=True)+ except (binascii.Error, ValueError) as e:+ raise ValueError(+ f"Invalid trusted_signers fingerprint {fp!r}; the digest is "+ "not valid base64."+ ) from e+ if len(raw) != 32:+ raise ValueError(+ f"Invalid trusted_signers fingerprint {fp!r}; expected a "+ f"SHA-256 (32-byte) digest, got {len(raw)} byte(s)."+ )+ # Re-encode from the decoded bytes rather than returning `body` verbatim.+ # base64 of 32 bytes has 2 unused ("slack") bits in the final character, so+ # several distinct final characters decode to the same digest. Returning the+ # raw text lets such a variant validate here yet never match the canonical+ # form, which is a permanent silent miss.+ return "SHA256:" + base64.b64encode(raw).decode("ascii").rstrip("=")+++def normalize_fingerprints(value: Iterable[str] | None) -> set[str]:+ """Validate and collect `trusted_signers` fingerprint strings.++ Rejects a bare `str` (which would otherwise iterate into single+ characters — a silent-miss footgun) and canonicalizes each entry via+ :func:`normalize_fingerprint` so a padded or urlsafe paste still matches+ :func:`fingerprint` output.+ """+ if value is None:+ return set()+ if isinstance(value, str):+ raise TypeError(+ "trusted_signers must be an iterable of fingerprint strings, not "+ "a single str. Wrap it in a set/list: trusted_signers={fp}."+ )+ return {normalize_fingerprint(fp) for fp in value}++def generate_keypair() -> tuple[str, str]:"""Generate an Ed25519 key pair for cache signing.@@ -300,7 +399,7 @@ def generate_keypair() -> tuple[str, str]:def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:- """Resolve the default cache signer for this session.+ """Resolve the default cache signer for a session with no frozen policy.Resolution order:@@ -309,16 +408,9 @@ def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:3. `marimo_state_dir() / "cache_signing_key.pem"` → load saved private key4. Neither set → generate a fresh Ed25519 key, save it, return signer- When *auto_generate* is `False`, steps 3 and 4 are skipped — only- explicitly configured keys (env vars) are used. This is the right- choice for shared stores where an auto-generated machine-local key- would be unverifiable by other machines.-- Returns `None` when the `cryptography` package is not installed so- that unsigned caching degrades gracefully.+ Reads the environment live, so it is only for contexts that have no+ frozen policy. Returns `None` when `cryptography` is not installed."""- import logging-from marimo._dependencies.dependencies import DependencyManagerif not DependencyManager.cryptography.has():@@ -329,23 +421,47 @@ def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:if signer is not None:return signer- if not auto_generate:- return None+ return _get_machine_signer(auto_generate=auto_generate)+- # 3 & 4: key file in the marimo state directory+def _get_machine_signer(+ key_path: str | None = None, auto_generate: bool = True+) -> CacheSigner | None:+ """Load (or, if *auto_generate*, mint) the machine-local signing key.++ `key_path` defaults to `marimo_state_dir() / "cache_signing_key.pem"`. A+ caller passes an explicit path to avoid re-resolving the state directory+ from a possibly-polluted live environment. Does not read signing env vars.+ `auto_generate=False` skips minting (shared/remote stores, whose auto key+ is unverifiable elsewhere). Returns `None` when `cryptography` is+ unavailable.+ """+ import loggingimport osimport stat+ from pathlib import Path++ from marimo._dependencies.dependencies import DependencyManager++ if not DependencyManager.cryptography.has():+ return None++ if not auto_generate:+ return None- from marimo._utils.xdg import marimo_state_dir+ if key_path is None:+ from marimo._utils.xdg import marimo_state_dir- key_path = marimo_state_dir() / "cache_signing_key.pem"- if key_path.exists():+ key_file = marimo_state_dir() / "cache_signing_key.pem"+ else:+ key_file = Path(key_path)+ if key_file.exists():try:- signer = CacheSigner.from_private_key_pem(key_path.read_text())+ signer = CacheSigner.from_private_key_pem(key_file.read_text())# Best-effort: re-tighten perms in case the key was created before# we chmod'd it (or by another tool) — it's a private signing key.try:- os.chmod(key_path, stat.S_IRUSR | stat.S_IWUSR)+ os.chmod(key_file, stat.S_IRUSR | stat.S_IWUSR)except OSError:passreturn signer@@ -353,7 +469,7 @@ def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:logging.getLogger("marimo").warning("Failed to load cache signing key from %s; ""generating a new one.",- key_path,+ key_file,)# Auto-generate and persist atomically (write to temp, rename).@@ -365,9 +481,9 @@ def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:try:private_pem, _ = generate_keypair()- key_path.parent.mkdir(parents=True, exist_ok=True)+ key_file.parent.mkdir(parents=True, exist_ok=True)fd, tmp = tempfile.mkstemp(- dir=key_path.parent, prefix=".cache_key_", suffix=".tmp"+ dir=key_file.parent, prefix=".cache_key_", suffix=".tmp")closed = Falsetry:@@ -375,7 +491,7 @@ def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:os.close(fd)closed = Trueos.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR)- os.replace(tmp, str(key_path))+ os.replace(tmp, str(key_file))except BaseException:if not closed:os.close(fd)@@ -385,18 +501,18 @@ def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:passraiselogging.getLogger("marimo").info(- "Generated cache signing key: %s", key_path+ "Generated cache signing key: %s", key_file)# Adopt whatever key won the rename (see note above); fall back to the# in-memory key if the file is unreadable for any reason.try:- return CacheSigner.from_private_key_pem(key_path.read_text())+ return CacheSigner.from_private_key_pem(key_file.read_text())except Exception:return CacheSigner.from_private_key_pem(private_pem)except Exception:logging.getLogger("marimo").warning("Could not persist cache signing key to %s; ""cache entries will be unsigned for this session.",- key_path,+ key_file,)return Nonediff --git a/marimo/_save/signing_policy.py b/marimo/_save/signing_policy.pynew file mode 100644index 0000000000..31dde896ab--- /dev/null+++ b/marimo/_save/signing_policy.py@@ -0,0 +1,242 @@+# Copyright 2026 Marimo. All rights reserved.+"""Resolve marimo config into a frozen cache-signing policy.++Trust is anchored from the merged config's user/env layers and the inherited+environment before any configured `.env` is loaded. Loaders read only the+frozen result. See `SigningPolicy`.+"""++from __future__ import annotations++import os+import stat+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING, Any++from marimo import _loggers+from marimo._save.signing import (+ DEFAULT_VERIFICATION,+ CacheSigner,+ fingerprint,+ normalize_fingerprint,+ normalize_verification,+)++if TYPE_CHECKING:+ from marimo._config.config import MarimoConfig++LOGGER = _loggers.marimo_logger()++# A Privacy-Enhanced Mail (PEM) Ed25519 private key is well under 1 KiB. Cap+# the read so a `private_key_path` aimed at a huge or streaming file cannot hang+# or exhaust memory.+_MAX_KEY_FILE_BYTES = 64 * 1024++_PRIVATE_KEY_ENV = "MARIMO_CACHE_SIGNING_PRIVATE_KEY"+_PUBLIC_KEY_ENV = "MARIMO_CACHE_SIGNING_PUBLIC_KEY"+++@dataclass(frozen=True)+class SigningPolicy:+ """The cache-signing configuration resolved for one session.++ Frozen: trust must not change between the moment it is checked and the+ eventual `pickle.loads`. `signer` and `trusted_signers` resolve once at+ construction, reading the environment as inherited, so loading a `.env`+ afterwards cannot introduce a signing identity.+ """++ verification: str = DEFAULT_VERIFICATION+ trusted_signers: frozenset[str] = field(default_factory=frozenset)+ # NB. compare=False: CacheSigner isn't a value type. The policy's identity+ # is its (verification, trust, key-path).+ signer: CacheSigner | None = field(default=None, compare=False)+ state_key_path: str | None = None++ @classmethod+ def from_config(cls, config: MarimoConfig) -> SigningPolicy:+ signing = config.get("signing") or {}+ cache = config.get("cache") or {}++ verification = normalize_verification(+ cache.get("verification", DEFAULT_VERIFICATION)+ )++ trusted = _resolve_trusted_signers(signing.get("trusted_signers"))+ # A public key in the inherited environment is a trusted *verifier*, not+ # this loader's own signing identity — record it as a trusted+ # fingerprint (so it must be named to be trusted) rather than an+ # implicitly-trusted own-signer that would auto-trust arbitrary writes.+ env_public = _env_public_fingerprint()+ if env_public is not None:+ trusted.add(env_public)++ signer = _resolve_write_signer(signing.get("private_key_path") or None)+ return cls(+ verification=verification,+ trusted_signers=frozenset(trusted),+ signer=signer,+ state_key_path=_default_state_key_path(),+ )+++def _env_public_fingerprint() -> str | None:+ """Fingerprint of `MARIMO_CACHE_SIGNING_PUBLIC_KEY`, read from inherited env."""+ pem = os.environ.get(_PUBLIC_KEY_ENV)+ if not pem:+ return None+ try:+ return fingerprint(pem)+ except Exception as e:+ LOGGER.warning("Ignoring invalid %s: %s", _PUBLIC_KEY_ENV, e)+ return None+++def _resolve_write_signer(private_key_path: str | None) -> CacheSigner | None:+ """Resolve the write identity from the config key path or the env key.++ Returns `None` when neither resolves or `cryptography` is unavailable.+ """+ from marimo._dependencies.dependencies import DependencyManager++ if not DependencyManager.cryptography.has():+ return None+ if private_key_path:+ signer = _load_signer_from_path(private_key_path)+ if signer is not None:+ return signer+ pem = os.environ.get(_PRIVATE_KEY_ENV)+ if pem:+ try:+ return CacheSigner.from_private_key_pem(pem)+ except Exception as e:+ LOGGER.warning("Ignoring invalid %s: %s", _PRIVATE_KEY_ENV, e)+ return None+++def _default_state_key_path() -> str:+ from marimo._utils.xdg import marimo_state_dir++ return str(marimo_state_dir() / "cache_signing_key.pem")+++def _load_signer_from_path(raw_path: Any) -> CacheSigner | None:+ """Load a private-key signer from an absolute path, else `None`.++ Any failure (not a string, missing, oversized, malformed/encrypted or+ unsupported PEM) degrades to `None` uniformly rather than raising: a bad+ key path must not stop the session from starting.+ """+ if not isinstance(raw_path, str):+ LOGGER.warning(+ "signing.private_key_path must be a string, got %s; ignoring "+ "and falling back to an auto-resolved signing identity.",+ type(raw_path).__name__,+ )+ return None+ expanded = Path(raw_path).expanduser()+ # NB. reject relative paths: they resolve against the live CWD, where a+ # project can drop in a substitute key.+ if not expanded.is_absolute():+ LOGGER.warning(+ "signing.private_key_path %r must be an absolute path; ignoring "+ "and falling back to an auto-resolved signing identity.",+ raw_path,+ )+ return None+ try:+ return CacheSigner.from_private_key_pem(_read_key_file(str(expanded)))+ except Exception as e:+ LOGGER.warning(+ "Could not load signing.private_key_path %r (%s); falling back "+ "to an auto-resolved signing identity.",+ raw_path,+ e,+ )+ return None+++def _read_key_file(path: str) -> str:+ """Read a small key file through a single fd, without following symlinks."""+ flags = os.O_RDONLY+ # O_NOFOLLOW is POSIX. It is absent on some platforms, Windows included.+ flags |= getattr(os, "O_NOFOLLOW", 0)+ fd = os.open(path, flags)+ try:+ st = os.fstat(fd)+ if not stat.S_ISREG(st.st_mode):+ raise OSError("not a regular file")+ if st.st_size > _MAX_KEY_FILE_BYTES:+ raise OSError("file too large to be a PEM key")+ data = os.read(fd, _MAX_KEY_FILE_BYTES + 1)+ # NB. the cap is enforced on the bytes actually read, not on the stat+ # above: the file can grow between the two.+ if len(data) > _MAX_KEY_FILE_BYTES:+ raise OSError("file too large to be a PEM key")+ return data.decode()+ finally:+ os.close(fd)+++def _resolve_trusted_signers(raw: Any) -> set[str]:+ """Normalize a config `trusted_signers` mapping into canonical fingerprints.++ A malformed fingerprint is dropped with a warning rather than raised, so one+ bad entry in a configuration file cannot break the whole session. Two raw+ keys that canonicalize to the same fingerprint warn rather than collapse+ silently.+ """+ if raw is None:+ return set()+ if not isinstance(raw, dict):+ LOGGER.warning(+ "signing.trusted_signers must be a table of "+ "{fingerprint = label}; ignoring %r.",+ type(raw).__name__,+ )+ return set()++ resolved: set[str] = set()+ for fp in raw:+ try:+ canonical = normalize_fingerprint(fp)+ except (ValueError, TypeError):+ # NB. the entry is deliberately kept out of the message. A+ # fingerprint gives the reader nothing to act on, and this branch+ # runs when parsing failed, so what the value holds is unknown.+ LOGGER.warning(+ "Ignoring an invalid signing.trusted_signers entry. Expected "+ "'SHA256:<base64>' as produced by "+ "marimo._save.signing.fingerprint()."+ )+ continue+ if canonical in resolved:+ LOGGER.warning(+ "Duplicate signing.trusted_signers fingerprint after "+ "normalization (%r); keeping one entry.",+ canonical,+ )+ resolved.add(canonical)+ return resolved+++def get_signing_policy(+ current_path: str | None = None,+ *,+ config: MarimoConfig | None = None,+) -> SigningPolicy:+ """Resolve the effective cache-signing policy for the current session.++ Pass `config` — the kernel's effective, already-merged, unmasked config — to+ honor trust and verification provided by the session or by a WebAssembly+ export. When it is omitted, the on-disk user and environment config is read+ with `hide_secrets=False`, so that the real `private_key_path` is visible.+ """+ if config is None:+ from marimo._config.manager import get_default_config_manager++ config = get_default_config_manager(+ current_path=current_path+ ).get_config(hide_secrets=False)+ return SigningPolicy.from_config(config)diff --git a/tests/_save/loaders/test_lazy_signing.py b/tests/_save/loaders/test_lazy_signing.pyindex 9b75ebcd50..b0dfbe29fc 100644--- a/tests/_save/loaders/test_lazy_signing.py+++ b/tests/_save/loaders/test_lazy_signing.py@@ -90,20 +90,20 @@ class _FileStoreLoaderTest:class TestSignedRoundTrip(_FileStoreLoaderTest):- def test_signer_and_mode_settable_via_setattr(self) -> None:+ def test_signer_and_verification_settable_via_setattr(self) -> None:"""Reconfiguring via setattr (as LoaderPartial.create_or_reconfigure- does) works for signer and mode."""+ does) works for signer and verification."""signer, verifier = _keypair()- # Start in off mode with no signer, then reconfigure to a signing- # loader — mirroring how create_or_reconfigure applies kwargs.- loader = self._loader(signer=None, mode="off")+ # Start with verification off and no signer, then reconfigure to a+ # signing loader — mirroring how create_or_reconfigure applies kwargs.+ loader = self._loader(signer=None, verification="off")assert loader.signer is None- assert loader.mode == "off"+ assert loader.verification == "off"loader.signer = signer- loader.mode = "verify"+ loader.verification = "on"assert loader._signer is signer- assert loader._mode == "verify"+ assert loader._verification == "on"# Full round-trip with the reconfigured signercache = _simple_cache(hash_val="reconfig_hash", v=99)@@ -128,7 +128,7 @@ class TestSignedRoundTrip(_FileStoreLoaderTest):from marimo._save.loaders.lazy import _SIGNER_UNSETloader = LazyLoader(- "ns", store=MockStore(), signer=None, mode="verify"+ "ns", store=MockStore(), signer=None, verification="on")with mock.patch("marimo._save.loaders.lazy._get_default_signer"@@ -241,7 +241,7 @@ class TestUnsignedEntries(_FileStoreLoaderTest):def _write_unsigned(self, hash_val: str = "unsigned_hash") -> None:"""Write a valid but unsigned cache entry via an off-mode loader(off is the only mode that writes unsigned)."""- loader = self._loader(signer=None, mode="off")+ loader = self._loader(signer=None, verification="off")cache = _simple_cache(hash_val=hash_val, z=55)assert loader.save_cache(cache)loader.flush()@@ -249,7 +249,7 @@ class TestUnsignedEntries(_FileStoreLoaderTest):def test_unsigned_served_in_off_mode(self) -> None:"""off mode neither signs nor verifies: unsigned entries load fine."""self._write_unsigned()- loader = self._loader(signer=None, mode="off")+ loader = self._loader(signer=None, verification="off")loaded = loader.load_cache(key("unsigned_hash"))assert loaded is not Noneassert loaded.defs["z"] == 55@@ -259,14 +259,14 @@ class TestUnsignedEntries(_FileStoreLoaderTest):misses (fail-safe) rather than being served."""self._write_unsigned()_, verifier = _keypair()- loader = self._loader(signer=verifier) # mode="verify" default+ loader = self._loader(signer=verifier) # verification="on" defaultassert loader.load_cache(key("unsigned_hash")) is Nonedef test_unsigned_rejected_in_strict_mode(self) -> None:"""strict mode: unsigned entries raise CacheSignatureError."""self._write_unsigned()_, verifier = _keypair()- loader = self._loader(signer=verifier, mode="strict")+ loader = self._loader(signer=verifier, verification="strict")with pytest.raises(CacheSignatureError, match="unsigned"):loader.load_cache(key("unsigned_hash"))@@ -317,9 +317,9 @@ class TestTampering(_FileStoreLoaderTest):# Locate and corrupt the manifest filemanifest_key = str(- LazyLoader("test", store=self.store, mode="off").build_path(- key("manip_manifest")- )+ LazyLoader(+ "test", store=self.store, verification="off"+ ).build_path(key("manip_manifest")))raw = self.store.get(manifest_key)assert raw is not None@@ -331,7 +331,7 @@ class TestTampering(_FileStoreLoaderTest):)self.store.put(manifest_key, tampered)- reader = self._read_loader(signer, mode="strict")+ reader = self._read_loader(signer, verification="strict")with pytest.raises(CacheSignatureError):reader.load_cache(key("manip_manifest"))@@ -348,7 +348,7 @@ class TestTampering(_FileStoreLoaderTest):evil_bytes = pickle.dumps({"injected": True})blobs[0].write_bytes(evil_bytes)- reader = self._read_loader(signer, mode="strict")+ reader = self._read_loader(signer, verification="strict")with pytest.raises(CacheSignatureError, match="checksum"):reader.load_cache(key("blob_tamper"))@@ -357,9 +357,9 @@ class TestTampering(_FileStoreLoaderTest):signer = self._write_signed(hash_val="sig_swallow")manifest_key = str(- LazyLoader("test", store=self.store, mode="off").build_path(- key("sig_swallow")- )+ LazyLoader(+ "test", store=self.store, verification="off"+ ).build_path(key("sig_swallow")))raw = self.store.get(manifest_key)assert raw is not None@@ -370,7 +370,7 @@ class TestTampering(_FileStoreLoaderTest):)self.store.put(manifest_key, tampered)- reader = self._read_loader(signer, mode="strict")+ reader = self._read_loader(signer, verification="strict")# Must raise, not return Nonewith pytest.raises(CacheSignatureError):reader.load_cache(key("sig_swallow"))@@ -380,9 +380,9 @@ class TestTampering(_FileStoreLoaderTest):signer = self._write_signed(hash_val="verify_tamper")manifest_key = str(- LazyLoader("test", store=self.store, mode="off").build_path(- key("verify_tamper")- )+ LazyLoader(+ "test", store=self.store, verification="off"+ ).build_path(key("verify_tamper")))raw = self.store.get(manifest_key)assert raw is not None@@ -408,7 +408,7 @@ class TestTampering(_FileStoreLoaderTest):writer.flush()reader = LazyLoader(- "test", store=self.store, signer=verifier_b, mode="strict"+ "test", store=self.store, signer=verifier_b, verification="strict")with pytest.raises(CacheSignatureError):reader.load_cache(key("wrong_key"))@@ -438,9 +438,9 @@ class TestTampering(_FileStoreLoaderTest):signer = self._write_signed(hash_val="missing_hash", secret={"k": "v"})manifest_key = str(- LazyLoader("test", store=self.store, mode="off").build_path(- key("missing_hash")- )+ LazyLoader(+ "test", store=self.store, verification="off"+ ).build_path(key("missing_hash")))raw = self.store.get(manifest_key)assert raw is not None@@ -464,7 +464,7 @@ class TestTampering(_FileStoreLoaderTest):)self.store.put(manifest_key, resigned)- reader = self._read_loader(signer, mode="strict")+ reader = self._read_loader(signer, verification="strict")with pytest.raises(CacheSignatureError, match="integrity hash"):reader.load_cache(key("missing_hash"))@@ -472,7 +472,7 @@ class TestTampering(_FileStoreLoaderTest):"""A manifest whose internal hash disagrees with its store path is acorrupt/misfiled entry: miss before fetching any blob (otherwise themismatch is only caught after every blob is pickle.loads()-ed)."""- loader = LazyLoader("test", store=self.store, mode="off")+ loader = LazyLoader("test", store=self.store, verification="off")ref = (Path("test") / "wrong" / "v.pickle").as_posix()manifest = msgspec.json.encode(CacheSchema(@@ -507,7 +507,9 @@ class TestTampering(_FileStoreLoaderTest):class TestBlobHashesInManifest(_FileStoreLoaderTest):def test_unsigned_manifest_has_empty_blob_hashes(self) -> None:- loader = LazyLoader("test", store=self.store, signer=None, mode="off")+ loader = LazyLoader(+ "test", store=self.store, signer=None, verification="off"+ )cache = _simple_cache(hash_val="no_hashes", x=1)loader.save_cache(cache)loader.flush()@@ -615,19 +617,21 @@ class TestSignableBytesStability:# ----------------------------------------------------------------------------class TestModeAndCapabilityValidation(_FileStoreLoaderTest):+class TestVerificationAndCapabilityValidation(_FileStoreLoaderTest):def test_strict_with_no_capability_raises(self) -> None:"""strict + signer=None + no trusted_signers → ValueError at init."""with pytest.raises(ValueError, match="strict"):- LazyLoader("test", store=self.store, signer=None, mode="strict")+ LazyLoader(+ "test", store=self.store, signer=None, verification="strict"+ )def test_strict_with_signer_is_fine(self) -> None:_, verifier = generate_keypair()signer = CacheSigner.from_public_key_pem(verifier)loader = LazyLoader(- "test", store=self.store, signer=signer, mode="strict"+ "test", store=self.store, signer=signer, verification="strict")- assert loader.mode == "strict"+ assert loader.verification == "strict"def test_strict_with_trusted_signers_only_is_fine(self) -> None:_, root_pub = generate_keypair()@@ -636,26 +640,28 @@ class TestModeAndCapabilityValidation(_FileStoreLoaderTest):store=self.store,signer=None,trusted_signers={fingerprint(root_pub)},- mode="strict",+ verification="strict",)- assert loader.mode == "strict"+ assert loader.verification == "strict"- def test_verify_with_no_capability_degrades_to_off(self) -> None:- """verify + nothing to verify with → degrade to off (no raise); an- unsigned entry is then served."""+ def test_on_with_no_capability_misses_never_serves(self) -> None:+ """verify + nothing to verify with (local file store) → keep verifying+ (never degrade to off): the unsigned entry misses, it is not served."""# Write an unsigned entry.- w = LazyLoader("test", store=self.store, signer=None, mode="off")+ w = LazyLoader(+ "test", store=self.store, signer=None, verification="off"+ )w.save_cache(_simple_cache(hash_val="degrade", z=3))w.flush()- # Reader with verify but no signer and no trusted_signers degrades.+ # Reader with verify but no signer and no trusted_signers must NOT+ # degrade to off on a local file store — that was the fail-open hole.reader = LazyLoader("test", store=self.store, signer=None)- loaded = reader.load_cache(key("degrade"))- assert loaded is not None- assert loaded.defs["z"] == 3+ assert reader._effective_verification() == "on"+ assert reader.load_cache(key("degrade")) is None- def test_invalid_mode_raises(self) -> None:- with pytest.raises(ValueError, match="Invalid cache signing mode"):- LazyLoader("test", store=self.store, mode="paranoid")+ def test_invalid_verification_raises(self) -> None:+ with pytest.raises(ValueError, match="Invalid cache verification"):+ LazyLoader("test", store=self.store, verification="paranoid")def test_bare_string_trusted_signers_raises(self) -> None:"""A bare str would iterate into single characters — rejected."""@@ -686,16 +692,25 @@ class TestModeAndCapabilityValidation(_FileStoreLoaderTest):):with pytest.raises(ValueError, match="cryptography"):LazyLoader(- "test", store=self.store, signer=signer, mode="strict"+ "test",+ store=self.store,+ signer=signer,+ verification="strict",)- def test_no_cryptography_verify_degrades_to_off(self) -> None:- """verify degrades to off (serves unsigned) when cryptography is- unavailable — unsigned caching still works without the package."""+ def test_no_cryptography_local_store_degrades_to_off(self) -> None:+ """Without cryptography, a local file store degrades to `off`.++ Nothing in the install can verify, so keeping `on` turns the cache off+ for every plain `pip install marimo`. A local cache directory is already+ gated on filesystem access to the notebook, so it is served.+ """from unittest import mock# Write an unsigned entry (off mode).- w = LazyLoader("test", store=self.store, signer=None, mode="off")+ w = LazyLoader(+ "test", store=self.store, signer=None, verification="off"+ )w.save_cache(_simple_cache(hash_val="nocrypto", z=8))w.flush()@@ -706,10 +721,10 @@ class TestModeAndCapabilityValidation(_FileStoreLoaderTest):return_value=False,):reader = LazyLoader("test", store=self.store, signer=signer)- assert reader._effective_mode() == "off"- loaded = reader.load_cache(key("nocrypto"))- assert loaded is not None- assert loaded.defs["z"] == 8+ assert reader._effective_verification() == "off"+ cache = reader.load_cache(key("nocrypto"))+ assert cache is not None+ assert cache.defs["z"] == 8# ---------------------------------------------------------------------------@@ -740,38 +755,40 @@ class TestReviewFixes(_FileStoreLoaderTest):assert loaded is not Noneassert loaded.defs["k"] == 1- def test_remote_store_verify_does_not_degrade_to_off(self) -> None:+ def test_remote_store_on_does_not_degrade_to_off(self) -> None:"""On a shared/remote store, verify with no signer/trusted must NOTdegrade to off (which would serve unverified bytes from exactly thebackend signing protects); it stays verify, so an unsigned entrymisses."""store = MockStore()- w = LazyLoader("ns", store=store, signer=None, mode="off")+ w = LazyLoader("ns", store=store, signer=None, verification="off")w.save_cache(_simple_cache(hash_val="remote_unsigned", z=3))w.flush()reader = LazyLoader("ns", store=store, signer=None)- assert reader._effective_mode() == "verify"+ assert reader._effective_verification() == "on"assert reader.load_cache(key("remote_unsigned")) is None- def test_local_store_verify_still_degrades_to_off(self) -> None:- """A local file store keeps the benign degrade-to-off when there is- nothing to verify with (low-threat, single-machine)."""- w = LazyLoader("test", store=self.store, signer=None, mode="off")+ def test_local_store_on_never_serves_unsigned(self) -> None:+ """A local file store must NOT degrade verify→off: a cloned repo's+ `__marimo__/cache` is attacker-controlled bytes that merely sit on local+ disk, so an unsigned entry misses (recomputes) rather than being served.+ """+ w = LazyLoader(+ "test", store=self.store, signer=None, verification="off"+ )w.save_cache(_simple_cache(hash_val="local_unsigned", z=4))w.flush()reader = LazyLoader("test", store=self.store, signer=None)- assert reader._effective_mode() == "off"- loaded = reader.load_cache(key("local_unsigned"))- assert loaded is not None- assert loaded.defs["z"] == 4+ assert reader._effective_verification() == "on"+ assert reader.load_cache(key("local_unsigned")) is Nonedef test_strict_hash_mismatch_raises(self) -> None:"""Under strict, a manifest whose internal hash disagrees with itsstore path is a trust anomaly and must raise (fail-closed), not miss."""signer, _ = _keypair()loader = LazyLoader(- "test", store=self.store, signer=signer, mode="strict"+ "test", store=self.store, signer=signer, verification="strict")manifest = msgspec.json.encode(CacheSchema(@@ -816,27 +833,27 @@ class TestReviewFixes(_FileStoreLoaderTest):def test_trusted_signers_property_is_frozen_copy(self) -> None:"""The property returns a frozenset copy so mutating it cannot bypass- _normalize_fingerprints."""+ normalize_fingerprints."""_, pub = generate_keypair()loader = LazyLoader("test",store=self.store,signer=None,trusted_signers={fingerprint(pub)},- mode="off",+ verification="off",)ts = loader.trusted_signersassert isinstance(ts, frozenset)assert not hasattr(ts, "add")- def test_no_crypto_remote_store_stays_verify(self) -> None:+ def test_no_crypto_remote_store_stays_on(self) -> None:"""Without cryptography, a shared/remote store must NOT degrade to off(which would deserialize unverified bytes from the very backend signingprotects); it stays verify so an unsigned entry misses."""from unittest import mockstore = MockStore()- w = LazyLoader("ns", store=store, signer=None, mode="off")+ w = LazyLoader("ns", store=store, signer=None, verification="off")w.save_cache(_simple_cache(hash_val="nocrypto_remote", z=9))w.flush()@@ -846,7 +863,7 @@ class TestReviewFixes(_FileStoreLoaderTest):return_value=False,):reader = LazyLoader("ns", store=store, signer=None)- assert reader._effective_mode() == "verify"+ assert reader._effective_verification() == "on"assert reader.load_cache(key("nocrypto_remote")) is Nonedef test_non_finite_floats_round_trip_and_keep_signature(self) -> None:@@ -858,7 +875,7 @@ class TestReviewFixes(_FileStoreLoaderTest):signer, verifier = _keypair()writer = LazyLoader(- "test", store=self.store, signer=signer, mode="verify"+ "test", store=self.store, signer=signer, verification="on")writer.save_cache(_simple_cache(@@ -885,7 +902,7 @@ class TestReviewFixes(_FileStoreLoaderTest):# strict → load returns a value only if verification passes; a broken# signature would raise instead.reader = LazyLoader(- "test", store=self.store, signer=verifier, mode="strict"+ "test", store=self.store, signer=verifier, verification="strict")loaded = reader.load_cache(key("nonfinite"))assert loaded is not None@@ -902,7 +919,7 @@ class TestReviewFixes(_FileStoreLoaderTest):import base64import string- from marimo._save.loaders.lazy import _normalize_fingerprint+ from marimo._save.signing import normalize_fingerprintsigner, _ = _keypair()canonical = signer.fingerprint()@@ -922,7 +939,7 @@ class TestReviewFixes(_FileStoreLoaderTest):)variant = "SHA256:" + body[:-1] + variant_charassert variant != canonical- assert _normalize_fingerprint(variant) == canonical+ assert normalize_fingerprint(variant) == canonicaldef test_strict_raises_on_unsupported_declared_key(self) -> None:"""If parsing the manifest's declared key raises (e.g. cryptography's@@ -935,7 +952,7 @@ class TestReviewFixes(_FileStoreLoaderTest):signer, verifier = _keypair()writer = LazyLoader(- "test", store=self.store, signer=signer, mode="verify"+ "test", store=self.store, signer=signer, verification="on")writer.save_cache(_simple_cache(hash_val="unsupported", z=1))writer.flush()@@ -947,7 +964,7 @@ class TestReviewFixes(_FileStoreLoaderTest):store=self.store,signer=None,trusted_signers={signer.fingerprint()},- mode="strict",+ verification="strict",)with mock.patch("marimo._save.loaders.lazy.fingerprint",@@ -957,7 +974,7 @@ class TestReviewFixes(_FileStoreLoaderTest):reader.load_cache(key("unsupported"))def test_off_mode_does_not_resolve_or_mint_signer(self) -> None:- """mode='off' never signs or verifies, so it must not load or mint a+ """verification='off' never signs or verifies, so it must not load or mint amachine-local signing key (avoiding a stray key file / read-onlystate-dir warnings for a caller who opted out)."""from unittest import mock@@ -967,7 +984,7 @@ class TestReviewFixes(_FileStoreLoaderTest):with mock.patch("marimo._save.loaders.lazy._get_default_signer") as get_signer:- loader = LazyLoader("test", store=self.store, mode="off")+ loader = LazyLoader("test", store=self.store, verification="off")assert loader.signer is Noneloader.save_cache(_simple_cache(hash_val="offkey", z=1))loader.flush()@@ -975,7 +992,7 @@ class TestReviewFixes(_FileStoreLoaderTest):# Still unresolved, so a later reconfigure to verify can resolve.assert isinstance(loader._signer, _Unset)- def test_wasm_store_verify_degrades_to_off(self) -> None:+ def test_wasm_store_on_degrades_to_off(self) -> None:"""The WASM HTTP store is same-origin as the notebook code, so a verifyloader with no key/anchor degrades to off (serves) rather than missingevery read — otherwise the bundled-cache restore feature this stack@@ -984,12 +1001,12 @@ class TestReviewFixes(_FileStoreLoaderTest):from marimo._save.stores.dict_store import DictStorestore = WasmLazyStore(DictStore())- w = LazyLoader("ns", store=store, signer=None, mode="off")+ w = LazyLoader("ns", store=store, signer=None, verification="off")assert w.save_cache(_simple_cache(hash_val="wasm_unsigned", z=7))w.flush()- reader = LazyLoader("ns", store=store, signer=None, mode="verify")- assert reader._effective_mode() == "off"+ reader = LazyLoader("ns", store=store, signer=None, verification="on")+ assert reader._effective_verification() == "off"loaded = reader.load_cache(key("wasm_unsigned"))assert loaded is not Noneassert loaded.defs["z"] == 7@@ -1003,7 +1020,7 @@ class TestReviewFixes(_FileStoreLoaderTest):from marimo._save.stores.dict_store import DictStorestore = WasmLazyStore(DictStore())- w = LazyLoader("ns", store=store, signer=None, mode="off")+ w = LazyLoader("ns", store=store, signer=None, verification="off")w.save_cache(_simple_cache(hash_val="wasm_nocrypto", z=8))w.flush()@@ -1012,8 +1029,10 @@ class TestReviewFixes(_FileStoreLoaderTest):"cryptography.has",return_value=False,):- reader = LazyLoader("ns", store=store, signer=None, mode="verify")- assert reader._effective_mode() == "off"+ reader = LazyLoader(+ "ns", store=store, signer=None, verification="on"+ )+ assert reader._effective_verification() == "off"loaded = reader.load_cache(key("wasm_nocrypto"))assert loaded is not Noneassert loaded.defs["z"] == 8@@ -1025,7 +1044,7 @@ class TestReviewFixes(_FileStoreLoaderTest):(fail-safe) treats the same garbage as a plain miss."""signer, _ = _keypair()loader = LazyLoader(- "test", store=self.store, signer=signer, mode="strict"+ "test", store=self.store, signer=signer, verification="strict")path = str(loader.build_path(key("garbage")))self.store.put(path, b"{ this is not valid json")@@ -1033,7 +1052,7 @@ class TestReviewFixes(_FileStoreLoaderTest):loader.load_cache(key("garbage"))verify_loader = LazyLoader(- "test", store=self.store, signer=signer, mode="verify"+ "test", store=self.store, signer=signer, verification="on")assert verify_loader.load_cache(key("garbage")) is None@@ -1068,11 +1087,11 @@ class TestReviewFixes(_FileStoreLoaderTest):# Drop the blob but leave the (still validly-signed) manifest.assert self.store.clear("test/missing_blob/pt.pickle")- strict = self._loader(signer=verifier, mode="strict")+ strict = self._loader(signer=verifier, verification="strict")with pytest.raises(CacheSignatureError):strict.load_cache(key("missing_blob"))- verify = self._loader(signer=verifier, mode="verify")+ verify = self._loader(signer=verifier, verification="on")assert verify.load_cache(key("missing_blob")) is Nonedef test_strict_deserialize_failure_is_miss_not_tampering(self) -> None:@@ -1092,7 +1111,7 @@ class TestReviewFixes(_FileStoreLoaderTest):def _boom(_data: bytes, _type_hint: str | None = None) -> Any:raise RuntimeError("deserializer cannot run in this environment")- reader = self._loader(signer=verifier, mode="strict")+ reader = self._loader(signer=verifier, verification="strict")with mock.patch.dict("marimo._save.loaders.lazy.BLOB_DESERIALIZERS",{".pickle": _boom},diff --git a/tests/_save/loaders/test_lazy_wasm.py b/tests/_save/loaders/test_lazy_wasm.pyindex 5f04598829..73e32ec482 100644--- a/tests/_save/loaders/test_lazy_wasm.py+++ b/tests/_save/loaders/test_lazy_wasm.py@@ -225,9 +225,9 @@ class TestLazyLoaderBatchPath:def test_restore_uses_batch_path(self) -> None:inner = DictStore()store = LazyStore(inner=inner)- # mode="off": this exercises the batch-restore mechanics, not signing+ # verification="off": this exercises the batch-restore mechanics, not signing# (covered in test_lazy_signing.py); the seeded manifest is unsigned.- loader = LazyLoader("test_batch", store=store, mode="off")+ loader = LazyLoader("test_batch", store=store, verification="off")# Seed a cache manuallybase = Path("test_batch") / "hash1"@@ -261,8 +261,8 @@ class TestLazyLoaderBatchPath:# (no threads in Pyodide) via `_dispatch_write`.inner = DictStore()store = WasmLazyStore(inner=inner)- # mode="off": exercises the synchronous WASM write path, not signing.- loader = WasmLazyLoader("test_sync", store=store, mode="off")+ # verification="off": exercises the synchronous WASM write path, not signing.+ loader = WasmLazyLoader("test_sync", store=store, verification="off")cache = Cache(defs={"x": 42, "y": "hello"},@@ -380,7 +380,7 @@ class TestRestoreTripwire:) -> None:self._patch_failing_codec(monkeypatch)store = LazyStore(inner=DictStore())- loader = LazyLoader("trip_native", store=store, mode="off")+ loader = LazyLoader("trip_native", store=store, verification="off")base = Path("trip_native") / "h"good_ref = (base / "good.pickle").as_posix()@@ -404,7 +404,7 @@ class TestRestoreTripwire:# Exercises the WASM `_read_blobs` variant (get_batch, no threads).self._patch_failing_codec(monkeypatch)store = WasmLazyStore(inner=DictStore())- loader = WasmLazyLoader("trip_wasm", store=store, mode="off")+ loader = WasmLazyLoader("trip_wasm", store=store, verification="off")base = Path("trip_wasm") / "h"good_ref = (base / "good.pickle").as_posix()@@ -431,7 +431,7 @@ class TestRestoreTripwire:from marimo._save.hash import HashKeystore = LazyStore(inner=DictStore())- loader = LazyLoader("trip_return", store=store, mode="off")+ loader = LazyLoader("trip_return", store=store, verification="off")base = Path("trip_return") / "h"good_ref = (base / "good.pickle").as_posix()@@ -459,7 +459,9 @@ class TestRestoreTripwire:from marimo._save.hash import HashKeystore = WasmLazyStore(inner=DictStore())- loader = WasmLazyLoader("trip_return_wasm", store=store, mode="off")+ loader = WasmLazyLoader(+ "trip_return_wasm", store=store, verification="off"+ )base = Path("trip_return_wasm") / "h"good_ref = (base / "good.pickle").as_posix()@@ -488,7 +490,7 @@ class TestRestoreTripwire:from marimo._save.hash import HashKeystore = LazyStore(inner=DictStore())- loader = LazyLoader("trip_ui", store=store, mode="off")+ loader = LazyLoader("trip_ui", store=store, verification="off")ui_ref = (Path("trip_ui") / "h" / "ui.pickle").as_posix()store.put(ui_ref, b"__FAIL__")@@ -534,7 +536,7 @@ class TestRestoreTripwire:)store = LazyStore(inner=DictStore())- loader = LazyLoader("trip_import", store=store, mode="off")+ loader = LazyLoader("trip_import", store=store, verification="off")bad_ref = (Path("trip_import") / "h" / "bad.faildep").as_posix()store.put(bad_ref, b"unused")self._seed(@@ -601,7 +603,7 @@ class TestStaleKeys:from marimo._save.loaders.lazy import _cache_statestore = LazyStore(inner=DictStore())- loader = LazyLoader("stale_test", store=store, mode="off")+ loader = LazyLoader("stale_test", store=store, verification="off")base = Path("stale_test") / "h"var_ref = (base / "v.pickle").as_posix()diff --git a/tests/_save/loaders/test_loader.py b/tests/_save/loaders/test_loader.pyindex 7047d53b4d..e10fae5672 100644--- a/tests/_save/loaders/test_loader.py+++ b/tests/_save/loaders/test_loader.py@@ -209,8 +209,8 @@ class TestLazyLoader(ABCTestLoader):def _instance(self) -> Loader:# These exercise generic loader mechanics (hit/miss, blob handling)# with hand-written unsigned manifests; signing behavior is covered in- # test_lazy_signing.py. mode="off" serves unsigned entries as-is.- return LazyLoader("test", store=self.store, mode="off")+ # test_lazy_signing.py. verification="off" serves unsigned entries as-is.+ return LazyLoader("test", store=self.store, verification="off")def teardown_method(self) -> None:if self.value and hasattr(self.value, "flush"):diff --git a/tests/_save/stubs/test_lazy_asset_codec.py b/tests/_save/stubs/test_lazy_asset_codec.pyindex 3fbe17fe93..d40a64e957 100644--- a/tests/_save/stubs/test_lazy_asset_codec.py+++ b/tests/_save/stubs/test_lazy_asset_codec.py@@ -40,7 +40,7 @@ def test_blob_asset_codec_round_trip() -> None:def test_lazy_loader_round_trips_blob_asset() -> None:store = MockStore()- loader = LazyLoader("asset-test", store=store, mode="off")+ loader = LazyLoader("asset-test", store=store, verification="off")asset = BlobAsset(data=b"\x89PNG\r\n\x1a\n",media_type="image/png",diff --git a/tests/_save/test_signing_policy.py b/tests/_save/test_signing_policy.pynew file mode 100644index 0000000000..cfee1e3d25--- /dev/null+++ b/tests/_save/test_signing_policy.py@@ -0,0 +1,425 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import os+from types import SimpleNamespace++import pytest++from marimo._save.cache import CacheState+from marimo._save.signing import (+ fingerprint,+ generate_keypair,+)+from marimo._save.signing_policy import (+ SigningPolicy,+ _resolve_trusted_signers,+)+from marimo._save.stores import DEFAULT_STORE+from marimo._session.model import SessionMode+++def keypair() -> tuple[str, str, str]:+ pytest.importorskip("cryptography")+ priv, pub = generate_keypair()+ return priv, pub, fingerprint(pub)++[email protected](autouse=True)+def _clear_signing_env(monkeypatch) -> None:+ # The policy reads signing env vars at freeze; keep tests hermetic.+ monkeypatch.delenv("MARIMO_CACHE_SIGNING_PRIVATE_KEY", raising=False)+ monkeypatch.delenv("MARIMO_CACHE_SIGNING_PUBLIC_KEY", raising=False)+++def _alternate_spelling(fp: str) -> str:+ """A different raw spelling of `fp` that canonicalizes back to it.++ `normalize_fingerprint` accepts urlsafe base64 and optional padding.+ Padding is the dimension that always differs: base64 of a 32-byte digest is+ 43 characters plus one `=`, which `fingerprint()` strips. Swapping `+`/`/`+ for `-`/`_` alone would leave the test vacuous for the ~1 digest in 4 that+ contains neither character.+ """+ body = fp[len("SHA256:") :]+ alternate = "SHA256:" + body.replace("+", "-").replace("/", "_") + "="+ assert alternate != fp+ return alternate+++class TestSigningPolicyFromConfig:+ def test_empty_config_defaults(self) -> None:+ policy = SigningPolicy.from_config({})+ assert policy.verification == "on"+ assert policy.trusted_signers == frozenset()+ assert policy.signer is None+ # The machine-key path is frozen at construction, not read live later.+ from marimo._utils.xdg import marimo_state_dir++ assert policy.state_key_path == str(+ marimo_state_dir() / "cache_signing_key.pem"+ )++ def test_verification_passthrough(self) -> None:+ assert SigningPolicy.from_config(+ {"cache": {"verification": "strict"}}+ ).verification == ("strict")+ assert SigningPolicy.from_config(+ {"cache": {"verification": "off"}}+ ).verification == ("off")++ def test_invalid_verification_falls_back_to_on(self) -> None:+ policy = SigningPolicy.from_config(+ {"cache": {"verification": "bogus"}}+ )+ assert policy.verification == "on"++ def test_trusted_signers_normalized(self, keypair) -> None:+ _priv, pub, fp = keypair+ # An urlsafe, padded variant must canonicalize to fingerprint() output.+ policy = SigningPolicy.from_config(+ {+ "signing": {+ "trusted_signers": {_alternate_spelling(fp): "alice"}+ }+ }+ )+ assert policy.trusted_signers == frozenset({fp})++ def test_malformed_fingerprints_dropped(self, keypair) -> None:+ _priv, _pub, fp = keypair+ policy = SigningPolicy.from_config(+ {+ "signing": {+ "trusted_signers": {+ fp: "good",+ "SHA256:not-valid-base64!!": "bad",+ "no-prefix": "bad",+ }+ }+ }+ )+ assert policy.trusted_signers == frozenset({fp})++ def test_non_dict_trusted_signers_ignored(self) -> None:+ policy = SigningPolicy.from_config(+ {"signing": {"trusted_signers": ["SHA256:whatever"]}}+ )+ assert policy.trusted_signers == frozenset()++ def test_private_key_path_resolves_to_signer(+ self, keypair, tmp_path+ ) -> None:+ priv, _pub, fp = keypair+ key_file = tmp_path / "key.pem"+ key_file.write_text(priv)+ # The concrete signer is resolved eagerly at freeze (not lazily).+ policy = SigningPolicy.from_config(+ {"signing": {"private_key_path": str(key_file)}}+ )+ assert policy.signer is not None+ assert policy.signer.fingerprint() == fp++ def test_bad_private_key_path_degrades_to_none(self, tmp_path) -> None:+ policy = SigningPolicy.from_config(+ {"signing": {"private_key_path": str(tmp_path / "missing.pem")}}+ )+ assert policy.signer is None++ def test_oversized_key_file_read_rejected(self, tmp_path) -> None:+ # The cap must fire before the whole file is read (DoS guard). A valid+ # key is never this large, so pin the read primitive directly.+ from marimo._save.signing_policy import (+ _MAX_KEY_FILE_BYTES,+ _read_key_file,+ )++ big = tmp_path / "big.pem"+ big.write_text("x" * (_MAX_KEY_FILE_BYTES + 1))+ with pytest.raises(OSError, match="too large"):+ _read_key_file(str(big))+ # End-to-end, the read failure degrades to no signer, never a raise.+ policy = SigningPolicy.from_config(+ {"signing": {"private_key_path": str(big)}}+ )+ assert policy.signer is None++ def test_non_string_private_key_path_degrades(self) -> None:+ # A wrong type in the TOML must follow the documented fallback, not+ # raise out of policy resolution and stop the session from starting.+ policy = SigningPolicy.from_config(+ {"signing": {"private_key_path": 5}}+ )+ assert policy.signer is None++ def test_relative_private_key_path_rejected(+ self, keypair, tmp_path, monkeypatch+ ) -> None:+ # A valid key exists at ./key.pem, but a relative path must still be+ # refused — otherwise a project run from its own dir substitutes a key.+ priv, _pub, _fp = keypair+ (tmp_path / "key.pem").write_text(priv)+ monkeypatch.chdir(tmp_path)+ policy = SigningPolicy.from_config(+ {"signing": {"private_key_path": "key.pem"}}+ )+ assert policy.signer is None++ def test_symlinked_key_not_followed(self, keypair, tmp_path) -> None:+ if not hasattr(os, "O_NOFOLLOW"):+ pytest.skip("O_NOFOLLOW unavailable on this platform")+ from marimo._save.signing_policy import _read_key_file++ priv, _pub, _fp = keypair+ real = tmp_path / "real.pem"+ real.write_text(priv)+ link = tmp_path / "link.pem"+ os.symlink(real, link)+ with pytest.raises(OSError):+ _read_key_file(str(link))++ def test_encrypted_pem_degrades_like_garbage(self, tmp_path):+ # An encrypted key raises TypeError (not ValueError) deep in+ # cryptography; it must degrade to None uniformly, not propagate.+ pytest.importorskip("cryptography")+ from cryptography.hazmat.primitives import serialization+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (+ Ed25519PrivateKey,+ )++ enc = Ed25519PrivateKey.generate().private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.BestAvailableEncryption(b"hunter2"),+ )+ key_file = tmp_path / "enc.pem"+ key_file.write_bytes(enc)+ policy = SigningPolicy.from_config(+ {"signing": {"private_key_path": str(key_file)}}+ )+ assert policy.signer is None++ def test_env_public_key_becomes_trusted_fingerprint(+ self, keypair, monkeypatch+ ) -> None:+ # An inherited public key is a trusted *verifier* (a fingerprint), not+ # an implicitly-trusted own signer.+ _priv, pub, fp = keypair+ monkeypatch.setenv("MARIMO_CACHE_SIGNING_PUBLIC_KEY", pub)+ policy = SigningPolicy.from_config({})+ assert fp in policy.trusted_signers+ assert policy.signer is None++ def test_env_private_key_becomes_signer(+ self, keypair, monkeypatch+ ) -> None:+ priv, _pub, fp = keypair+ monkeypatch.setenv("MARIMO_CACHE_SIGNING_PRIVATE_KEY", priv)+ policy = SigningPolicy.from_config({})+ assert policy.signer is not None+ assert policy.signer.fingerprint() == fp+++class TestResolveTrustedSigners:+ def test_none_returns_empty(self) -> None:+ assert _resolve_trusted_signers(None) == set()++ def test_duplicate_after_normalization_kept_once(self) -> None:+ pytest.importorskip("cryptography")+ _priv, pub = generate_keypair()+ fp = fingerprint(pub)+ # Distinct raw keys that canonicalize to the same fingerprint.+ resolved = _resolve_trusted_signers(+ {fp: "a", _alternate_spelling(fp): "b"}+ )+ assert resolved == {fp}+++class TestPolicyReachesLoader:+ """The session policy is the loader's default trust/identity source."""++ @pytest.fixture+ def patched_state(self, monkeypatch):+ state = CacheState(store=DEFAULT_STORE())+ monkeypatch.setattr(+ "marimo._save.loaders.lazy._cache_state", lambda: state+ )+ return state++ def test_policy_verification_and_trust_applied(+ self, patched_state, keypair+ ) -> None:+ from marimo._save.loaders.lazy import LazyLoader++ _priv, _pub, fp = keypair+ patched_state.signing_policy = SigningPolicy(+ verification="strict", trusted_signers=frozenset({fp})+ )+ loader = LazyLoader("policy_applied")+ assert loader._verification == "strict"+ assert fp in loader.trusted_signers++ def test_explicit_args_override_policy(+ self, patched_state, keypair+ ) -> None:+ from marimo._save.loaders.lazy import LazyLoader++ _priv, _pub, fp = keypair+ patched_state.signing_policy = SigningPolicy(+ verification="strict", trusted_signers=frozenset({fp})+ )+ # Explicit empty trust + off mode must win over the policy.+ loader = LazyLoader(+ "policy_override", verification="off", trusted_signers=set()+ )+ assert loader._verification == "off"+ assert loader.trusted_signers == frozenset()++ def test_no_policy_uses_defaults(self, patched_state) -> None:+ from marimo._save.loaders.lazy import LazyLoader++ patched_state.signing_policy = None+ loader = LazyLoader("policy_absent", verification="off")+ assert loader._verification == "off"+ assert loader.trusted_signers == frozenset()++ def test_omitted_trusted_signers_inherits_policy(+ self, patched_state, keypair+ ) -> None:+ from marimo._save.loaders.lazy import LazyLoader++ _priv, _pub, fp = keypair+ patched_state.signing_policy = SigningPolicy(+ verification="off", trusted_signers=frozenset({fp})+ )+ loader = LazyLoader("inherits", verification="off")+ assert loader.trusted_signers == frozenset({fp})++ def test_explicit_none_trusted_signers_means_no_trust(+ self, patched_state, keypair+ ) -> None:+ from marimo._save.loaders.lazy import LazyLoader++ _priv, _pub, fp = keypair+ patched_state.signing_policy = SigningPolicy(+ verification="off", trusted_signers=frozenset({fp})+ )+ # Explicit None must NOT silently inherit the policy trust — it means+ # "no trust", like set(). Distinguished from omission by the sentinel.+ loader = LazyLoader(+ "explicit_none", verification="off", trusted_signers=None+ )+ assert loader.trusted_signers == frozenset()+++class TestChildContextInheritsPolicy:+ """An embedded app's child context must not resolve a second policy.++ The policy is frozen before the kernel loads any configured `.env`. A child+ context created later would resolve against a post-dotenv environment, so a+ committed `.env` could introduce a signing identity mid-session — the exact+ window freezing is meant to close.+ """++ def _context(self, monkeypatch, *, parent):+ from marimo._runtime.context import kernel_context++ resolved: list[str] = []++ def _spy(*_args: object, **_kwargs: object) -> SigningPolicy:+ resolved.append("called")+ return SigningPolicy(verification="strict")++ # `create_kernel_context` imports these inside the function, so patch+ # them where they are defined.+ monkeypatch.setattr(+ "marimo._save.signing_policy.get_signing_policy", _spy+ )+ monkeypatch.setattr(+ "marimo._save.stores.get_store", lambda _path: DEFAULT_STORE()+ )+ kernel = SimpleNamespace(+ app_metadata=SimpleNamespace(filename=None, app_config=None),+ user_config={},+ )+ ctx = kernel_context.create_kernel_context(+ kernel=kernel,+ streams=SimpleNamespace(stream=None, stdout=None, stderr=None),+ virtual_file_storage=None,+ mode=SessionMode.EDIT,+ parent=parent,+ )+ return ctx, resolved++ def test_root_context_resolves_once(self, monkeypatch) -> None:+ ctx, resolved = self._context(monkeypatch, parent=None)+ assert resolved == ["called"]+ # The resolved policy reaches the cache state, not a default.+ assert ctx.cache.signing_policy is not None+ assert ctx.cache.signing_policy.verification == "strict"++ def test_child_reuses_parent_policy(self, monkeypatch) -> None:+ parent, _ = self._context(monkeypatch, parent=None)+ parent_policy = parent.cache.signing_policy++ child, resolved = self._context(monkeypatch, parent=parent)+ # Not re-resolved: the child holds the very same frozen object.+ assert resolved == []+ assert child.cache.signing_policy is parent_policy+++class TestKeyFileReadCap:+ def test_cap_applies_to_bytes_read_not_only_to_stat(+ self, tmp_path, monkeypatch+ ) -> None:+ """The size cap must hold even if the file grows after the stat.++ `_read_key_file` stats the descriptor and then reads from it. A file+ that grows in between would sail past a stat-only check.+ """+ import os as os_module++ from marimo._save.signing_policy import (+ _MAX_KEY_FILE_BYTES,+ _read_key_file,+ )++ big = tmp_path / "grown.pem"+ big.write_text("x" * (_MAX_KEY_FILE_BYTES + 1))++ real_fstat = os_module.fstat++ def _understating_fstat(fd: int) -> object:+ st = real_fstat(fd)+ return SimpleNamespace(st_mode=st.st_mode, st_size=1)++ monkeypatch.setattr(+ "marimo._save.signing_policy.os.fstat", _understating_fstat+ )+ with pytest.raises(OSError, match="too large"):+ _read_key_file(str(big))+++class TestInvalidEntriesAreNotLogged:+ def test_entry_is_not_written_to_the_log(self) -> None:+ """The rejected entry must not reach the log.++ A fingerprint gives the reader nothing to act on, and this path runs+ when parsing failed, so what the value holds is unknown — a mispaste+ could put a private key in `trusted_signers`.+ """+ from unittest.mock import patch++ secret = "SHA256:" + "SUPERSECRETKEYMATERIAL" * 4+ with patch("marimo._save.signing_policy.LOGGER") as logger:+ policy = SigningPolicy.from_config(+ {"signing": {"trusted_signers": {secret: "oops"}}}+ )++ assert policy.trusted_signers == frozenset()+ logged = " ".join(str(c) for c in logger.warning.call_args_list)+ assert "SUPERSECRETKEYMATERIAL" not in logged+ # The reader still learns that an entry was dropped, and the format.+ assert "signing.trusted_signers" in logged+ assert "SHA256:<base64>" in logged