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
feat: add signatures to cache bundles to prevent tamper (#10123)
Dylan Madisettif68522021a4c
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 349609deee..c6a918a7e7 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -263,6 +263,7 @@ class DependencyManager:obstore = Dependency("obstore")fsspec = Dependency("fsspec")cloudpathlib = Dependency("cloudpathlib")+ cryptography = Dependency("cryptography")# Version requirements to properly support the new superfences introduced in# pymdown#2470diff --git a/marimo/_save/loaders/lazy.py b/marimo/_save/loaders/lazy.pyindex 24ede1ef40..1765b2a570 100644--- a/marimo/_save/loaders/lazy.py+++ b/marimo/_save/loaders/lazy.py@@ -1,9 +1,11 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import base64import hashlibimport importlibimport inspect+import mathimport pickleimport queueimport threading@@ -28,6 +30,13 @@ from marimo._save.cache import (from marimo._save.encode import common_container_to_bytes, data_to_bufferfrom marimo._save.hash import DEFAULT_HASH, HashKeyfrom marimo._save.loaders.loader import BasePersistenceLoader+from marimo._save.signing import (+ CacheSignatureError,+ CacheSigner,+ _get_default_signer,+ _sha256hex,+ fingerprint,+)from marimo._save.stores import DEFAULT_STORE, FileStore, Storeif TYPE_CHECKING:@@ -54,10 +63,189 @@ from marimo._save.stubs.stubs import mro_lookupLOGGER = _loggers.marimo_logger()+class _Unset:+ """Sentinel for LazyLoader.signer default — distinguishes 'not provided'+ from explicit `None` (which opts out of signing entirely)."""+++_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).+ """+ 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}++class _BlobStatus(Enum):- """Sentinel placed in the results queue when a blob is missing."""+ """Sentinel placed in the results queue for a blob that yielded no value.++ `MISSING`: the store had no bytes for the key — under a verified manifest a+ genuine gap is an integrity anomaly. `UNREADABLE`: bytes were present and+ hash-verified but the deserializer failed (an environment issue, e.g. a+ CUDA tensor on a CPU-only host) — authentic, so recompute rather than flag+ tampering.+ """MISSING = auto()+ UNREADABLE = auto()+++# Domain-separation tag prepended to manifest signable bytes, binding a+# signature to this purpose and format version independent of payload shape.+_MANIFEST_SIG_CONTEXT = b"marimo-cache-manifest:v1:"+++def _signable_bytes(schema: CacheSchema) -> bytes:+ """Return the canonical bytes to sign or verify for a cache manifest.++ Clears the `signature` envelope field so save and restore operate on+ identical input. The manifest structs set `omit_defaults` (see+ `lazy_stub.py`), so these bytes stay stable across additive,+ absent-defaulted schema changes; any other schema change must bump+ `MARIMO_CACHE_VERSION`.+ """+ unsigned_meta = msgspec.structs.replace(schema.meta, signature=None)+ return _MANIFEST_SIG_CONTEXT + msgspec.json.encode(+ msgspec.structs.replace(schema, meta=unsigned_meta)+ )+++def _is_local_file_store(store: Store) -> bool:+ """True when a loader's blobs live on the local filesystem, so a+ machine-local auto-generated signing key is meaningful (single-machine+ trust).++ `LazyStore` wraps its backend by composition rather than subclassing+ `FileStore`, so unwrap to the inner store. Shared/remote backends+ (Redis, REST) and the WASM HTTP store (`DictStore` inner) return+ `False` — their entries can't be verified by a key only this machine+ holds.+ """+ if isinstance(store, LazyStore):+ return isinstance(store._inner, FileStore)+ return isinstance(store, FileStore)+++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)+++def _verify_signed_blob(+ key: str,+ data: bytes,+ blob_hash_map: dict[str, str] | None,+ effective_signer: CacheSigner | None,+) -> None:+ """Check a fetched blob against its signed hash before deserialization.++ No-op for unsigned entries (`effective_signer is None`). For a verified+ manifest, a *missing* hash is itself a signature error: the signed manifest+ and the blob set must agree, so a hash-less reference means writer drift or+ tampering rather than a reason to skip the check (which would otherwise let+ a blob reach `pickle.loads` unverified — even in strict mode).+ """+ if effective_signer is None:+ return+ expected_hash = (blob_hash_map or {}).get(key)+ if expected_hash is None:+ raise CacheSignatureError(+ f"A signed cache entry is missing the integrity hash for blob "+ f"{key!r}. The cached data may be corrupted or was modified "+ f"outside of marimo.\n"+ f"To recover, call cache_clear() on the cached function or "+ f"context manager."+ )+ effective_signer.verify_blob(key, data, expected_hash)+++def _incomplete_cache_error(+ effective_signer: CacheSigner | None,+) -> Exception:+ """Error for a cache entry missing one or more blobs."""+ # NB. under a verified manifest the blob set is authenticated, so a missing+ # blob is a trust anomaly: raise CacheSignatureError so strict fails closed+ # (verify still misses). Unsigned entries stay a plain miss.+ if effective_signer is not None:+ return CacheSignatureError(+ "A signed cache entry is missing one or more blobs. The cached "+ "data may be corrupted or was modified outside of marimo.\n"+ "To recover, call cache_clear() on the cached function or "+ "context manager."+ )+ return FileNotFoundError("Incomplete cache: missing blobs")def _module_available(type_hint: str | None) -> bool:@@ -134,6 +322,21 @@ def _maybe_import_ref(value: Any) -> tuple[str, str] | None:return (module, qualname) if obj is value else None+# Token <-> value for non-finite floats, inlined in Item.special_float rather+# than pickled (see the field for why they can't use Item.primitive).+_NON_FINITE_FLOATS: dict[str, float] = {+ "nan": float("nan"),+ "inf": float("inf"),+ "-inf": float("-inf"),+}+++def _non_finite_token(value: float) -> str:+ if math.isnan(value):+ return "nan"+ return "inf" if value > 0 else "-inf"++def to_item(path: Path,value: Any | None,@@ -175,7 +378,20 @@ def to_item(module=value.name,module_version=value.version or None,)- if isinstance(value, (int, str, float, bool, bytes, type(None))):+ # bool must be tested before int (bool is a subclass of int).+ # Coerce scalar subclasses (e.g. numpy.float64, numpy.int32) to plain+ # Python types so msgspec.json.encode can serialise them.+ if isinstance(value, bool):+ return Item(primitive=bool(value))+ if isinstance(value, int):+ return Item(primitive=int(value))+ if isinstance(value, float):+ if not math.isfinite(value):+ return Item(special_float=_non_finite_token(value))+ return Item(primitive=float(value))+ # NB. no `bytes`: msgspec JSON-encodes it to a base64 str that restores as+ # str, corrupting the value (bytes route to "pickle" via LAZY_STUB_LOOKUP).+ if isinstance(value, (str, type(None))):return Item(primitive=value)return Item(@@ -213,6 +429,10 @@ def from_item(item: Item, var_name: str = "") -> Any:return FunctionStub.from_dump(item.function)if item.class_def is not None:return ClassStub.from_dump(item.class_def)+ if item.special_float is not None:+ # A corrupted/unknown token can only arise in a tampered manifest,+ # which verify/strict reject before reaching here; fall back to nan.+ return _NON_FINITE_FLOATS.get(item.special_float, float("nan"))if item.primitive is not None:return item.primitivereturn None@@ -443,7 +663,59 @@ class LazyLoader(BasePersistenceLoader):self,name: str,store: Store | None = None,+ signer: CacheSigner | None | _Unset = _SIGNER_UNSET,+ trusted_signers: Iterable[str] | None = None,+ mode: str = "verify",) -> None:+ """Create a LazyLoader.++ Args:+ name: Cache namespace / directory name.+ store: Backing store. Defaults to `LazyStore` (file-based).+ signer: :class:`~marimo._save.signing.CacheSigner` for Ed25519+ manifest signing (write) and verification (read). A loader+ always trusts its own signer's key, so the common case — one+ signer 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.+ trusted_signers: Fingerprint strings (`"SHA256:<base64>"` from+ :func:`~marimo._save.signing.fingerprint`) that this loader+ trusts, in addition to its own signer (always trusted for its+ own writes). An entry verifies when it is signed directly by a+ trusted fingerprint's key. Padded or urlsafe fingerprints are+ normalized 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+ :class:`~marimo._save.signing.CacheSignatureError` on an+ unverifiable entry (fail-closed). `strict` also requires a+ signing/verification capability at construction; `verify`+ degrades to `off` (with a one-time warning) when none exists.+ """+ if (+ not isinstance(signer, (_Unset, CacheSigner))+ and signer is not None+ ):+ raise TypeError(+ "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_loadersif store is None:# Reuse the store across recreations of a named loader (State GC,@@ -452,8 +724,178 @@ 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._degrade_warned = False+ self._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.+ 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+ # verify/strict (resolving the key), but returns early for 'off'.+ # 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()loaders[name] = self+ def _resolve_unset_signer(self) -> CacheSigner | None:+ """Auto-resolve the signer for an unset value, matching __init__.++ A local file store auto-generates (or loads) a machine-local key so the+ loader signs its own writes — *even when* `trusted_signers` is also+ configured. Composing trust with signing this way means adding a+ teammate's fingerprint to also trust their caches never silently turns+ off signing of our own writes (which would otherwise leave the loader+ read-only). Shared/remote stores don't auto-generate — an auto key is+ unverifiable by other machines — so they use only an explicitly+ configured (env/config) 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.+ """+ if self._mode == "off":+ return "off"++ from marimo._dependencies.dependencies import DependencyManager++ if not DependencyManager.cryptography.has():+ if self._mode == "strict":+ raise ValueError(+ "mode='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"+ if self.signer is None and not self._trusted_fingerprints:+ if self._mode == "strict":+ raise ValueError(+ "mode='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++ def _warn_degraded(self, reason: str) -> None:+ if not self._degrade_warned:+ self._degrade_warned = True+ LOGGER.warning(+ "LazyLoader mode=%r degraded to 'off' because %s; cache "+ "entries are neither signed nor verified.",+ self._mode,+ reason,+ )++ def _warn_no_trust_anchor(self, reason: str) -> None:+ """One-time warning: a shared/remote store has no way to verify.++ 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).+ """+ if not self._degrade_warned:+ self._degrade_warned = True+ LOGGER.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 "+ "MARIMO_CACHE_SIGNING_PUBLIC_KEY (to verify only), or pass "+ "trusted_signers=..., to use the cache; or mode='off' to cache "+ "without signing.",+ self._mode,+ reason,+ )++ # Property accessors so LoaderPartial.create_or_reconfigure() can update+ # signer / trusted_signers / mode via setattr() using the constructor+ # argument names.+ @property+ def signer(self) -> CacheSigner | None:+ # Auto-resolve the _Unset sentinel on first access. In 'off' mode 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":+ return None+ self._signer = self._resolve_unset_signer()+ return self._signer++ @signer.setter+ def signer(self, value: CacheSigner | None | _Unset) -> None:+ # Validate up front (mirrors __init__) so a bad reconfigure fails here+ # rather than as an AttributeError mid-save.+ if not isinstance(value, (_Unset, CacheSigner)) and value is not None:+ raise TypeError(+ "signer must be a CacheSigner or None, got "+ 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.+ self._signer = value++ @property+ def trusted_signers(self) -> frozenset[str]:+ # Frozen copy so mutating the return value can't bypass+ # _normalize_fingerprints — assign to the property to change trust.+ return frozenset(self._trusted_fingerprints)++ @trusted_signers.setter+ def trusted_signers(self, value: Iterable[str] | None) -> None:+ self._trusted_fingerprints = _normalize_fingerprints(value)++ @property+ def mode(self) -> str:+ return self._mode++ @mode.setter+ def mode(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+def flush(self) -> None:"""Wait for all pending background writes to complete."""for t in self._pending:@@ -495,6 +937,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+ # configuration surfaces as a ValueError rather than being swallowed+ # as a generic miss by the except clause below.+ mode = self._effective_mode()manifest_key = str(self.build_path(key))# Invalidated for re-execution this session.if manifest_key in _cache_state().stale_keys:@@ -505,6 +951,26 @@ class LazyLoader(BasePersistenceLoader):if not blob:return Nonereturn self.restore_cache(key, blob)+ except CacheSignatureError as e:+ # Evict the rejected manifest + its blobs. On WASM this clears the+ # HTTP-fetched bytes from the session store (and poisons the keys+ # so they aren't re-fetched), so tampered data can't be re-served+ # or swept into a later export bundle via export_keys(); no-op+ # natively, where a non-strict recompute overwrites the entry.+ # Any manifest that fails to verify against a trusted key reaches+ # 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":+ raise+ # verify (fail-safe): degrade to cache miss rather than crashing;+ # the entry is recomputed rather than served unverified.+ LOGGER.warning(+ "Cache signature verification failed (treating as "+ "cache miss): %s",+ e,+ )+ return Noneexcept Exception as e:LOGGER.warning("Failed to restore lazy cache: %s", e)self._on_restore_failure(key, blob)@@ -516,9 +982,133 @@ class LazyLoader(BasePersistenceLoader):"""Hook after a failed restore. No-op natively; the WASM variantevicts and poisons the bad keys so HTTP won't re-fetch them."""- def restore_cache(self, _key: HashKey, blob: bytes) -> Cache:- cache_data = msgspec.json.decode(blob, type=CacheSchema)+ def _direct_candidates(self, cache_data: CacheSchema) -> list[CacheSigner]:+ """Candidate verifier keys for the direct path, in priority order:+ this loader's own signer (always trusted for its own writes), then the+ manifest's declared signer key when its fingerprint is in+ `trusted_signers`."""+ candidates: list[CacheSigner] = []+ own = self.signer+ if own is not None:+ candidates.append(own)+ declared = cache_data.meta.signer_public_key+ if declared:+ try:+ if fingerprint(declared) in self._trusted_fingerprints:+ candidates.append(+ CacheSigner.from_public_key_pem(declared)+ )+ except Exception:+ # A malformed/unsupported declared key can't be a direct+ # candidate (parsing it can raise ValueError,+ # CacheSignatureError, or cryptography's UnsupportedAlgorithm,+ # none of which subclass a common base) — swallow it here so a+ # strict loader still raises "unverifiable" downstream instead+ # of escaping to the generic-miss handler. The own-signer+ # candidate may still verify.+ pass+ return candidates++ def _resolve_effective_signer(+ self, cache_data: CacheSchema, mode: 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 `verify`/`strict` the entry must verify against a trusted key:+ this loader's own signer (implicitly trusted for its own writes), or+ the manifest's declared signer key when its fingerprint is in+ `trusted_signers`. Anything else raises `CacheSignatureError`, so+ unverifiable data is recomputed (verify) or rejected (strict) — never+ deserialized.++ Returning the verifying signer (non-`None`) enables the blob-hash+ checks downstream.++ Note: a cache written by another machine's auto-generated key on a+ shared or committed cache dir won't match any trusted fingerprint, so+ it misses (recomputes) rather than being accepted. To share a cache+ across machines, configure a shared signing key+ (`MARIMO_CACHE_SIGNING_*`) or add the writer's fingerprint to+ `trusted_signers`.+ """+ if mode == "off":+ return None++ sig = cache_data.meta.signature+ if 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"signing or was tampered with; it will be recomputed.\n"+ f"To recover, call cache_clear() on the cached function or "+ f"context manager."+ )++ signable = _signable_bytes(cache_data)+ for verifier in self._direct_candidates(cache_data):+ try:+ verifier.verify(signable, sig)+ return verifier+ except CacheSignatureError:+ continue++ raise CacheSignatureError(+ "A cache entry could not be verified against any trusted signer — "+ "its signature is invalid or was made by an untrusted key. The "+ "entry will be recomputed.\n"+ "To recover, call cache_clear() on the cached function or context "+ "manager."+ )++ def restore_cache(self, key: HashKey, blob: bytes) -> Cache:+ mode = self._effective_mode()+ 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":+ raise CacheSignatureError(+ "A cache manifest could not be decoded (mode='strict'). "+ "The cache may be corrupted or was modified outside of "+ "marimo.\n"+ "To recover, call cache_clear() on the cached function or "+ "context manager."+ ) from e+ raise++ # Guard: the manifest must describe the entry we asked for, checked+ # 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+ # 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":+ 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"The cache may be corrupted or was modified outside of "+ f"marimo.\n"+ f"To recover, call cache_clear() on the cached function or "+ f"context manager."+ )+ raise FileNotFoundError(+ f"Cache manifest hash {cache_data.hash!r} does not match the "+ f"requested key {key.hash!r}"+ )++ # 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+ # 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)+base = Path(self.name) / cache_data.hash+ blob_hash_map = cache_data.meta.blob_hashes # {} for unsigned entries# Collect references to loadref_vars: dict[str, str] = {}@@ -562,7 +1152,12 @@ class LazyLoader(BasePersistenceLoader):if return_ref:unique_keys.add(return_ref)unpickled = self._read_blobs(- unique_keys, ref_type_hints, return_ref, return_type_hint+ unique_keys,+ ref_type_hints,+ return_ref,+ return_type_hint,+ blob_hash_map,+ effective_signer,)# Distribute to defs@@ -583,7 +1178,11 @@ class LazyLoader(BasePersistenceLoader):# the unpickle until Cache.restore has materialized the class.raw = self.store.get(ref)if not raw:- raise FileNotFoundError("Incomplete cache: missing blobs")+ raise _incomplete_cache_error(effective_signer)+ # Deferred blobs bypass `_read_blobs`, so verify the signed+ # blob hash here too — before these bytes are ever unpickled+ # by `ReferenceStub.load` during `Cache.restore`.+ _verify_signed_blob(ref, raw, blob_hash_map, effective_signer)stub = ImmediateReferenceStub(ReferenceStub(ref, hash_value=item.hash or "", blob=raw))@@ -636,7 +1235,13 @@ class LazyLoader(BasePersistenceLoader):ref_type_hints: dict[str, str | None],return_ref: str | None,return_type_hint: str | None,+ blob_hash_map: dict[str, str] | None = None,+ effective_signer: CacheSigner | None = None,) -> Any:+ # Verify the blob hash before deserialization so a tampered blob never+ # reaches pickle.loads. Raises CacheSignatureError (propagated by the+ # callers) on mismatch or a missing hash under a verified manifest.+ _verify_signed_blob(key, data, blob_hash_map, effective_signer)ext = Path(key).suffixdeserialize = BLOB_DESERIALIZERS.get(ext, BLOB_DESERIALIZERS[".pickle"]@@ -658,9 +1263,16 @@ class LazyLoader(BasePersistenceLoader):ref_type_hints: dict[str, str | None],return_ref: str | None,return_type_hint: str | None,+ blob_hash_map: dict[str, str] | None = None,+ effective_signer: CacheSigner | None = None,) -> dict[str, Any]:"""Read + deserialize blobs in parallel via threads."""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+ # generic cache miss.+ errors: list[CacheSignatureError] = []def _load_blob(key: str) -> None:try:@@ -675,14 +1287,22 @@ class LazyLoader(BasePersistenceLoader):ref_type_hints,return_ref,return_type_hint,+ blob_hash_map,+ effective_signer,),))else:results.put((key, _BlobStatus.MISSING))+ except CacheSignatureError as exc:+ errors.append(exc)+ results.put((key, _BlobStatus.MISSING))except Exception as e:+ # Hash verification precedes deserialization, so bytes that+ # reach here are authentic — a failure is an environment issue,+ # not tampering. Recompute rather than flag corruption.LOGGER.warning("Failed to deserialize blob %s: %s", key, e)- results.put((key, _BlobStatus.MISSING))+ results.put((key, _BlobStatus.UNREADABLE))threads = [threading.Thread(target=_load_blob, args=(key,))@@ -691,15 +1311,38 @@ class LazyLoader(BasePersistenceLoader):for t in threads:t.start()unpickled: dict[str, Any] = {}+ missing = False+ unreadable = Falsetry:+ # Drain all N results (one per key) and join before deciding.+ # Raising on the first MISSING dequeued would let a genuinely+ # missing blob mask a concurrent thread's signed-hash mismatch,+ # routing a strict loader through the generic-miss path instead of+ # raising. Each error thread appends to `errors` before putting its+ # MISSING, so after the full drain `errors` is complete.for _ in unique_keys:key, val = results.get()if val is _BlobStatus.MISSING:- raise FileNotFoundError("Incomplete cache: missing blobs")- unpickled[key] = val+ missing = True+ elif val is _BlobStatus.UNREADABLE:+ unreadable = True+ else:+ unpickled[key] = valfinally:for t in threads: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.+ if errors:+ raise errors[0]+ if missing:+ raise _incomplete_cache_error(effective_signer)+ if unreadable:+ raise FileNotFoundError(+ "Incomplete cache: a blob could not be deserialized"+ )return unpickleddef save_cache(self, cache: Cache) -> bool:@@ -759,9 +1402,60 @@ class LazyLoader(BasePersistenceLoader):version = cache.meta.get("version", MARIMO_CACHE_VERSION)+ # Use property to normalise any stale _Unset sentinel.+ signer = self.signer+ mode = self._effective_mode()+ # 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++ if mode != "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 = True+ LOGGER.warning(+ "LazyLoader mode=%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,+ )+ return False++ # Blob digests collected while writing; embedded + signed by+ # `_encode_manifest` on the signed path (stays empty otherwise).+ blob_hashes: dict[str, str] = {}+def _encode_manifest() -> bytes:# Encoded after the blobs so any `unserializable_type` marks set- # by `_put_or_mark_unserializable` are reflected in the manifest.+ # by `_put_or_mark_unserializable` are reflected in the manifest,+ # and (when signing) every blob hash has been collected.+ if signing:+ assert signer is not None+ base_schema = CacheSchema(+ hash=cache.hash,+ cache_type=cache_type_enum,+ stateful_refs=list(cache.stateful_refs),+ defs=defs_dict,+ meta=Meta(+ version=version,+ return_value=return_item,+ blob_hashes=blob_hashes,+ signer_public_key=signer.public_key_pem(),+ signature=None,+ ),+ ui_defs=ui_defs_list,+ )+ sig = signer.sign(_signable_bytes(base_schema))+ signed_meta = msgspec.structs.replace(+ base_schema.meta, signature=sig+ )+ return msgspec.json.encode(+ msgspec.structs.replace(base_schema, meta=signed_meta)+ )return msgspec.json.encode(CacheSchema(hash=cache.hash,@@ -798,10 +1492,14 @@ class LazyLoader(BasePersistenceLoader):instead mark each manifest `Item` with `unserializable_type`.Returns `True` when the blob was stored, `False` when it was- marked unserializable.+ marked unserializable. Records the blob digest for the signed+ manifest when the loader is signing."""try:- store.put(key, serialize(value))+ data = serialize(value)+ store.put(key, data)+ if signing:+ blob_hashes[key] = _sha256hex(data)except Exception as e:LOGGER.warning("Failed to serialize %s for cache; marking "@@ -868,7 +1566,8 @@ class LazyLoader(BasePersistenceLoader):var,)# Manifest last — readers check for it to detect complete- # writes, and it now carries any unserializable marks set above.+ # writes, and it now carries any unserializable marks set above+ # plus (when signing) the signed blob hashes and signature.store.put(manifest_key, _encode_manifest())except Exception:LOGGER.exception("Failed to write cache blobs for %s", path)@@ -900,17 +1599,26 @@ class WasmLazyLoader(LazyLoader):ref_type_hints: dict[str, str | None],return_ref: str | None,return_type_hint: str | None,+ blob_hash_map: dict[str, str] | None = None,+ effective_signer: CacheSigner | None = None,) -> dict[str, Any]:unpickled: dict[str, Any] = {}# The store handles concurrency (HTTP batch fetch in WASM). The WASM# variant pairs with a `WasmLazyStore` (see `_store_cls`), whose# `get_batch` fetches concurrently; `get_batch` is defined on every- # `Store` so no narrowing is needed.+ # `Store` so no narrowing is needed. A signed-hash mismatch raises+ # CacheSignatureError straight out of `_deserialize_blob`.for key, data in self.store.get_batch(unique_keys):if not data:- raise FileNotFoundError("Incomplete cache: missing blobs")+ raise _incomplete_cache_error(effective_signer)unpickled[key] = self._deserialize_blob(- key, data, ref_type_hints, return_ref, return_type_hint+ key,+ data,+ ref_type_hints,+ return_ref,+ return_type_hint,+ blob_hash_map,+ effective_signer,)return unpickleddiff --git a/marimo/_save/signing.py b/marimo/_save/signing.pynew file mode 100644index 0000000000..bb7f961229--- /dev/null+++ b/marimo/_save/signing.py@@ -0,0 +1,402 @@+# Copyright 2026 Marimo. All rights reserved.+"""Ed25519 signing and blob-hash verification for LazyLoader cache manifests.++This module is importable without the `cryptography` package — all+`cryptography` imports are deferred inside methods so consumers that do not+use signing incur no import cost.+"""++from __future__ import annotations++import base64+import hashlib+from typing import Any+++class CacheSignatureError(Exception):+ """Raised when Ed25519 or blob-hash verification fails.++ Untrusted bytes are **not** returned — the error surfaces before any+ deserialization so that a poisoned cache entry cannot execute arbitrary+ code via `pickle.loads`.+ """+++def _sha256hex(data: bytes) -> str:+ """Return the hex-encoded SHA-256 digest of *data*."""+ return hashlib.sha256(data).hexdigest()+++class CacheSigner:+ """Ed25519 signing and verification for LazyLoader cache manifests.++ Private key signs; consumers only need the public key to verify.+ All `cryptography` imports are deferred so this module is importable+ without the package installed.++ Typical usage::++ from marimo._save.signing import CacheSigner, generate_keypair++ private_pem, public_pem = generate_keypair()++ # Publisher — signs on write+ writer = LazyLoader.partial(+ signer=CacheSigner.from_private_key_pem(private_pem)+ )++ # Consumer — verifies signed entries; unverifiable entries miss+ # (recompute) rather than being served (fail-safe, mode="verify")+ reader = LazyLoader.partial(+ signer=CacheSigner.from_public_key_pem(public_pem)+ )++ # Consumer — strict: raises on any unsigned/unverifiable entry+ reader_strict = LazyLoader.partial(+ signer=CacheSigner.from_public_key_pem(public_pem),+ mode="strict",+ )++ Keys can also be loaded from environment variables::++ loader = LazyLoader.partial(signer=CacheSigner.from_env())+ """++ def __init__(+ self,+ private_key: Any = None,+ public_key: Any = None,+ ) -> None:+ if private_key is None and public_key is None:+ raise ValueError(+ "CacheSigner requires at least one of private_key or public_key"+ )+ self._private_key: Any = private_key+ self._public_key: Any = (+ public_key if public_key is not None else private_key.public_key()+ )++ @property+ def can_sign(self) -> bool:+ """True when a private key is available for signing."""+ return self._private_key is not None++ def sign(self, data: bytes) -> str:+ """Sign *data* and return a base64url-encoded Ed25519 signature."""+ if self._private_key is None:+ raise ValueError("Cannot sign: no private key configured")+ return base64.urlsafe_b64encode(self._private_key.sign(data)).decode()++ def verify(self, data: bytes, signature: str) -> None:+ """Verify *signature* against *data*.++ Raises :class:`CacheSignatureError` when the signature is invalid,+ including when the signature string is not valid base64.+ """+ import binascii++ from cryptography.exceptions import InvalidSignature++ try:+ # validate=True so a malformed signature raises deterministically+ # here rather than decoding to junk that fails verification later.+ sig_bytes = base64.b64decode(+ signature, altchars=b"-_", validate=True+ )+ except (binascii.Error, ValueError) as e:+ raise CacheSignatureError(+ "A cache entry could not be verified — its signature field is "+ "not readable. The cached data may be corrupted or was edited "+ "outside of marimo.\n"+ "To recover, call cache_clear() on the cached function or "+ "context manager."+ ) from e++ try:+ self._public_key.verify(sig_bytes, data)+ except InvalidSignature as e:+ raise CacheSignatureError(+ "A cache entry's signature does not match its contents — the "+ "cached data may be corrupted or was modified outside of "+ "marimo.\n"+ "To recover, call cache_clear() on the cached function or "+ "context manager."+ ) from e++ def verify_blob(+ self, blob_key: str, blob_bytes: bytes, expected_hex: str+ ) -> None:+ """Verify that *blob_bytes* match the signed hash *expected_hex*.++ Raises :class:`CacheSignatureError` when the hashes differ. This is+ called **before** `pickle.loads` so that a tampered blob cannot+ execute arbitrary code.+ """+ actual = _sha256hex(blob_bytes)+ if actual != expected_hex:+ raise CacheSignatureError(+ f"A cached file's contents don't match the expected checksum "+ f"(file: {blob_key!r}). The data may be corrupted or was "+ f"modified outside of marimo.\n"+ f"To recover, call cache_clear() on the cached function or "+ f"context manager."+ )++ def fingerprint(self) -> str:+ """Return the SSH-style SHA-256 fingerprint of this signer's key.++ The single trust primitive: two signers with the same fingerprint hold+ the same public key. See the module-level :func:`fingerprint`.+ """+ return fingerprint(self.public_key_pem())++ @classmethod+ def from_private_key_pem(cls, pem: str) -> CacheSigner:+ """Load a signer from a PEM-encoded Ed25519 private key.++ Raises `ValueError` if the PEM is not an Ed25519 key — a non-Ed25519+ key would otherwise load fine and only fail later at `sign()`/+ `verify()` (surfacing as a generic cache miss).+ """+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (+ Ed25519PrivateKey,+ )+ from cryptography.hazmat.primitives.serialization import (+ load_pem_private_key,+ )++ private_key = load_pem_private_key(pem.encode(), password=None)+ if not isinstance(private_key, Ed25519PrivateKey):+ raise ValueError(+ "Cache signing requires an Ed25519 private key, got "+ f"{type(private_key).__name__}."+ )+ return cls(private_key=private_key)++ @classmethod+ def from_public_key_pem(cls, pem: str) -> CacheSigner:+ """Load a verifier from a PEM-encoded Ed25519 public key.++ Raises `ValueError` if the PEM is not an Ed25519 key.+ """+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (+ Ed25519PublicKey,+ )+ from cryptography.hazmat.primitives.serialization import (+ load_pem_public_key,+ )++ public_key = load_pem_public_key(pem.encode())+ if not isinstance(public_key, Ed25519PublicKey):+ raise ValueError(+ "Cache signing requires an Ed25519 public key, got "+ f"{type(public_key).__name__}."+ )+ return cls(public_key=public_key)++ @classmethod+ def from_env(+ cls,+ private_key_env: str = "MARIMO_CACHE_SIGNING_PRIVATE_KEY",+ public_key_env: str = "MARIMO_CACHE_SIGNING_PUBLIC_KEY",+ ) -> CacheSigner | None:+ """Construct a signer from environment variables.++ Returns `None` when neither variable is set so callers can write::++ signer = CacheSigner.from_env()+ loader = LazyLoader.partial(signer=signer)+ """+ import os++ if pem := os.environ.get(private_key_env):+ return cls.from_private_key_pem(pem)+ if pem := os.environ.get(public_key_env):+ return cls.from_public_key_pem(pem)+ return None++ def public_key_pem(self) -> str:+ """Return the PEM-encoded public key."""+ from cryptography.hazmat.primitives.serialization import (+ Encoding,+ PublicFormat,+ )++ result: str = self._public_key.public_bytes(+ Encoding.PEM, PublicFormat.SubjectPublicKeyInfo+ ).decode()+ return result++ def private_key_pem(self) -> str:+ """Return the PEM-encoded private key.++ Raises `ValueError` when only a public key was provided.+ """+ from cryptography.hazmat.primitives.serialization import (+ Encoding,+ NoEncryption,+ PrivateFormat,+ )++ if self._private_key is None:+ raise ValueError("No private key available")+ result: str = self._private_key.private_bytes(+ Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()+ ).decode()+ return result+++def fingerprint(public_key_pem: str) -> str:+ """Return the SSH-style SHA-256 fingerprint of an Ed25519 public key PEM.++ Format: `"SHA256:" + base64(sha256(DER SubjectPublicKeyInfo))` with the+ trailing base64 padding stripped, matching how OpenSSH presents key+ fingerprints. This is the single trust primitive — config lists and the+ per-loader `trusted_signers` set hold these strings, while the full key+ travels in the manifest, so a compact fingerprint pins a full key without+ bloating configuration.++ Raises `ValueError` when *public_key_pem* is not an Ed25519 public key.+ """+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (+ Ed25519PublicKey,+ )+ from cryptography.hazmat.primitives.serialization import (+ Encoding,+ PublicFormat,+ load_pem_public_key,+ )++ key = load_pem_public_key(public_key_pem.encode())+ if not isinstance(key, Ed25519PublicKey):+ raise ValueError(+ "Cache signing requires an Ed25519 public key, got "+ f"{type(key).__name__}."+ )+ der = key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)+ return "SHA256:" + base64.b64encode(+ hashlib.sha256(der).digest()+ ).decode().rstrip("=")+++def generate_keypair() -> tuple[str, str]:+ """Generate an Ed25519 key pair for cache signing.++ Returns `(private_key_pem, public_key_pem)`. Keep the private key+ secret; distribute the public key to cache consumers.++ Example::++ private_pem, public_pem = generate_keypair()+ # Store private_pem securely; share public_pem with readers.+ """+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (+ Ed25519PrivateKey,+ )++ key = Ed25519PrivateKey.generate()+ signer = CacheSigner(private_key=key)+ return signer.private_key_pem(), signer.public_key_pem()+++def _get_default_signer(auto_generate: bool = True) -> CacheSigner | None:+ """Resolve the default cache signer for this session.++ Resolution order:++ 1. `MARIMO_CACHE_SIGNING_PRIVATE_KEY` env var → private-key signer+ 2. `MARIMO_CACHE_SIGNING_PUBLIC_KEY` env var → public-key (verify-only) signer+ 3. `marimo_state_dir() / "cache_signing_key.pem"` → load saved private key+ 4. 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.+ """+ import logging++ from marimo._dependencies.dependencies import DependencyManager++ if not DependencyManager.cryptography.has():+ return None++ # 1 & 2: env vars take precedence+ signer = CacheSigner.from_env()+ if signer is not None:+ return signer++ if not auto_generate:+ return None++ # 3 & 4: key file in the marimo state directory+ import os+ import stat++ from marimo._utils.xdg import marimo_state_dir++ key_path = marimo_state_dir() / "cache_signing_key.pem"+ if key_path.exists():+ try:+ signer = CacheSigner.from_private_key_pem(key_path.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)+ except OSError:+ pass+ return signer+ except Exception:+ logging.getLogger("marimo").warning(+ "Failed to load cache signing key from %s; "+ "generating a new one.",+ key_path,+ )++ # Auto-generate and persist atomically (write to temp, rename).+ # os.replace is atomic on POSIX; if two processes race, the last rename+ # wins. We then load the key that actually landed on disk (rather than the+ # one we generated), so a process that lost the race still uses the winning+ # key this session and can verify caches written by the winner.+ import tempfile++ try:+ private_pem, _ = generate_keypair()+ key_path.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp = tempfile.mkstemp(+ dir=key_path.parent, prefix=".cache_key_", suffix=".tmp"+ )+ closed = False+ try:+ os.write(fd, private_pem.encode())+ os.close(fd)+ closed = True+ os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR)+ os.replace(tmp, str(key_path))+ except BaseException:+ if not closed:+ os.close(fd)+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+ logging.getLogger("marimo").info(+ "Generated cache signing key: %s", key_path+ )+ # 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())+ 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,+ )+ return Nonediff --git a/marimo/_save/stubs/lazy_stub.py b/marimo/_save/stubs/lazy_stub.pyindex 0a3e947645..6d0fdd4046 100644--- a/marimo/_save/stubs/lazy_stub.py+++ b/marimo/_save/stubs/lazy_stub.py@@ -29,10 +29,18 @@ class CacheType(Enum):UNKNOWN = "Unknown"-class Item(msgspec.Struct):+class Item(msgspec.Struct, omit_defaults=True):"""Represents a cached item with different value types.Only one of the value fields should be set (oneof semantics).++ `omit_defaults` keeps the encoded manifest — and therefore the signature+ computed over it — stable when a new optional field (default `None`/+ empty) is added: an entry that doesn't set the field encodes identically+ before and after the field exists. Any change that is *not* purely+ additive-with-an-absent-default (reordering, renaming, changing a default,+ adding a required field) alters the signable bytes and MUST bump+ `MARIMO_CACHE_VERSION`."""primitive: Any | None = None@@ -60,6 +68,11 @@ class Item(msgspec.Struct):unserializable_type: str | None = None# Pinned version of a `module` def, captured at cache time.module_version: str | None = None+ # Non-finite float token ("nan"/"inf"/"-inf"), stored inline rather than via+ # `primitive`: msgspec encodes non-finite floats as JSON `null`, which both+ # corrupts the value and breaks signature verification (the re-encoded+ # manifest drops the null field).+ special_float: str | None = Nonedef __post_init__(self) -> None:fields_set = sum(@@ -72,6 +85,7 @@ class Item(msgspec.Struct):self.function,self.class_def,self.unserializable_type,+ self.special_float,]if field is not None)@@ -79,12 +93,24 @@ class Item(msgspec.Struct):raise ValueError("Item can only have one value field set")-class Meta(msgspec.Struct):+class Meta(msgspec.Struct, omit_defaults=True):version: intreturn_value: Item | None = None---class Cache(msgspec.Struct):+ # Maps each blob store-key to its SHA-256 hex digest. Covered by the+ # Ed25519 signature (which is computed over the manifest with the+ # signature field cleared), so blob hashes are implicitly authenticated.+ blob_hashes: dict[str, str] = msgspec.field(default_factory=dict)+ # PEM-encoded Ed25519 public key of the signer. Included in the signed+ # bytes (NOT stripped by _signable_bytes), so an attacker cannot swap+ # the claimed key without invalidating the signature.+ signer_public_key: str | None = None+ # --- Envelope field (stripped before signing) ---+ # Base64url-encoded Ed25519 signature over _signable_bytes() of this+ # manifest (signature=None). None means the entry is unsigned.+ signature: str | None = None+++class Cache(msgspec.Struct, omit_defaults=True):hash: strcache_type: CacheTypedefs: dict[str, Item]diff --git a/marimo/_smoke_tests/lazy_cache_example.py b/marimo/_smoke_tests/lazy_cache_example.pynew file mode 100644index 0000000000..ddaa6ed960--- /dev/null+++ b/marimo/_smoke_tests/lazy_cache_example.py@@ -0,0 +1,169 @@+import marimo++__generated_with = "0.23.1"+app = marimo.App(width="medium")++with app.setup:+ import marimo as mo++[email protected](hide_code=True)+def _():+ mo.md(r"""+ # Lazy Cache Signing Smoke Test++ This notebook exercises the Ed25519 cache-signing feature built into+ `LazyLoader`. Signing is **automatic** when the `cryptography` package is+ installed — no configuration required.++ > **Prereq:** `uv sync --extra signing`++ On first run, marimo generates a per-user Ed25519 key and saves it to+ `~/.local/state/marimo/cache_signing_key.pem`. Subsequent runs load the+ saved key and verify every cache entry before unpickling.+ """)+ return++[email protected](hide_code=True)+def _():+ mo.md("""+ ## 1 — Context-manager form (`mo.persistent_cache`)+ """)+ return++[email protected](hide_code=True)+def _():+ with mo.persistent_cache("signing_demo_ctx", method="lazy"):+ ctx_result = sum(i**2 for i in range(100_000))++ mo.md(f"**ctx_result** = `{ctx_result}`")+ return++[email protected](hide_code=True)+def _():+ mo.md("""+ ## 2 — Decorator form (`mo.persistent_cache`)+ """)+ return++[email protected](hide_code=True)+def _():+ @mo.persistent_cache(method="lazy")+ def expensive(n: int) -> int:+ return sum(i**2 for i in range(n))+++ dec_result = expensive(100_000)+ mo.md(f"**expensive(100 000)** = `{dec_result}`")+ return++[email protected](hide_code=True)+def _():+ mo.md("""+ ## 3 — Where is the signing key?++ marimo resolves the key in this order:++ 1. `MARIMO_CACHE_SIGNING_PRIVATE_KEY` env var+ 2. `MARIMO_CACHE_SIGNING_PUBLIC_KEY` env var+ 3. `<marimo_state_dir>/cache_signing_key.pem` — loaded or auto-generated+ """)+ return++[email protected](hide_code=True)+def _():+ from marimo._utils.xdg import marimo_state_dir++ _key_path = marimo_state_dir() / "cache_signing_key.pem"+ mo.md(f"""+ **Key file:** `{_key_path}`++ **Exists:** `{_key_path.exists()}`+ """)+ return++[email protected](hide_code=True)+def _():+ mo.md("""+ ## 4 — Custom key via env vars++ For shared infrastructure (e.g. a Redis cache written by CI and read by+ notebook users), set env vars before starting marimo:++ ```bash+ export MARIMO_CACHE_SIGNING_PRIVATE_KEY="$(cat private_key.pem)"+ # consumers — public key only:+ export MARIMO_CACHE_SIGNING_PUBLIC_KEY="$(cat public_key.pem)"+ ```++ Use `generate_keypair()` to create a fresh key pair:+ """)+ return++[email protected](hide_code=True)+def _():+ from marimo._save.signing import generate_keypair++ _priv, _pub = generate_keypair()+ mo.md(f"""+ ```+ # private key (keep secret)+ {_priv[:64].strip()}...++ # public key (share with consumers)+ {_pub.strip()}+ ```+ """)+ return++[email protected](hide_code=True)+def _():+ mo.md("""+ ## 5 — NumPy & Pandas: external serializers work with signing+ """)+ return++[email protected](hide_code=True)+def _():+ import numpy as np++ with mo.persistent_cache("signed_numpy_demo", method="lazy") as _c:+ arr = np.random.rand(1_000)+ mean_val = arr.mean()++ # _c.cache_clear()+ mo.md(f"NumPy array (first 3): `{arr[:3]}`, mean=`{mean_val:.4f}` ✅")+ return++[email protected](hide_code=True)+def _():+ import pandas as pd++ with mo.persistent_cache("signed_pandas", method="lazy") as _c:+ df = pd.DataFrame({"x": range(10), "y": [i**2 for i in range(10)]})++ # Leave the cache in place so a re-run exercises the signed-load + verify+ # path; uncomment to force a fresh write instead.+ # _c.cache_clear()+ mo.md(f"DataFrame shape: `{df.shape}` | head: `{df.head(2).to_dict()!r}` ✅")+ return+++def _():+ return+++if __name__ == "__main__":+ app.run()diff --git a/pyproject.toml b/pyproject.tomlindex 5e94a971eb..83cb1c38fc 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -102,6 +102,7 @@ sandbox = [recommended = ["marimo[sql]","marimo[sandbox]", # For `marimo edit --sandbox DIRECTORY`+ "cryptography>=42.0.0", # Ed25519 signing of persistent cache manifests"altair>=5.4.0", # Plotting in datasource viewer"pydantic-ai-slim[openai]>=1.107.0,<3.0.0", # AI features"ruff", # Formattingdiff --git a/tests/_save/loaders/test_lazy_signing.py b/tests/_save/loaders/test_lazy_signing.pynew file mode 100644index 0000000000..9b75ebcd50--- /dev/null+++ b/tests/_save/loaders/test_lazy_signing.py@@ -0,0 +1,1186 @@+# Copyright 2026 Marimo. All rights reserved.+"""Integration tests for LazyLoader cache signing."""++from __future__ import annotations++import pickle+import tempfile+from pathlib import Path+from typing import Any++import msgspec+import pytest++pytest.importorskip("cryptography", reason="cryptography not installed")++from marimo._save.cache import MARIMO_CACHE_VERSION, Cache+from marimo._save.hash import HashKey+from marimo._save.loaders import LazyLoader+from marimo._save.signing import (+ CacheSignatureError,+ CacheSigner,+ _sha256hex,+ fingerprint,+ generate_keypair,+)+from marimo._save.stores.file import FileStore+from marimo._save.stubs.lazy_stub import (+ Cache as CacheSchema,+ CacheType,+ Item,+ Meta,+)+from tests._save.store.mocks import MockStore+++# Module-level class so pickle can resolve it.+class _Point:+ def __init__(self, x: int, y: int) -> None:+ self.x, self.y = x, y+++# ---------------------------------------------------------------------------+# Fixtures / helpers+# ---------------------------------------------------------------------------+++def key(h: str, cache_type: str = "Pure") -> HashKey:+ return HashKey(h, cache_type)+++def _simple_cache(hash_val: str = "abc123", **defs: Any) -> Cache:+ if not defs:+ defs = {"x": 42, "msg": "hello"}+ return Cache(+ defs=defs,+ hash=hash_val,+ cache_type="Pure",+ stateful_refs=set(),+ hit=False,+ meta={"version": MARIMO_CACHE_VERSION},+ )+++def _keypair() -> tuple[CacheSigner, CacheSigner]:+ """Return (full_signer_with_private, verifier_with_public_only)."""+ private_pem, public_pem = generate_keypair()+ return (+ CacheSigner.from_private_key_pem(private_pem),+ CacheSigner.from_public_key_pem(public_pem),+ )+++# ---------------------------------------------------------------------------+# Round-trip tests+# ---------------------------------------------------------------------------+++class _FileStoreLoaderTest:+ """Shared scaffolding: a temp-dir FileStore and a loader factory over it."""++ def setup_method(self) -> None:+ self.temp_dir = tempfile.TemporaryDirectory()+ self.store = FileStore(save_path=self.temp_dir.name)++ def teardown_method(self) -> None:+ self.temp_dir.cleanup()++ def _loader(self, **kwargs: Any) -> LazyLoader:+ return LazyLoader("test", store=self.store, **kwargs)+++class TestSignedRoundTrip(_FileStoreLoaderTest):+ def test_signer_and_mode_settable_via_setattr(self) -> None:+ """Reconfiguring via setattr (as LoaderPartial.create_or_reconfigure+ does) works for signer and mode."""+ 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")+ assert loader.signer is None+ assert loader.mode == "off"++ loader.signer = signer+ loader.mode = "verify"+ assert loader._signer is signer+ assert loader._mode == "verify"++ # Full round-trip with the reconfigured signer+ cache = _simple_cache(hash_val="reconfig_hash", v=99)+ assert loader.save_cache(cache)+ loader.flush()++ reader = self._loader(signer=verifier)+ loaded = reader.load_cache(key("reconfig_hash"))+ assert loaded is not None+ assert loaded.defs["v"] == 99++ def test_reconfigure_unset_signer_does_not_automint_for_shared_store(+ self,+ ) -> None:+ """Re-setting the signer to unset on a non-local (shared) store must+ not auto-generate a machine-local key when the deferred resolution+ fires — only explicit/env keys apply, matching __init__'s+ local-vs-shared distinction. The setter stores the sentinel unresolved;+ resolution happens lazily on the first `signer` property access."""+ from unittest import mock++ from marimo._save.loaders.lazy import _SIGNER_UNSET++ loader = LazyLoader(+ "ns", store=MockStore(), signer=None, mode="verify"+ )+ with mock.patch(+ "marimo._save.loaders.lazy._get_default_signer"+ ) as gds:+ gds.return_value = None+ loader.signer = _SIGNER_UNSET+ # Setter defers: nothing resolved yet.+ gds.assert_not_called()+ # Property access (non-off mode) triggers the single resolution.+ _ = loader.signer+ gds.assert_called_once()+ assert gds.call_args.kwargs.get("auto_generate") is False++ def test_default_round_trip(self) -> None:+ """The default loader auto-resolves a local signing key, so a plain+ save/load round-trips (signs on write, verifies own key on read)."""+ loader = self._loader()+ cache = _simple_cache()+ assert loader.save_cache(cache)+ loader.flush()++ loaded = loader.load_cache(key("abc123"))+ assert loaded is not None+ assert loaded.defs["x"] == 42+ assert loaded.defs["msg"] == "hello"++ def test_signed_round_trip(self) -> None:+ """Full signer → save signs, load with public key verifies (a loader+ trusts its own key's fingerprint, so no trusted_signers needed)."""+ signer, verifier = _keypair()++ writer = self._loader(signer=signer)+ cache = _simple_cache(hash_val="signed_hash", x=99, label="signed")+ assert writer.save_cache(cache)+ writer.flush()++ reader = self._loader(signer=verifier)+ loaded = reader.load_cache(key("signed_hash"))+ assert loaded is not None+ assert loaded.defs["x"] == 99+ assert loaded.defs["label"] == "signed"++ def test_signed_round_trip_with_pickle_object(self) -> None:+ """Pickle blobs are hash-verified before deserialization."""+ signer, verifier = _keypair()++ pt = _Point(3, 4)+ writer = self._loader(signer=signer)+ cache = _simple_cache(hash_val="pt_hash", pt=pt)+ assert writer.save_cache(cache)+ writer.flush()++ reader = self._loader(signer=verifier)+ loaded = reader.load_cache(key("pt_hash"))+ assert loaded is not None+ result = loaded.defs["pt"]+ assert result.x == 3+ assert result.y == 4++ def test_self_verify_with_private_key(self) -> None:+ """A loader with a private-key signer can also verify its own entries."""+ signer, _ = _keypair()+ loader = self._loader(signer=signer)++ cache = _simple_cache(hash_val="self_verify", val=7)+ assert loader.save_cache(cache)+ loader.flush()++ loaded = loader.load_cache(key("self_verify"))+ assert loaded is not None+ assert loaded.defs["val"] == 7++ def test_trusted_third_party_direct_signer(self) -> None:+ """A reader trusts a third party's direct signature by adding the+ writer's fingerprint to trusted_signers (reader has no own key)."""+ signer, verifier = _keypair()+ writer = self._loader(signer=signer)+ writer.save_cache(_simple_cache(hash_val="third_party", n=5))+ writer.flush()++ reader = self._loader(+ signer=None, trusted_signers={verifier.fingerprint()}+ )+ loaded = reader.load_cache(key("third_party"))+ assert loaded is not None+ assert loaded.defs["n"] == 5++ def test_mock_store_signed_round_trip(self) -> None:+ """Works with any Store backend (MockStore here)."""+ signer, verifier = _keypair()+ store = MockStore()++ writer = LazyLoader("ns", store=store, signer=signer)+ cache = _simple_cache(hash_val="mock_hash", n=123)+ assert writer.save_cache(cache)+ writer.flush()++ reader = LazyLoader("ns", store=store, signer=verifier)+ loaded = reader.load_cache(key("mock_hash"))+ assert loaded is not None+ assert loaded.defs["n"] == 123+++# ---------------------------------------------------------------------------+# Unsigned-entry behavior (mode-governed)+# ---------------------------------------------------------------------------+++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")+ cache = _simple_cache(hash_val=hash_val, z=55)+ assert loader.save_cache(cache)+ loader.flush()++ 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")+ loaded = loader.load_cache(key("unsigned_hash"))+ assert loaded is not None+ assert loaded.defs["z"] == 55++ def test_unsigned_misses_in_verify_mode(self) -> None:+ """verify mode (default): an unsigned entry is unverifiable, so it+ misses (fail-safe) rather than being served."""+ self._write_unsigned()+ _, verifier = _keypair()+ loader = self._loader(signer=verifier) # mode="verify" default+ assert loader.load_cache(key("unsigned_hash")) is None++ def 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")+ with pytest.raises(CacheSignatureError, match="unsigned"):+ loader.load_cache(key("unsigned_hash"))++ def test_verify_only_signer_write_is_skipped_and_warns(self) -> None:+ """A verify-only signer (no private key) in verify mode cannot sign, so+ the write is skipped (no unsigned entry written) and a warning logged."""+ from unittest.mock import patch++ _, verifier = _keypair()+ loader = self._loader(signer=verifier) # verify mode, no private key+ cache = _simple_cache(hash_val="warn_hash", z=1)+ with patch("marimo._save.loaders.lazy.LOGGER") as mock_log:+ assert loader.save_cache(cache) is False+ loader.flush()+ warning_msgs = [str(call) for call in mock_log.warning.call_args_list]+ assert any("cannot sign" in msg.lower() for msg in warning_msgs)+ # Nothing was written.+ assert self.store.get(str(loader.build_path(key("warn_hash")))) is None+++# ---------------------------------------------------------------------------+# Tampering tests+# ---------------------------------------------------------------------------+++class TestTampering(_FileStoreLoaderTest):+ def _write_signed(+ self, hash_val: str = "tamper_hash", **defs: Any+ ) -> CacheSigner:+ if not defs:+ defs = {"v": 1}+ signer, _ = _keypair()+ loader = LazyLoader("test", store=self.store, signer=signer)+ cache = _simple_cache(hash_val=hash_val, **defs)+ loader.save_cache(cache)+ loader.flush()+ return signer++ def _read_loader(self, signer: CacheSigner, **kwargs: Any) -> LazyLoader:+ # Build a verifier from the same public key+ verifier = CacheSigner.from_public_key_pem(signer.public_key_pem())+ return LazyLoader("test", store=self.store, signer=verifier, **kwargs)++ def test_tampered_manifest_raises(self) -> None:+ """Flipping a byte in the manifest invalidates the Ed25519 signature.+ In strict mode this raises rather than degrading to miss."""+ signer = self._write_signed(hash_val="manip_manifest")++ # Locate and corrupt the manifest file+ manifest_key = str(+ LazyLoader("test", store=self.store, mode="off").build_path(+ key("manip_manifest")+ )+ )+ raw = self.store.get(manifest_key)+ assert raw is not None+ # Decode, mutate, re-encode without updating the signature+ schema = msgspec.json.decode(raw, type=CacheSchema)+ tampered_meta = msgspec.structs.replace(schema.meta, version=9999)+ tampered = msgspec.json.encode(+ msgspec.structs.replace(schema, meta=tampered_meta)+ )+ self.store.put(manifest_key, tampered)++ reader = self._read_loader(signer, mode="strict")+ with pytest.raises(CacheSignatureError):+ reader.load_cache(key("manip_manifest"))++ def test_tampered_blob_raises_before_unpickling(self) -> None:+ """A replaced blob raises CacheSignatureError before pickle.loads."""+ signer = self._write_signed(+ hash_val="blob_tamper", secret={"key": "val"}+ )++ # Find the pickle blob and overwrite it with a different payload+ blob_dir = Path(self.temp_dir.name) / "test" / "blob_tamper"+ blobs = list(blob_dir.glob("*.pickle"))+ assert blobs, "expected a .pickle blob"+ evil_bytes = pickle.dumps({"injected": True})+ blobs[0].write_bytes(evil_bytes)++ reader = self._read_loader(signer, mode="strict")+ with pytest.raises(CacheSignatureError, match="checksum"):+ reader.load_cache(key("blob_tamper"))++ def test_signature_error_not_swallowed_by_load_cache(self) -> None:+ """load_cache re-raises CacheSignatureError in strict mode."""+ signer = self._write_signed(hash_val="sig_swallow")++ manifest_key = str(+ LazyLoader("test", store=self.store, mode="off").build_path(+ key("sig_swallow")+ )+ )+ raw = self.store.get(manifest_key)+ assert raw is not None+ schema = msgspec.json.decode(raw, type=CacheSchema)+ tampered_meta = msgspec.structs.replace(schema.meta, version=0)+ tampered = msgspec.json.encode(+ msgspec.structs.replace(schema, meta=tampered_meta)+ )+ self.store.put(manifest_key, tampered)++ reader = self._read_loader(signer, mode="strict")+ # Must raise, not return None+ with pytest.raises(CacheSignatureError):+ reader.load_cache(key("sig_swallow"))++ def test_bad_signature_degrades_to_miss_in_verify_mode(self) -> None:+ """In verify mode a tampered manifest returns None (cache miss)."""+ signer = self._write_signed(hash_val="verify_tamper")++ manifest_key = str(+ LazyLoader("test", store=self.store, mode="off").build_path(+ key("verify_tamper")+ )+ )+ raw = self.store.get(manifest_key)+ assert raw is not None+ schema = msgspec.json.decode(raw, type=CacheSchema)+ tampered_meta = msgspec.structs.replace(schema.meta, version=9999)+ tampered = msgspec.json.encode(+ msgspec.structs.replace(schema, meta=tampered_meta)+ )+ self.store.put(manifest_key, tampered)++ # verify mode (default) — degrade to cache miss+ reader = self._read_loader(signer)+ assert reader.load_cache(key("verify_tamper")) is None++ def test_wrong_key_cannot_verify(self) -> None:+ """An entry signed by key A cannot be verified by key B."""+ signer_a, _ = _keypair()+ _, verifier_b = _keypair()++ writer = LazyLoader("test", store=self.store, signer=signer_a)+ cache = _simple_cache(hash_val="wrong_key", val=1)+ writer.save_cache(cache)+ writer.flush()++ reader = LazyLoader(+ "test", store=self.store, signer=verifier_b, mode="strict"+ )+ with pytest.raises(CacheSignatureError):+ reader.load_cache(key("wrong_key"))++ def test_foreign_key_misses_in_verify_mode(self) -> None:+ """A different key's signature does not verify against this loader's+ key, so the entry misses (recomputes) rather than being served+ unverified — even in verify mode. Sharing a cache across machines+ requires a shared/trusted key, not silent acceptance."""+ signer_a, _ = _keypair()+ _, verifier_b = _keypair()++ writer = LazyLoader("test", store=self.store, signer=signer_a)+ writer.save_cache(_simple_cache(hash_val="foreign_ok", val=7))+ writer.flush()++ # verify mode (default) with an unrelated key B: the foreign signature+ # fails verification -> fail-safe cache miss.+ reader = LazyLoader("test", store=self.store, signer=verifier_b)+ assert reader.load_cache(key("foreign_ok")) is None++ def test_signed_manifest_missing_blob_hash_rejected(self) -> None:+ """A validly-signed manifest that omits the integrity hash for a blob+ it references is rejected (writer-drift / integrity-bypass guard),+ rather than letting the blob reach pickle.loads unverified."""+ from marimo._save.loaders.lazy import _signable_bytes++ 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")+ )+ )+ raw = self.store.get(manifest_key)+ assert raw is not None+ schema = msgspec.json.decode(raw, type=CacheSchema)+ # Drop one referenced blob's hash, then re-sign so the manifest+ # signature itself remains valid (the attack we guard against is a+ # signed-but-hash-incomplete manifest, not a broken signature).+ blob_key = next(iter(schema.meta.blob_hashes))+ pruned = {+ k: v for k, v in schema.meta.blob_hashes.items() if k != blob_key+ }+ base_meta = msgspec.structs.replace(+ schema.meta, blob_hashes=pruned, signature=None+ )+ base = msgspec.structs.replace(schema, meta=base_meta)+ sig = signer.sign(_signable_bytes(base))+ resigned = msgspec.json.encode(+ msgspec.structs.replace(+ base, meta=msgspec.structs.replace(base_meta, signature=sig)+ )+ )+ self.store.put(manifest_key, resigned)++ reader = self._read_loader(signer, mode="strict")+ with pytest.raises(CacheSignatureError, match="integrity hash"):+ reader.load_cache(key("missing_hash"))++ def test_manifest_hash_mismatch_misses_before_blob_io(self) -> None:+ """A manifest whose internal hash disagrees with its store path is a+ corrupt/misfiled entry: miss before fetching any blob (otherwise the+ mismatch is only caught after every blob is pickle.loads()-ed)."""+ loader = LazyLoader("test", store=self.store, mode="off")+ ref = (Path("test") / "wrong" / "v.pickle").as_posix()+ manifest = msgspec.json.encode(+ CacheSchema(+ hash="different_hash",+ cache_type=CacheType.PURE,+ defs={"v": Item(reference=ref)},+ stateful_refs=[],+ meta=Meta(version=MARIMO_CACHE_VERSION),+ )+ )+ self.store.put(str(loader.build_path(key("asked_hash"))), manifest)++ fetched: list[str] = []+ orig = self.store.get++ def spy(k: str) -> Any:+ fetched.append(k)+ return orig(k)++ self.store.get = spy # type: ignore[method-assign]+ try:+ assert loader.load_cache(key("asked_hash")) is None+ finally:+ self.store.get = orig # type: ignore[method-assign]+ assert ref not in fetched+++# ---------------------------------------------------------------------------+# Blob-hash content in manifest+# ---------------------------------------------------------------------------+++class TestBlobHashesInManifest(_FileStoreLoaderTest):+ def test_unsigned_manifest_has_empty_blob_hashes(self) -> None:+ loader = LazyLoader("test", store=self.store, signer=None, mode="off")+ cache = _simple_cache(hash_val="no_hashes", x=1)+ loader.save_cache(cache)+ loader.flush()++ manifest_key = str(loader.build_path(key("no_hashes")))+ raw = self.store.get(manifest_key)+ schema = msgspec.json.decode(raw, type=CacheSchema)+ assert schema.meta.blob_hashes == {}+ assert schema.meta.signature is None+ assert schema.meta.signer_public_key is None++ def test_signed_manifest_has_blob_hashes_and_signature(self) -> None:+ signer, _ = _keypair()+ loader = LazyLoader("test", store=self.store, signer=signer)+ cache = _simple_cache(hash_val="with_hashes", obj={"a": 1})+ loader.save_cache(cache)+ loader.flush()++ manifest_key = str(loader.build_path(key("with_hashes")))+ raw = self.store.get(manifest_key)+ schema = msgspec.json.decode(raw, type=CacheSchema)+ # Blob hashes should be populated+ assert len(schema.meta.blob_hashes) > 0+ # Each value is a 64-char hex string+ for h in schema.meta.blob_hashes.values():+ assert len(h) == 64+ # Signature and public key present+ assert schema.meta.signature is not None+ assert schema.meta.signer_public_key is not None+ assert "PUBLIC KEY" in schema.meta.signer_public_key++ def test_blob_hashes_match_actual_blobs(self) -> None:+ signer, _ = _keypair()+ loader = LazyLoader("test", store=self.store, signer=signer)+ cache = _simple_cache(hash_val="verify_hash_content", n=42)+ loader.save_cache(cache)+ loader.flush()++ manifest_key = str(loader.build_path(key("verify_hash_content")))+ raw = self.store.get(manifest_key)+ schema = msgspec.json.decode(raw, type=CacheSchema)++ for blob_key, expected_hex in schema.meta.blob_hashes.items():+ blob_data = self.store.get(blob_key)+ assert blob_data is not None+ assert _sha256hex(blob_data) == expected_hex+++# ---------------------------------------------------------------------------+# Signable bytes stability (regression test)+# ---------------------------------------------------------------------------+++class TestSignableBytesStability:+ """_signable_bytes must produce identical output across runs for the same+ schema. If msgspec changes field ordering or encoding, signatures written+ by one version become unverifiable by another."""++ def test_signable_bytes_strips_signature(self) -> None:+ """The signature envelope field is cleared regardless of its value."""+ from marimo._save.loaders.lazy import _signable_bytes++ meta = Meta(+ version=1,+ blob_hashes={"k": "a" * 64},+ signature="should_be_stripped",+ )+ schema = CacheSchema(+ hash="h",+ cache_type=CacheType.PURE,+ defs={},+ stateful_refs=[],+ meta=meta,+ )+ from marimo._save.loaders.lazy import _MANIFEST_SIG_CONTEXT++ out = _signable_bytes(schema)+ # Signable bytes carry a domain-separation prefix before the JSON.+ assert out.startswith(_MANIFEST_SIG_CONTEXT)+ decoded = msgspec.json.decode(+ out[len(_MANIFEST_SIG_CONTEXT) :], type=CacheSchema+ )+ assert decoded.meta.signature is None+ # Non-envelope fields preserved+ assert decoded.meta.blob_hashes == {"k": "a" * 64}+ assert decoded.meta.version == 1++ def test_signable_bytes_deterministic(self) -> None:+ """Same input always produces identical bytes."""+ from marimo._save.loaders.lazy import _signable_bytes++ meta = Meta(version=1, blob_hashes={"x": "b" * 64})+ schema = CacheSchema(+ hash="det",+ cache_type=CacheType.PURE,+ defs={},+ stateful_refs=[],+ meta=meta,+ )+ assert _signable_bytes(schema) == _signable_bytes(schema)+++# ---------------------------------------------------------------------------+# Mode + capability validation+# ---------------------------------------------------------------------------+++class TestModeAndCapabilityValidation(_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")++ 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"+ )+ assert loader.mode == "strict"++ def test_strict_with_trusted_signers_only_is_fine(self) -> None:+ _, root_pub = generate_keypair()+ loader = LazyLoader(+ "test",+ store=self.store,+ signer=None,+ trusted_signers={fingerprint(root_pub)},+ mode="strict",+ )+ assert loader.mode == "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."""+ # Write an unsigned entry.+ w = LazyLoader("test", store=self.store, signer=None, mode="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 = LazyLoader("test", store=self.store, signer=None)+ loaded = reader.load_cache(key("degrade"))+ assert loaded is not None+ assert loaded.defs["z"] == 3++ 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_bare_string_trusted_signers_raises(self) -> None:+ """A bare str would iterate into single characters — rejected."""+ with pytest.raises(TypeError, match="iterable of fingerprint"):+ LazyLoader(+ "test",+ store=self.store,+ trusted_signers="SHA256:abc", # type: ignore[arg-type]+ )++ def test_malformed_fingerprint_raises(self) -> None:+ with pytest.raises(ValueError, match="Invalid trusted_signers"):+ LazyLoader("test", store=self.store, trusted_signers={"not-a-fp"})++ def test_bad_signer_type_raises(self) -> None:+ with pytest.raises(TypeError, match="signer must be a CacheSigner"):+ LazyLoader("test", store=self.store, signer="nope") # type: ignore[arg-type]++ def test_no_cryptography_strict_raises(self) -> None:+ """strict must fail closed when cryptography is unavailable."""+ from unittest import mock++ signer, _ = _keypair()+ with mock.patch(+ "marimo._dependencies.dependencies.DependencyManager."+ "cryptography.has",+ return_value=False,+ ):+ with pytest.raises(ValueError, match="cryptography"):+ LazyLoader(+ "test", store=self.store, signer=signer, mode="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."""+ from unittest import mock++ # Write an unsigned entry (off mode).+ w = LazyLoader("test", store=self.store, signer=None, mode="off")+ w.save_cache(_simple_cache(hash_val="nocrypto", z=8))+ w.flush()++ signer, _ = _keypair()+ with mock.patch(+ "marimo._dependencies.dependencies.DependencyManager."+ "cryptography.has",+ 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+++# ---------------------------------------------------------------------------+# Review fixes: trust/sign composition, remote posture, strict hash guard,+# fingerprint normalization, frozen trust set+# ---------------------------------------------------------------------------+++class TestReviewFixes(_FileStoreLoaderTest):+ def test_trusted_signers_still_signs_own_writes_on_local_store(+ self,+ ) -> None:+ """Configuring trusted_signers must not turn off signing of our own+ writes on a local store: trust composes with signing (a loader that+ also trusts a teammate keeps its auto-resolved key and round-trips its+ own cache)."""+ _, other_pub = generate_keypair()+ loader = LazyLoader(+ "test",+ store=self.store,+ trusted_signers={fingerprint(other_pub)},+ )+ # Own signing key auto-resolved despite trusted_signers being set.+ assert loader.signer is not None+ assert loader.save_cache(_simple_cache(hash_val="compose", k=1))+ loader.flush()+ loaded = loader.load_cache(key("compose"))+ assert loaded is not None+ assert loaded.defs["k"] == 1++ def test_remote_store_verify_does_not_degrade_to_off(self) -> None:+ """On a shared/remote store, verify with no signer/trusted must NOT+ degrade to off (which would serve unverified bytes from exactly the+ backend signing protects); it stays verify, so an unsigned entry+ misses."""+ store = MockStore()+ w = LazyLoader("ns", store=store, signer=None, mode="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.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")+ 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++ def test_strict_hash_mismatch_raises(self) -> None:+ """Under strict, a manifest whose internal hash disagrees with its+ store path is a trust anomaly and must raise (fail-closed), not miss."""+ signer, _ = _keypair()+ loader = LazyLoader(+ "test", store=self.store, signer=signer, mode="strict"+ )+ manifest = msgspec.json.encode(+ CacheSchema(+ hash="different_hash",+ cache_type=CacheType.PURE,+ defs={},+ stateful_refs=[],+ meta=Meta(version=MARIMO_CACHE_VERSION),+ )+ )+ self.store.put(str(loader.build_path(key("asked_hash"))), manifest)+ with pytest.raises(CacheSignatureError, match="does not match"):+ loader.load_cache(key("asked_hash"))++ def test_fingerprint_normalization_accepts_padded_and_urlsafe(+ self,+ ) -> None:+ """A padded or urlsafe fingerprint paste is canonicalized so it still+ matches fingerprint() output (rather than validating but never+ matching → permanent silent miss)."""+ signer, _ = _keypair()+ writer = LazyLoader("test", store=self.store, signer=signer)+ writer.save_cache(_simple_cache(hash_val="norm", n=5))+ writer.flush()++ canonical = signer.fingerprint()+ body = canonical[len("SHA256:") :]+ padded = "SHA256:" + body + "=" * (-len(body) % 4)+ urlsafe = "SHA256:" + body.replace("+", "-").replace("/", "_")++ for variant in (padded, urlsafe):+ reader = LazyLoader(+ "test",+ store=self.store,+ signer=None,+ trusted_signers={variant},+ )+ assert reader.trusted_signers == {canonical}+ loaded = reader.load_cache(key("norm"))+ assert loaded is not None+ assert loaded.defs["n"] == 5++ def test_trusted_signers_property_is_frozen_copy(self) -> None:+ """The property returns a frozenset copy so mutating it cannot bypass+ _normalize_fingerprints."""+ _, pub = generate_keypair()+ loader = LazyLoader(+ "test",+ store=self.store,+ signer=None,+ trusted_signers={fingerprint(pub)},+ mode="off",+ )+ ts = loader.trusted_signers+ assert isinstance(ts, frozenset)+ assert not hasattr(ts, "add")++ def test_no_crypto_remote_store_stays_verify(self) -> None:+ """Without cryptography, a shared/remote store must NOT degrade to off+ (which would deserialize unverified bytes from the very backend signing+ protects); it stays verify so an unsigned entry misses."""+ from unittest import mock++ store = MockStore()+ w = LazyLoader("ns", store=store, signer=None, mode="off")+ w.save_cache(_simple_cache(hash_val="nocrypto_remote", z=9))+ w.flush()++ with mock.patch(+ "marimo._dependencies.dependencies.DependencyManager."+ "cryptography.has",+ return_value=False,+ ):+ reader = LazyLoader("ns", store=store, signer=None)+ assert reader._effective_mode() == "verify"+ assert reader.load_cache(key("nocrypto_remote")) is None++ def test_non_finite_floats_round_trip_and_keep_signature(self) -> None:+ """nan/inf/-inf can't be inlined via `primitive` (msgspec encodes them+ as JSON null, which corrupts the value and breaks the signature once+ re-encoded). They round-trip through a compact inline `special_float`+ token — no pickle blob — and survive a strict round-trip."""+ import math++ signer, verifier = _keypair()+ writer = LazyLoader(+ "test", store=self.store, signer=signer, mode="verify"+ )+ writer.save_cache(+ _simple_cache(+ hash_val="nonfinite",+ a=float("nan"),+ b=float("inf"),+ c=float("-inf"),+ d=1.5,+ )+ )+ writer.flush()++ # No pickle blob is written for the non-finite values — they live+ # inline in the manifest as tokens.+ manifest = msgspec.json.decode(+ self.store.get(str(writer.build_path(key("nonfinite")))),+ type=CacheSchema,+ )+ assert manifest.defs["a"].special_float == "nan"+ assert manifest.defs["b"].special_float == "inf"+ assert manifest.defs["c"].special_float == "-inf"+ assert manifest.defs["d"].primitive == 1.5++ # 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"+ )+ loaded = reader.load_cache(key("nonfinite"))+ assert loaded is not None+ assert math.isnan(loaded.defs["a"])+ assert loaded.defs["b"] == float("inf")+ assert loaded.defs["c"] == float("-inf")+ assert loaded.defs["d"] == 1.5++ def test_fingerprint_slack_bits_canonicalized(self) -> None:+ """base64 of a 32-byte digest has 2 slack bits in its final char, so+ several final chars decode to the same digest. Normalization must+ re-encode to the canonical form (not echo the pasted char), else a+ slack-bit variant validates but never matches → permanent silent miss."""+ import base64+ import string++ from marimo._save.loaders.lazy import _normalize_fingerprint++ signer, _ = _keypair()+ canonical = signer.fingerprint()+ body = canonical[len("SHA256:") :]+ raw = base64.b64decode(body + "=" * (-len(body) % 4))+ alphabet = (+ string.ascii_uppercase+ + string.ascii_lowercase+ + string.digits+ + "+/"+ )+ variant_char = next(+ c+ for c in alphabet+ if c != body[-1]+ and base64.b64decode(body[:-1] + c + "=", validate=True) == raw+ )+ variant = "SHA256:" + body[:-1] + variant_char+ assert variant != canonical+ assert _normalize_fingerprint(variant) == canonical++ def test_strict_raises_on_unsupported_declared_key(self) -> None:+ """If parsing the manifest's declared key raises (e.g. cryptography's+ UnsupportedAlgorithm, which is not a ValueError), a strict loader must+ still raise 'unverifiable' rather than letting it escape to a silent+ miss."""+ from unittest import mock++ from cryptography.exceptions import UnsupportedAlgorithm++ signer, verifier = _keypair()+ writer = LazyLoader(+ "test", store=self.store, signer=signer, mode="verify"+ )+ writer.save_cache(_simple_cache(hash_val="unsupported", z=1))+ writer.flush()++ # Reader trusts the declared key by fingerprint but has no own key, so+ # the declared-key path is the only route to verification.+ reader = LazyLoader(+ "test",+ store=self.store,+ signer=None,+ trusted_signers={signer.fingerprint()},+ mode="strict",+ )+ with mock.patch(+ "marimo._save.loaders.lazy.fingerprint",+ side_effect=UnsupportedAlgorithm("bad OID"),+ ):+ with pytest.raises(CacheSignatureError):+ 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+ machine-local signing key (avoiding a stray key file / read-only+ state-dir warnings for a caller who opted out)."""+ from unittest import mock++ from marimo._save.loaders.lazy import _Unset++ with mock.patch(+ "marimo._save.loaders.lazy._get_default_signer"+ ) as get_signer:+ loader = LazyLoader("test", store=self.store, mode="off")+ assert loader.signer is None+ loader.save_cache(_simple_cache(hash_val="offkey", z=1))+ loader.flush()+ get_signer.assert_not_called()+ # 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:+ """The WASM HTTP store is same-origin as the notebook code, so a verify+ loader with no key/anchor degrades to off (serves) rather than missing+ every read — otherwise the bundled-cache restore feature this stack+ ships is silently disabled in the browser."""+ from marimo._save.loaders.lazy import WasmLazyStore+ from marimo._save.stores.dict_store import DictStore++ store = WasmLazyStore(DictStore())+ w = LazyLoader("ns", store=store, signer=None, mode="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"+ loaded = reader.load_cache(key("wasm_unsigned"))+ assert loaded is not None+ assert loaded.defs["z"] == 7++ def test_wasm_store_no_crypto_degrades_to_off(self) -> None:+ """Same same-origin rationale under the no-cryptography branch: the+ WASM store degrades to off rather than missing every read."""+ from unittest import mock++ from marimo._save.loaders.lazy import WasmLazyStore+ from marimo._save.stores.dict_store import DictStore++ store = WasmLazyStore(DictStore())+ w = LazyLoader("ns", store=store, signer=None, mode="off")+ w.save_cache(_simple_cache(hash_val="wasm_nocrypto", z=8))+ w.flush()++ with mock.patch(+ "marimo._dependencies.dependencies.DependencyManager."+ "cryptography.has",+ return_value=False,+ ):+ reader = LazyLoader("ns", store=store, signer=None, mode="verify")+ assert reader._effective_mode() == "off"+ loaded = reader.load_cache(key("wasm_nocrypto"))+ assert loaded is not None+ assert loaded.defs["z"] == 8++ def test_strict_raises_on_undecodable_manifest(self) -> None:+ """A manifest that fails to decode (malformed JSON, or a tampered+ one-of Item) is a trust anomaly under strict and must raise+ (fail-closed), not fall through to a silent generic miss. verify+ (fail-safe) treats the same garbage as a plain miss."""+ signer, _ = _keypair()+ loader = LazyLoader(+ "test", store=self.store, signer=signer, mode="strict"+ )+ path = str(loader.build_path(key("garbage")))+ self.store.put(path, b"{ this is not valid json")+ with pytest.raises(CacheSignatureError):+ loader.load_cache(key("garbage"))++ verify_loader = LazyLoader(+ "test", store=self.store, signer=signer, mode="verify"+ )+ assert verify_loader.load_cache(key("garbage")) is None++ def test_bytes_forced_inline_falls_through_to_blob_reference(self) -> None:+ """to_item must never inline bytes via `primitive` (msgspec base64s it+ to a str, silently corrupting the value). Even when inline is forced,+ bytes fall through to a blob reference instead."""+ from pathlib import Path++ from marimo._save.loaders.lazy import to_item++ item = to_item(+ Path("ns/h"),+ b"\x00\x01raw",+ var_name="b",+ loader="inline",+ hash="h",+ )+ assert item.primitive is None+ assert item.reference == "ns/h/b.pickle"++ def test_strict_missing_blob_under_verified_manifest_raises(self) -> None:+ """A verified manifest whose blob is gone is an integrity failure:+ strict raises (fail-closed), verify misses (recompute). Otherwise a+ strict loader would silently miss an incomplete signed entry."""+ signer, verifier = _keypair()+ writer = self._loader(signer=signer)+ writer.save_cache(+ _simple_cache(hash_val="missing_blob", pt=_Point(1, 2))+ )+ writer.flush()+ # 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")+ with pytest.raises(CacheSignatureError):+ strict.load_cache(key("missing_blob"))++ verify = self._loader(signer=verifier, mode="verify")+ assert verify.load_cache(key("missing_blob")) is None++ def test_strict_deserialize_failure_is_miss_not_tampering(self) -> None:+ """A signed, hash-verified blob whose deserializer fails (e.g. a CUDA+ tensor on a CPU-only host) is authentic — not tampering. It must+ recompute (miss) in every mode, including strict, rather than raise a+ spurious CacheSignatureError blaming corruption."""+ from unittest import mock++ signer, verifier = _keypair()+ writer = self._loader(signer=signer)+ writer.save_cache(+ _simple_cache(hash_val="deser_fail", pt=_Point(1, 2))+ )+ writer.flush()++ 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")+ with mock.patch.dict(+ "marimo._save.loaders.lazy.BLOB_DESERIALIZERS",+ {".pickle": _boom},+ ):+ # Hash verifies (bytes untouched); only deserialization fails →+ # miss, not CacheSignatureError.+ assert reader.load_cache(key("deser_fail")) is None+++# ---------------------------------------------------------------------------+# fingerprint primitive+# ---------------------------------------------------------------------------+++class TestFingerprint:+ def test_fingerprint_format_and_stability(self) -> None:+ _, pub = generate_keypair()+ fp = fingerprint(pub)+ assert fp.startswith("SHA256:")+ assert "=" not in fp # unpadded+ assert fingerprint(pub) == fp # deterministic++ def test_fingerprint_matches_signer_method(self) -> None:+ _, pub = generate_keypair()+ signer = CacheSigner.from_public_key_pem(pub)+ assert signer.fingerprint() == fingerprint(pub)++ def test_distinct_keys_distinct_fingerprints(self) -> None:+ _, pub_a = generate_keypair()+ _, pub_b = generate_keypair()+ assert fingerprint(pub_a) != fingerprint(pub_b)+++# ---------------------------------------------------------------------------+# WASM: signature failures evict the fetched bytes+# ---------------------------------------------------------------------------+++class TestWasmSignatureEviction:+ """A signed-blob mismatch in WASM must evict the HTTP-fetched bytes from+ the session store (and poison the keys) so tampered data is neither+ re-served nor swept into an export bundle via export_keys()."""++ @pytest.fixture(autouse=True)+ def _isolate_poisoned_keys(self) -> Any:+ from marimo._save.loaders.lazy import _cache_state++ poisoned = _cache_state().poisoned_keys+ snapshot = set(poisoned)+ yield+ poisoned.clear()+ poisoned.update(snapshot)++ def test_tampered_blob_evicted_and_poisoned_in_verify(self) -> None:+ from unittest import mock++ from marimo._save.loaders.lazy import (+ WasmLazyLoader,+ WasmLazyStore,+ _cache_state,+ )+ from marimo._save.stores.dict_store import DictStore++ signer, verifier = _keypair()+ store = WasmLazyStore(inner=DictStore())+ writer = WasmLazyLoader("wasm_sig", store=store, signer=signer)+ writer.save_cache(+ _simple_cache(hash_val="wasm_tamper", secret={"k": "v"})+ )+ writer.flush()++ # Overwrite the pickle blob in the session store with different bytes.+ blob_key = next(+ k for k in store.export_keys() if k.endswith(".pickle")+ )+ store._inner.put(blob_key, pickle.dumps({"injected": True}))++ reader = WasmLazyLoader("wasm_sig", store=store, signer=verifier)+ # No network: the tampered blob is already resident in the inner store,+ # and evicted keys must not trigger a real fetch.+ with mock.patch.object(+ store, "_http_get_batch", return_value=iter([])+ ):+ assert reader.load_cache(key("wasm_tamper")) is None++ manifest_path = str(reader.build_path(key("wasm_tamper")))+ assert blob_key in _cache_state().poisoned_keys+ assert manifest_path in _cache_state().poisoned_keys+ assert not store.hit(blob_key)+ # The rejected blob is no longer advertised for export bundling.+ assert blob_key not in store.export_keys()diff --git a/tests/_save/loaders/test_lazy_wasm.py b/tests/_save/loaders/test_lazy_wasm.pyindex 50c1bf495a..5f04598829 100644--- a/tests/_save/loaders/test_lazy_wasm.py+++ b/tests/_save/loaders/test_lazy_wasm.py@@ -225,7 +225,9 @@ class TestLazyLoaderBatchPath:def test_restore_uses_batch_path(self) -> None:inner = DictStore()store = LazyStore(inner=inner)- loader = LazyLoader("test_batch", store=store)+ # mode="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")# Seed a cache manuallybase = Path("test_batch") / "hash1"@@ -259,7 +261,8 @@ class TestLazyLoaderBatchPath:# (no threads in Pyodide) via `_dispatch_write`.inner = DictStore()store = WasmLazyStore(inner=inner)- loader = WasmLazyLoader("test_sync", store=store)+ # mode="off": exercises the synchronous WASM write path, not signing.+ loader = WasmLazyLoader("test_sync", store=store, mode="off")cache = Cache(defs={"x": 42, "y": "hello"},@@ -377,7 +380,7 @@ class TestRestoreTripwire:) -> None:self._patch_failing_codec(monkeypatch)store = LazyStore(inner=DictStore())- loader = LazyLoader("trip_native", store=store)+ loader = LazyLoader("trip_native", store=store, mode="off")base = Path("trip_native") / "h"good_ref = (base / "good.pickle").as_posix()@@ -401,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)+ loader = WasmLazyLoader("trip_wasm", store=store, mode="off")base = Path("trip_wasm") / "h"good_ref = (base / "good.pickle").as_posix()@@ -428,7 +431,7 @@ class TestRestoreTripwire:from marimo._save.hash import HashKeystore = LazyStore(inner=DictStore())- loader = LazyLoader("trip_return", store=store)+ loader = LazyLoader("trip_return", store=store, mode="off")base = Path("trip_return") / "h"good_ref = (base / "good.pickle").as_posix()@@ -456,7 +459,7 @@ class TestRestoreTripwire:from marimo._save.hash import HashKeystore = WasmLazyStore(inner=DictStore())- loader = WasmLazyLoader("trip_return_wasm", store=store)+ loader = WasmLazyLoader("trip_return_wasm", store=store, mode="off")base = Path("trip_return_wasm") / "h"good_ref = (base / "good.pickle").as_posix()@@ -485,7 +488,7 @@ class TestRestoreTripwire:from marimo._save.hash import HashKeystore = LazyStore(inner=DictStore())- loader = LazyLoader("trip_ui", store=store)+ loader = LazyLoader("trip_ui", store=store, mode="off")ui_ref = (Path("trip_ui") / "h" / "ui.pickle").as_posix()store.put(ui_ref, b"__FAIL__")@@ -531,7 +534,7 @@ class TestRestoreTripwire:)store = LazyStore(inner=DictStore())- loader = LazyLoader("trip_import", store=store)+ loader = LazyLoader("trip_import", store=store, mode="off")bad_ref = (Path("trip_import") / "h" / "bad.faildep").as_posix()store.put(bad_ref, b"unused")self._seed(@@ -598,7 +601,7 @@ class TestStaleKeys:from marimo._save.loaders.lazy import _cache_statestore = LazyStore(inner=DictStore())- loader = LazyLoader("stale_test", store=store)+ loader = LazyLoader("stale_test", store=store, mode="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 37c71c04d4..7047d53b4d 100644--- a/tests/_save/loaders/test_loader.py+++ b/tests/_save/loaders/test_loader.py@@ -207,7 +207,10 @@ class TestLazyLoader(ABCTestLoader):suffix = "jsonl"def _instance(self) -> Loader:- return LazyLoader("test", store=self.store)+ # 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")def teardown_method(self) -> None:if self.value and hasattr(self.value, "flush"):diff --git a/tests/_save/test_signing.py b/tests/_save/test_signing.pynew file mode 100644index 0000000000..5afabb3356--- /dev/null+++ b/tests/_save/test_signing.py@@ -0,0 +1,416 @@+# Copyright 2026 Marimo. All rights reserved.+"""Unit tests for marimo._save.signing."""++from __future__ import annotations++import os+from typing import Any+from unittest.mock import patch++import pytest++pytest.importorskip("cryptography", reason="cryptography not installed")++from marimo._save.signing import (+ CacheSignatureError,+ CacheSigner,+ _sha256hex,+ fingerprint,+ generate_keypair,+)++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_signer() -> CacheSigner:+ private_pem, _ = generate_keypair()+ return CacheSigner.from_private_key_pem(private_pem)+++def _make_verifier() -> tuple[CacheSigner, CacheSigner]:+ """Return (signer_with_private, verifier_with_public_only)."""+ private_pem, public_pem = generate_keypair()+ signer = CacheSigner.from_private_key_pem(private_pem)+ verifier = CacheSigner.from_public_key_pem(public_pem)+ return signer, verifier+++# ---------------------------------------------------------------------------+# generate_keypair+# ---------------------------------------------------------------------------+++class TestGenerateKeypair:+ def test_returns_two_pem_strings(self) -> None:+ private_pem, public_pem = generate_keypair()+ assert "PRIVATE KEY" in private_pem+ assert "PUBLIC KEY" in public_pem++ def test_pem_round_trip(self) -> None:+ private_pem, public_pem = generate_keypair()+ signer = CacheSigner.from_private_key_pem(private_pem)+ assert signer.private_key_pem() == private_pem+ assert signer.public_key_pem() == public_pem+++# ---------------------------------------------------------------------------+# CacheSigner construction+# ---------------------------------------------------------------------------+++class TestCacheSignerConstruction:+ def test_requires_at_least_one_key(self) -> None:+ with pytest.raises(ValueError, match="at least one"):+ CacheSigner()++ def test_private_key_implies_public(self) -> None:+ signer = _make_signer()+ assert signer.can_sign+ # Public key is derived automatically; PEM export should work.+ pem = signer.public_key_pem()+ assert "PUBLIC KEY" in pem++ def test_public_key_only(self) -> None:+ _, public_pem = generate_keypair()+ verifier = CacheSigner.from_public_key_pem(public_pem)+ assert not verifier.can_sign++ def test_sign_without_private_key_raises(self) -> None:+ _, public_pem = generate_keypair()+ verifier = CacheSigner.from_public_key_pem(public_pem)+ with pytest.raises(ValueError, match="no private key"):+ verifier.sign(b"data")++ def test_private_key_pem_without_private_raises(self) -> None:+ _, public_pem = generate_keypair()+ verifier = CacheSigner.from_public_key_pem(public_pem)+ with pytest.raises(ValueError, match="No private key"):+ verifier.private_key_pem()++ def test_from_public_key_pem_rejects_non_ed25519(self) -> None:+ """A non-Ed25519 key must fail at load, not silently at verify time."""+ from cryptography.hazmat.primitives import serialization+ from cryptography.hazmat.primitives.asymmetric import ec++ ec_pub = (+ ec.generate_private_key(ec.SECP256R1())+ .public_key()+ .public_bytes(+ serialization.Encoding.PEM,+ serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ .decode()+ )+ with pytest.raises(ValueError, match="Ed25519"):+ CacheSigner.from_public_key_pem(ec_pub)++ def test_from_private_key_pem_rejects_non_ed25519(self) -> None:+ from cryptography.hazmat.primitives import serialization+ from cryptography.hazmat.primitives.asymmetric import ec++ ec_priv = (+ ec.generate_private_key(ec.SECP256R1())+ .private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ )+ .decode()+ )+ with pytest.raises(ValueError, match="Ed25519"):+ CacheSigner.from_private_key_pem(ec_priv)+++# ---------------------------------------------------------------------------+# sign / verify+# ---------------------------------------------------------------------------+++class TestSignVerify:+ def test_sign_and_verify_succeed(self) -> None:+ signer, verifier = _make_verifier()+ data = b"hello world"+ sig = signer.sign(data)+ # Must not raise+ verifier.verify(data, sig)++ def test_tampered_data_raises(self) -> None:+ signer, verifier = _make_verifier()+ sig = signer.sign(b"original")+ with pytest.raises(CacheSignatureError):+ verifier.verify(b"tampered", sig)++ def test_tampered_signature_raises(self) -> None:+ signer, verifier = _make_verifier()+ # Sign different data to get a valid but wrong signature+ bad_sig = signer.sign(b"completely different data")+ with pytest.raises(CacheSignatureError):+ verifier.verify(b"data", bad_sig)++ def test_wrong_key_raises(self) -> None:+ signer, _ = _make_verifier()+ _, other_verifier = _make_verifier()+ sig = signer.sign(b"data")+ with pytest.raises(CacheSignatureError):+ other_verifier.verify(b"data", sig)++ def test_self_verify(self) -> None:+ """A signer with private key can also verify its own signatures."""+ signer = _make_signer()+ data = b"test"+ sig = signer.sign(data)+ signer.verify(data, sig) # must not raise++ def test_malformed_base64_raises(self) -> None:+ """Truncated/corrupted base64 in the signature string raises CacheSignatureError."""+ _, verifier = _make_verifier()+ with pytest.raises(+ CacheSignatureError, match="not readable|corrupted"+ ):+ verifier.verify(b"data", "not!!valid==base64@@")+++# ---------------------------------------------------------------------------+# verify_blob+# ---------------------------------------------------------------------------+++class TestVerifyBlob:+ def test_correct_hash_passes(self) -> None:+ signer = _make_signer()+ blob = b"blob content"+ expected = _sha256hex(blob)+ signer.verify_blob("key", blob, expected) # must not raise++ def test_wrong_hash_raises(self) -> None:+ signer = _make_signer()+ blob = b"blob content"+ wrong_hash = _sha256hex(b"different content")+ with pytest.raises(CacheSignatureError, match="checksum"):+ signer.verify_blob("key", blob, wrong_hash)++ def test_error_message_contains_key(self) -> None:+ signer = _make_signer()+ with pytest.raises(CacheSignatureError, match="my_blob_key"):+ signer.verify_blob("my_blob_key", b"x", "0" * 64)+++# ---------------------------------------------------------------------------+# _sha256hex+# ---------------------------------------------------------------------------+++class TestSha256Hex:+ def test_known_value(self) -> None:+ # SHA-256 of empty bytes is well-known+ assert _sha256hex(b"") == (+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ )++ def test_returns_64_chars(self) -> None:+ assert len(_sha256hex(b"anything")) == 64+++# ---------------------------------------------------------------------------+# from_env+# ---------------------------------------------------------------------------+++class TestFromEnv:+ def test_returns_none_when_not_set(self) -> None:+ with patch.dict(+ os.environ,+ {},+ clear=False,+ ):+ # Ensure vars aren't set in the environment+ env = {+ k: v+ for k, v in os.environ.items()+ if k+ not in (+ "MARIMO_CACHE_SIGNING_PRIVATE_KEY",+ "MARIMO_CACHE_SIGNING_PUBLIC_KEY",+ )+ }+ with patch.dict(os.environ, env, clear=True):+ result = CacheSigner.from_env()+ assert result is None++ def test_private_key_env_takes_precedence(self) -> None:+ private_pem, public_pem = generate_keypair()+ with patch.dict(+ os.environ,+ {+ "MARIMO_CACHE_SIGNING_PRIVATE_KEY": private_pem,+ "MARIMO_CACHE_SIGNING_PUBLIC_KEY": public_pem,+ },+ ):+ signer = CacheSigner.from_env()+ assert signer is not None+ assert signer.can_sign++ def test_public_key_only_env(self) -> None:+ _, public_pem = generate_keypair()+ env_without_private = {+ k: v+ for k, v in os.environ.items()+ if k != "MARIMO_CACHE_SIGNING_PRIVATE_KEY"+ }+ env_without_private["MARIMO_CACHE_SIGNING_PUBLIC_KEY"] = public_pem+ with patch.dict(os.environ, env_without_private, clear=True):+ signer = CacheSigner.from_env()+ assert signer is not None+ assert not signer.can_sign++ def test_custom_env_var_names(self) -> None:+ private_pem, _ = generate_keypair()+ with patch.dict(os.environ, {"MY_PRIV": private_pem}):+ signer = CacheSigner.from_env(+ private_key_env="MY_PRIV", public_key_env="MY_PUB"+ )+ assert signer is not None+ assert signer.can_sign+++class TestFingerprint:+ def test_format_unpadded_sha256(self) -> None:+ _, pub = generate_keypair()+ fp = fingerprint(pub)+ assert fp.startswith("SHA256:")+ assert "=" not in fp++ def test_matches_signer_method(self) -> None:+ priv, pub = generate_keypair()+ signer = CacheSigner.from_private_key_pem(priv)+ assert signer.fingerprint() == fingerprint(pub)++ def test_deterministic_and_distinct(self) -> None:+ _, pub_a = generate_keypair()+ _, pub_b = generate_keypair()+ assert fingerprint(pub_a) == fingerprint(pub_a)+ assert fingerprint(pub_a) != fingerprint(pub_b)++ def test_rejects_garbage_pem(self) -> None:+ with pytest.raises(ValueError):+ fingerprint(+ "-----BEGIN PUBLIC KEY-----\nnope\n-----END PUBLIC KEY-----"+ )+++class TestGetDefaultSigner:+ def test_returns_none_without_cryptography(self) -> None:+ from marimo._save.signing import _get_default_signer++ with patch(+ "marimo._dependencies.dependencies.DependencyManager.cryptography.has",+ return_value=False,+ ):+ assert _get_default_signer() is None++ def test_env_var_takes_precedence(self) -> None:+ from marimo._save.signing import _get_default_signer++ private_pem, _ = generate_keypair()+ with patch.dict(+ os.environ,+ {"MARIMO_CACHE_SIGNING_PRIVATE_KEY": private_pem},+ ):+ signer = _get_default_signer()+ assert signer is not None+ assert signer.can_sign++ def test_generates_and_persists_key(self, tmp_path: Any) -> None:+ from marimo._save.signing import _get_default_signer++ key_path = tmp_path / "cache_signing_key.pem"++ # Ensure env vars don't interfere+ env = {+ k: v+ for k, v in os.environ.items()+ if k+ not in (+ "MARIMO_CACHE_SIGNING_PRIVATE_KEY",+ "MARIMO_CACHE_SIGNING_PUBLIC_KEY",+ )+ }+ with (+ patch.dict(os.environ, env, clear=True),+ patch(+ "marimo._utils.xdg.marimo_state_dir",+ return_value=tmp_path,+ ),+ ):+ signer = _get_default_signer()+ assert signer is not None+ assert signer.can_sign+ assert key_path.exists()+ # Key file should be readable and produce the same public key+ loaded = CacheSigner.from_private_key_pem(key_path.read_text())+ assert loaded.public_key_pem() == signer.public_key_pem()++ def test_loads_existing_key(self, tmp_path: Any) -> None:+ from marimo._save.signing import _get_default_signer++ # Pre-create a key file+ private_pem, _ = generate_keypair()+ key_path = tmp_path / "cache_signing_key.pem"+ key_path.write_text(private_pem)++ env = {+ k: v+ for k, v in os.environ.items()+ if k+ not in (+ "MARIMO_CACHE_SIGNING_PRIVATE_KEY",+ "MARIMO_CACHE_SIGNING_PUBLIC_KEY",+ )+ }+ with (+ patch.dict(os.environ, env, clear=True),+ patch(+ "marimo._utils.xdg.marimo_state_dir",+ return_value=tmp_path,+ ),+ ):+ signer = _get_default_signer()+ assert signer is not None+ # Should load the existing key, not generate a new one+ assert (+ signer.public_key_pem()+ == CacheSigner.from_private_key_pem(+ private_pem+ ).public_key_pem()+ )++ def test_corrupt_key_file_regenerates(self, tmp_path: Any) -> None:+ from marimo._save.signing import _get_default_signer++ key_path = tmp_path / "cache_signing_key.pem"+ key_path.write_text("not a valid PEM")++ env = {+ k: v+ for k, v in os.environ.items()+ if k+ not in (+ "MARIMO_CACHE_SIGNING_PRIVATE_KEY",+ "MARIMO_CACHE_SIGNING_PUBLIC_KEY",+ )+ }+ with (+ patch.dict(os.environ, env, clear=True),+ patch(+ "marimo._utils.xdg.marimo_state_dir",+ return_value=tmp_path,+ ),+ ):+ signer = _get_default_signer()+ assert signer is not None+ assert signer.can_sign+ # Should have overwritten the corrupt file+ assert key_path.exists()+ assert "PRIVATE KEY" in key_path.read_text()diff --git a/tests/snapshots/optional-dependencies-recommended.txt b/tests/snapshots/optional-dependencies-recommended.txtindex 3c6255ab21..f69b3a6957 100644--- a/tests/snapshots/optional-dependencies-recommended.txt+++ b/tests/snapshots/optional-dependencies-recommended.txt@@ -1,4 +1,5 @@altair>=5.4.0+cryptography>=42.0.0marimo[sandbox]marimo[sql]nbformat>=5.7.0