diff --git a/llms-full.txt b/llms-full.txt index 97d38a6b7c..6f715b1bfc 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2452,3 +2452,7 @@ automation into an independently certified transaction system. - Passphrase-derived keys, attended run keys and opened sealed sets are no longer cached for the whole process. Each independent operation authenticates again; caller-owned handles still reuse their key (#2341). + A durable checkpoint store counts as such a handle: it keeps the keys it + derived from its explicit key for its own lifetime. Without that, each + checkpoint read ran scrypt again, and the MockMed quickstart run took 28 s + instead of 3.5 s (131 derivations, now 1). diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index c488559fb3..0362f704bb 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -92,6 +92,10 @@ - Passphrase-derived keys, attended run keys and opened sealed sets are no longer cached for the whole process. Each independent operation authenticates again; caller-owned handles still reuse their key (#2341). + A durable checkpoint store counts as such a handle: it keeps the keys it + derived from its explicit key for its own lifetime. Without that, each + checkpoint read ran scrypt again, and the MockMed quickstart run took 28 s + instead of 3.5 s (131 derivations, now 1). ## v3.3.0 (2026-11-19) diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index cc1ae318d1..f0fa959e13 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -214,6 +214,13 @@ place is refused. The external attended journal stores each decision-log snapshot encrypted and bound to its run and sequence; its hash chain and HMAC cover the plaintext. A run whose attended files are plaintext from an earlier version still resumes, and its first encrypted write converts them. + +A durable store is itself a caller-owned handle. It keeps the keys it +derived from its own explicit key, by salt and work factors, for its own +lifetime, so one run stretches the passphrase once rather than once per +checkpoint read. Each read still authenticates the container on disk. Another +store, a changed key, or a store that reads the key from the environment +derives again. File and journal operations derive their keys with scrypt under the random salt kept in the run's `.attended_state.encrypted` marker. A conversion operation reuses its local AEAD across the files it converts; independent diff --git a/packages/flow/openadapt_flow/crypto.py b/packages/flow/openadapt_flow/crypto.py index ee2dfad539..6400120eb3 100644 --- a/packages/flow/openadapt_flow/crypto.py +++ b/packages/flow/openadapt_flow/crypto.py @@ -210,6 +210,7 @@ def encrypt_bytes( *, aad: bytes, salt: Optional[bytes] = None, + keys: Optional["ContainerKeys"] = None, ) -> bytes: """Seal ``plaintext`` into a self-describing AES-256-GCM container. @@ -222,6 +223,9 @@ def encrypt_bytes( ``salt`` lets one writer seal containers under the same salt. Each call still runs scrypt and uses a fresh random nonce; sharing a salt does not create a process-global key cache. Default: a fresh salt per container. + ``keys`` is a caller-owned :class:`ContainerKeys` handle; with it, a salt + the handle has already stretched for this passphrase is not stretched + again. """ passphrase = require_key(key) if salt is None: @@ -229,7 +233,7 @@ def encrypt_bytes( elif len(salt) != _SALT_LEN: raise CryptoError("a container salt must be 16 bytes") nonce = secrets.token_bytes(_NONCE_LEN) - dek = _derive(passphrase, salt, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P) + dek = _container_key(keys, passphrase, salt, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P) ciphertext = AESGCM(dek).encrypt(nonce, plaintext, aad) container = { "format": _MAGIC, @@ -247,7 +251,13 @@ def encrypt_bytes( return json.dumps(container, indent=2).encode("utf-8") -def decrypt_bytes(container: bytes, key: Optional[str], *, aad: bytes) -> bytes: +def decrypt_bytes( + container: bytes, + key: Optional[str], + *, + aad: bytes, + keys: Optional["ContainerKeys"] = None, +) -> bytes: """Authenticate and decrypt a container produced by :func:`encrypt_bytes`. Raises :class:`MissingKeyError` when no passphrase is configured, @@ -269,7 +279,7 @@ def decrypt_bytes(container: bytes, key: Optional[str], *, aad: bytes) -> bytes: raise except (ValueError, TypeError, KeyError) as exc: raise DecryptionError(f"malformed encrypted container: {exc}") from exc - dek = _derive(passphrase, salt, n=n, r=r, p=p) + dek = _container_key(keys, passphrase, salt, n=n, r=r, p=p) try: return AESGCM(dek).decrypt(nonce, ciphertext, aad) except InvalidTag as exc: @@ -279,6 +289,65 @@ def decrypt_bytes(container: bytes, key: Optional[str], *, aad: bytes) -> bytes: ) from exc +class ContainerKeys: + """Derived container keys owned by one caller, such as a checkpoint store. + + A run's checkpoint store reads its own sealed checkpoints back many times + per run. Without a handle each read runs scrypt again (131 derivations, + about 20 s, on one tutorial run). The handle keeps the keys it derived, + by salt and work factors, for its owner's lifetime only. It makes no copy + of the passphrase and keeps no verifier: the owner passes its passphrase + on every call, and :meth:`rebind` keeps only a reference to the key object + the owner already holds, dropping every key when that object changes. + Every read still authenticates the container's bytes with AES-GCM, so a + wrong key or a tampered file is refused as before. Nothing is module-level + and nothing is written anywhere. + """ + + __slots__ = ("_bound", "_keys", "_lock") + + _LIMIT: Final[int] = 32 + + def __init__(self) -> None: + self._bound: object = None + self._keys: dict[tuple[bytes, int, int, int], bytes] = {} + self._lock = threading.Lock() + + def rebind(self, owner_key: object) -> None: + """Drop every key unless ``owner_key`` is the object last bound.""" + with self._lock: + if owner_key is not self._bound: + self._keys.clear() + self._bound = owner_key + + def derive(self, passphrase: str, salt: bytes, *, n: int, r: int, p: int) -> bytes: + slot = (bytes(salt), int(n), int(r), int(p)) + with self._lock: + cached = self._keys.get(slot) + if cached is not None: + return cached + key = _derive(passphrase, salt, n=n, r=r, p=p) + with self._lock: + if len(self._keys) >= self._LIMIT: + self._keys.clear() + self._keys[slot] = key + return key + + +def _container_key( + keys: Optional[ContainerKeys], + passphrase: str, + salt: bytes, + *, + n: int, + r: int, + p: int, +) -> bytes: + if keys is None: + return _derive(passphrase, salt, n=n, r=r, p=p) + return keys.derive(passphrase, salt, n=n, r=r, p=p) + + # -- one derived key for a whole sealed set ---------------------------------- # # ``encrypt_bytes`` runs scrypt for every payload, which is right for one diff --git a/packages/flow/openadapt_flow/runtime/durable/checkpoint.py b/packages/flow/openadapt_flow/runtime/durable/checkpoint.py index 58ef77da1e..f9ab6757d1 100644 --- a/packages/flow/openadapt_flow/runtime/durable/checkpoint.py +++ b/packages/flow/openadapt_flow/runtime/durable/checkpoint.py @@ -45,7 +45,7 @@ from contextlib import contextmanager from datetime import datetime, timedelta, timezone from pathlib import Path -from typing import Callable, Iterator, Literal, Optional +from typing import TYPE_CHECKING, Callable, Iterator, Literal, Optional from pydantic import BaseModel, Field, model_serializer, model_validator @@ -75,6 +75,9 @@ ProgramCheckpoint, ) +if TYPE_CHECKING: + from openadapt_flow.crypto import ContainerKeys + CHECKPOINTS_DIRNAME = "checkpoints" MANIFEST_FILENAME = "_manifest.json" PENDING_FILENAME = "pending_escalation.json" @@ -492,10 +495,25 @@ def __init__(self, run_dir: Path | str, *, key: Optional[str] = None) -> None: # None => plaintext (unchanged default). A non-empty passphrase turns on # AEAD sealing for writes and decryption for reads. self.key = key - # Reuse one public salt for containers this store seals. Independent - # encryption/decryption requests still run scrypt; each container - # records the salt and gets its own random nonce. + # Reuse one public salt for containers this store seals; each + # container records the salt and gets its own random nonce. self._salt: Optional[bytes] = None + # This store's own derived keys (crypto.ContainerKeys): a run reads its + # checkpoints back many times, and each read would otherwise run + # scrypt again. Used only with an explicit key; another store, or a + # changed key, derives again. Every read still authenticates. + self._container_keys: Optional["ContainerKeys"] = None + + def _keys(self) -> Optional["ContainerKeys"]: + """This store's derived-key handle, or None without an explicit key.""" + if not self.key: + return None + from openadapt_flow import crypto as _crypto + + if self._container_keys is None: + self._container_keys = _crypto.ContainerKeys() + self._container_keys.rebind(self.key) + return self._container_keys def _container_salt(self) -> bytes: if self._salt is None: @@ -522,6 +540,7 @@ def _write_model(self, path: Path, model: BaseModel) -> Path: self.key, aad=_crypto.CHECKPOINT_AAD, salt=self._container_salt(), + keys=self._keys(), ), ) if path.exists(): @@ -579,7 +598,10 @@ def _read_json(self, path: Path) -> Optional[dict]: from openadapt_flow import crypto as _crypto decrypted = _crypto.decrypt_bytes( - enc.read_bytes(), self.key, aad=_crypto.CHECKPOINT_AAD + enc.read_bytes(), + self.key, + aad=_crypto.CHECKPOINT_AAD, + keys=self._keys(), ) return json.loads(decrypted) # type: ignore[no-any-return] if path.is_file(): diff --git a/packages/flow/tests/test_checkpoint_key_derivations.py b/packages/flow/tests/test_checkpoint_key_derivations.py index fae7b0907d..f3dd27cd62 100644 --- a/packages/flow/tests/test_checkpoint_key_derivations.py +++ b/packages/flow/tests/test_checkpoint_key_derivations.py @@ -1,8 +1,11 @@ -"""Checkpoint crypto derives per operation without a process-global verifier. - -The former cross-operation cache optimization is intentionally removed. -Wire, readback, wrong-key and tamper controls remain; explicit SetKey handles -reuse their owned AEAD within a sealed-set operation. +"""Checkpoint crypto keeps no process-global key cache; a store owns its keys. + +#2341 removed the process-wide derived-key cache. A checkpoint store is an +explicit caller-owned handle: it keeps the keys it derived for its own +lifetime (crypto.ContainerKeys), so one run stretches its passphrase once +instead of once per read (131 scrypt runs, about 20 s, on one MockMed run). +Another store, or a changed key, derives again. Wire format, wrong-key and +tamper refusals are unchanged, and every read still authenticates. """ from __future__ import annotations @@ -47,7 +50,7 @@ def _checkpoint(i: int) -> RunCheckpoint: ) -def test_a_run_derives_once_per_crypto_operation(tmp_path, derivation_requests): +def test_a_store_derives_its_key_once_for_a_whole_run(tmp_path, derivation_requests): before = crypto.derivations store = CheckpointStore(tmp_path / "run", key=KEY) store.write_manifest(RunManifest(workflow_name="w", bundle_dir="b")) @@ -55,23 +58,48 @@ def test_a_run_derives_once_per_crypto_operation(tmp_path, derivation_requests): store.write_checkpoint(_checkpoint(i)) store.continuation_state_digest() assert store.last_checkpoint().step_id == f"s{i}" - assert crypto.derivations - before == len(derivation_requests) - assert len(derivation_requests) > 3 + assert crypto.derivations - before == len(derivation_requests) == 1 -def test_resumed_store_reads_derive_per_operation(tmp_path, derivation_requests): +def test_another_store_on_the_same_run_derives_again(tmp_path, derivation_requests): run = tmp_path / "run" writer = CheckpointStore(run, key=KEY) for i in range(5): writer.write_checkpoint(_checkpoint(i)) - before_requests = len(derivation_requests) - before = crypto.derivations + assert len(derivation_requests) == 1 reader = CheckpointStore(run, key=KEY) for _ in range(10): assert len(reader.checkpoints()) == 5 reader.write_checkpoint(_checkpoint(5)) - assert crypto.derivations - before == len(derivation_requests) - before_requests - assert crypto.derivations - before == 51 + # The reader stretched the writer's salt once for its reads, and its own + # new salt once for its write; nothing was shared with the writer. + assert len(derivation_requests) == 3 + + +def test_a_changed_store_key_drops_the_derived_keys(tmp_path, derivation_requests): + run = tmp_path / "run" + store = CheckpointStore(run, key=KEY) + store.write_checkpoint(_checkpoint(0)) + assert store.last_checkpoint() is not None + assert len(derivation_requests) == 1 + store.key = WRONG + with pytest.raises(crypto.DecryptionError): + store.last_checkpoint() + assert len(derivation_requests) == 2 + + +def test_a_store_without_an_explicit_key_keeps_no_keys( + tmp_path, monkeypatch, derivation_requests +): + monkeypatch.setenv("OPENADAPT_BUNDLE_KEY", KEY) + writer = CheckpointStore(tmp_path / "run", key=KEY) + writer.write_checkpoint(_checkpoint(0)) + reader = CheckpointStore(tmp_path / "run") + before = len(derivation_requests) + for _ in range(3): + assert reader.last_checkpoint() is not None + assert len(derivation_requests) - before == 3 + assert reader._container_keys is None def test_containers_keep_the_format_with_one_salt_and_fresh_nonces(tmp_path): @@ -130,9 +158,9 @@ def test_repeated_payload_operations_do_not_use_a_global_cache(): assert not hasattr(crypto, "_DERIVED") -def test_durable_run_derives_per_operation(tmp_path, derivation_requests): - # Keep the original synthetic durable readback workload; its independent - # crypto operations now each derive, rather than sharing a global verifier. +def test_a_durable_run_derives_once_per_store(tmp_path, derivation_requests): + # The original synthetic durable readback workload: the run's store owns + # its derived key, and a fresh store reading the run back derives again. from openadapt_flow.ir import Workflow from openadapt_flow.runtime.replayer import Replayer from tests.test_durable_runtime import _key_step, _vision_ok @@ -153,6 +181,8 @@ def test_durable_run_derives_per_operation(tmp_path, derivation_requests): poll_interval_s=0.01, ).run(workflow, bundle_dir=bundle, run_dir=run_dir) assert report.success is True + during_run = len(derivation_requests) + assert 1 <= during_run <= 3 assert len(CheckpointStore(run_dir, key=KEY).checkpoints()) == 12 + assert len(derivation_requests) == during_run + 1 assert crypto.derivations - before == len(derivation_requests) - assert len(derivation_requests) > 3