diff --git a/openadapt/quickstart/engine.py b/openadapt/quickstart/engine.py index afda903c96..a7ba887778 100644 --- a/openadapt/quickstart/engine.py +++ b/openadapt/quickstart/engine.py @@ -18,6 +18,7 @@ from __future__ import annotations import contextlib +import importlib import inspect import json import threading @@ -43,6 +44,14 @@ #: How often the step ticker reads the recorder's event log, in seconds. _TICK_S = 0.05 +#: Seed for a reproducible compile of the bundled tutorial. The tutorial's +#: data is synthetic, so a public constant is safe here, and it makes every +#: quickstart compile the same program with the same content digest (OpenAdapt +#: Cloud pins that digest to list a published tutorial Seal). Never reuse it +#: for a real recording: anyone who knows it can test guesses against the +#: bundle's salted hashes. +TUTORIAL_REPRODUCIBLE_SEED = b"openadapt-quickstart-mockmed-tutorial-v1" + @dataclass class DemoStep: @@ -259,6 +268,21 @@ def _accepts(function: Callable[..., Any], name: str) -> bool: return False +def _compiler_accepts(name: str) -> bool: + """Whether the installed compiler takes keyword ``name``. + + ``compile_recording`` forwards ``**kwargs``, so the check reads the inner + compiler's signature. An older openadapt-flow without the keyword compiles + as before. + """ + try: + _compile = importlib.import_module("openadapt_flow.compiler.compile") + except ImportError: + return False + inner = getattr(_compile, "_compile_recording", None) + return inner is not None and _accepts(inner, name) + + def _effect_counts(report: Any) -> tuple[int, int]: envelope = getattr(report, "outcome_envelope", None) if envelope is None: @@ -446,12 +470,16 @@ def compile(self) -> int: consequential_step, ) + reproducible: dict[str, Any] = {} + if _compiler_accepts("reproducible_seed"): + reproducible["reproducible_seed"] = TUTORIAL_REPRODUCIBLE_SEED workflow = compile_recording( self.recording_dir, self.bundle_dir, name=TUTORIAL_WORKFLOW_NAME, mine_effects=True, bind_effect_params=True, + **reproducible, ) consequential_step(workflow) certify_tutorial(workflow) diff --git a/packages/flow/docs/TUTORIAL.md b/packages/flow/docs/TUTORIAL.md index fa71ce04f3..5455172617 100644 --- a/packages/flow/docs/TUTORIAL.md +++ b/packages/flow/docs/TUTORIAL.md @@ -117,6 +117,23 @@ free-form halt reason. It carries the bundle digest, so anyone can run the same public tutorial and compare. The complete field set is in [`RECEIPTS.md`](RECEIPTS.md). +`openadapt quickstart` compiles its bundled MockMed recording with a fixed +`reproducible_seed` (see [`phi_at_rest.md`](phi_at_rest.md)) when the installed +openadapt-flow supports it, so repeated runs of one release produce the same +program bundle and the same `bundle_content_digest`. This has been measured +for headless runs on macOS. A run that encrypts its files at rest (the +default) and one that doesn't give two different digests, since `encrypted` +is part of the program. A visible (`--watch`) run or another operating system +may render the screenshots differently and so give another digest. OpenAdapt +Cloud lists a published tutorial Seal only +when that digest is in its pinned list (`RECEIPT_GALLERY_SAMPLE_BUNDLE_DIGESTS`). +The digest belongs to a release: it changes whenever the tutorial app, the +recorded demonstration, or the compiler's output changes, so each release that +changes it needs its new digest added to that list. Check it by running the +quickstart twice and comparing `content_digest` in `bundle/manifest.json`. +`openadapt-flow tutorial` and `demo` still compile with fresh random salts, so +their digests differ from run to run. + ## Drive the same stages by hand ```bash diff --git a/packages/flow/docs/phi_at_rest.md b/packages/flow/docs/phi_at_rest.md index a2f788fe91..d51419d23f 100644 --- a/packages/flow/docs/phi_at_rest.md +++ b/packages/flow/docs/phi_at_rest.md @@ -663,6 +663,17 @@ can be brute-forced by anyone holding the bundle and the salt. Set `OPENADAPT_FLOW_IDENTITY_SALT` at both compile and replay to keep the salt out of the bundle. In a sealed bundle the template is encrypted as well. +Each compile draws fresh random salts for the identity template and the layout +fingerprint's scale landmarks, so salted hashes of the same screen text can't +be linked across bundles. `compile_recording(..., reproducible_seed=b"...")` +is an opt-in for synthetic recordings only: it derives both salts from the +seed (HMAC-SHA256, the same 16-byte format), fixes `created_at`, and derives +`recording_id` from the seed, so recompiling the same recording gives the same +content digest. Anyone who knows the seed can test guesses against the hashes, +so never use it with real data. `OPENADAPT_FLOW_IDENTITY_SALT` still takes +precedence. Only `openadapt quickstart` passes a seed, for its bundled +synthetic tutorial. + ## Governance - `.gitignore` excludes bundle output directories; the committed diff --git a/packages/flow/openadapt_flow/compiler/compile.py b/packages/flow/openadapt_flow/compiler/compile.py index bf4cd3263c..b36973a51c 100644 --- a/packages/flow/openadapt_flow/compiler/compile.py +++ b/packages/flow/openadapt_flow/compiler/compile.py @@ -11,6 +11,7 @@ import dataclasses import difflib import hashlib +import hmac import json import logging import math @@ -2815,6 +2816,20 @@ def _locale_invariants_from_meta(meta: dict[str, Any]) -> Any: ) from exc +#: ``Workflow.created_at`` of a reproducible compile (``reproducible_seed``): +#: a fixed value, since a wall-clock time would change the content digest. +REPRODUCIBLE_CREATED_AT = "1970-01-01T00:00:00+00:00" + + +def _reproducible_recording_id(seed: bytes) -> str: + """The ``recording_id`` of a reproducible compile, in the recorder's + ``uuid4().hex`` format: 32 hex characters derived from the seed.""" + + return hmac.new( + bytes(seed), b"openadapt-flow/recording-id/v1", hashlib.sha256 + ).hexdigest()[:32] + + def compile_recording( recording_dir: Path | str, out_bundle_dir: Path | str, @@ -2883,6 +2898,7 @@ def _compile_recording( bind_effect_params: bool = False, drop_redundant_keys: bool = False, phi_free_identity: bool = True, + reproducible_seed: Optional[bytes] = None, ) -> Workflow: """Compile a recording directory into a workflow bundle. @@ -3022,6 +3038,20 @@ def _compile_recording( in the demonstration. Off by default: the TYPE read-back at replay doesn't catch a wrong drop (see :mod:`openadapt_flow.compiler.fixup_passes`). + reproducible_seed: Opt-in reproducible build, for SYNTHETIC + recordings only (a bundled tutorial or test fixture). None (the + default) keeps every per-bundle salt fresh and random, so salted + hashes of screen text cannot be linked across real bundles. With + a seed, the identity-template salt and the layout-fingerprint + landmark salt are derived from it + (:func:`openadapt_flow.runtime.identity_template.new_salt_hex`), + ``created_at`` is the fixed :data:`REPRODUCIBLE_CREATED_AT`, and + ``recording_id`` is derived from the seed instead of copied from + the recording's random ``meta.json`` id. Two compiles of + recordings with the same frames and events then give the same + content digest. Anyone who knows the seed can test guesses + against the salted hashes, so never pass one for a real + recording. ``OPENADAPT_FLOW_IDENTITY_SALT`` still wins over it. Returns: The compiled :class:`Workflow` (also saved to the bundle). @@ -3037,6 +3067,10 @@ def _compile_recording( from openadapt_flow.compiler.codegen import render_workflow_py recording = Path(recording_dir) + if reproducible_seed is not None and ( + not isinstance(reproducible_seed, (bytes, bytearray)) or not reproducible_seed + ): + raise ValueError("reproducible_seed must be non-empty bytes") bundle = Path(out_bundle_dir) meta = json.loads(_sealed.read_text(recording / "meta.json")) review = meta.get("multi_surface_record") @@ -3162,7 +3196,7 @@ def _compile_recording( constellations: dict[str, "_constellation.TargetConstellation"] = {} from openadapt_flow.runtime import render_scale as _render_scale - scale_salt = _render_scale.new_salt_hex() + scale_salt = _render_scale.new_salt_hex(reproducible_seed) scale_landmarks: dict[str, list[list[Any]]] = {} def cached_lines(i: int, suffix: str, png: bytes) -> list[OcrLine]: @@ -4647,7 +4681,11 @@ def _constellation_ocr( ) workflow = Workflow( name=name, - recording_id=meta.get("id"), + recording_id=( + meta.get("id") + if reproducible_seed is None + else _reproducible_recording_id(reproducible_seed) + ), viewport=tuple(viewport) if viewport else None, backend_hints=backend_hints, locale_invariants=locale_invariants, @@ -4678,6 +4716,8 @@ def _constellation_ocr( }, ), ) + if reproducible_seed is not None: + workflow.created_at = REPRODUCIBLE_CREATED_AT source_recording_sha256: Optional[str] = None if _sealed.is_file(recording / ".openadapt-approval.json"): @@ -4966,7 +5006,7 @@ def _constellation_ocr( # hashes the bands itself once the loop's row columns are known # (compiler.induction.phi_free_program_identity). if phi_free_identity: - _phi_free_identity(workflow) + _phi_free_identity(workflow, seed=reproducible_seed) # PHI governance manifest (audit REM-1): classify the bundle so an operator # inventory and the pre-commit/CI guard can act on it. @@ -5185,7 +5225,7 @@ def _attach_submit_bindings( typed_since_commit = [] -def _phi_free_identity(workflow: Workflow) -> None: +def _phi_free_identity(workflow: Workflow, *, seed: Optional[bytes] = None) -> None: """Convert every anchor's plaintext identity evidence to a PHI-free, salted-hash :class:`~openadapt_flow.ir.IdentityTemplate` in place. @@ -5198,7 +5238,7 @@ def _phi_free_identity(workflow: Workflow) -> None: new_salt_hex, ) - salt = new_salt_hex() + salt = new_salt_hex(seed, purpose="identity") for step in workflow.steps: anchor = step.anchor if anchor is None or anchor.identity_template is not None: diff --git a/packages/flow/openadapt_flow/runtime/identity_template.py b/packages/flow/openadapt_flow/runtime/identity_template.py index f5f34e67ce..bfd9672927 100644 --- a/packages/flow/openadapt_flow/runtime/identity_template.py +++ b/packages/flow/openadapt_flow/runtime/identity_template.py @@ -110,12 +110,36 @@ def salted_digest(salt_hex: str, text: str) -> str: return _signal_hash(_salt_bytes(salt_hex), text) -def new_salt_hex() -> str: - """Fresh per-bundle salt (hex). Empty when an external env salt is set, so - the bundle stores no salt and the hashes are one-way without the secret.""" +# Domain separation for salts derived from a reproducible-build seed. Changing +# this string changes every reproducible bundle's digest. +_SEEDED_SALT_DOMAIN = b"openadapt-flow/seeded-salt/v1:" + + +def new_salt_hex(seed: Optional[bytes] = None, purpose: str = "identity") -> str: + """Per-bundle salt (hex). Empty when an external env salt is set, so the + bundle stores no salt and the hashes are one-way without the secret. + + Without ``seed`` (the default, and the only right choice for a real + recording) the salt is 16 fresh random bytes, so salted hashes of screen + text cannot be linked across bundles. With ``seed`` the salt is + ``HMAC-SHA256(seed, domain + purpose)`` truncated to the same 16 bytes: + the same seed and purpose always give the same salt, which makes a + compile of synthetic data reproducible byte for byte. ``purpose`` keeps + the salts for different uses in one bundle distinct. + """ if os.environ.get(IDENTITY_SALT_ENV): return "" - return os.urandom(16).hex() + if seed is None: + return os.urandom(16).hex() + if not isinstance(seed, (bytes, bytearray)) or not seed: + raise ValueError("a reproducible salt seed must be non-empty bytes") + return ( + hmac.new( + bytes(seed), _SEEDED_SALT_DOMAIN + purpose.encode("utf-8"), hashlib.sha256 + ) + .digest()[:16] + .hex() + ) # --------------------------------------------------------------------------- diff --git a/packages/flow/openadapt_flow/runtime/render_scale.py b/packages/flow/openadapt_flow/runtime/render_scale.py index 12213edd24..f1a0a43f54 100644 --- a/packages/flow/openadapt_flow/runtime/render_scale.py +++ b/packages/flow/openadapt_flow/runtime/render_scale.py @@ -120,10 +120,12 @@ def _digest(salt_hex: str, text: str) -> str: return _hash(_salt_bytes(salt_hex), _canonical(text)) -def new_salt_hex() -> str: +def new_salt_hex(seed: Optional[bytes] = None) -> str: + """Per-bundle landmark salt; see + :func:`openadapt_flow.runtime.identity_template.new_salt_hex`.""" from openadapt_flow.runtime.identity_template import new_salt_hex as _new - return _new() + return _new(seed, purpose="scale-landmarks") def scale_landmark_set( diff --git a/packages/flow/tests/test_reproducible_compile.py b/packages/flow/tests/test_reproducible_compile.py new file mode 100644 index 0000000000..3b05b25eea --- /dev/null +++ b/packages/flow/tests/test_reproducible_compile.py @@ -0,0 +1,148 @@ +"""Opt-in reproducible compile (``compile_recording(reproducible_seed=...)``). + +A synthetic recording compiled twice with the same seed gives the same content +digest, even when the two recordings carry different random ids and times. +Without a seed every compile gets fresh random salts, so salted hashes of +screen text cannot be linked across bundles. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from openadapt_flow.compiler import compile_recording +from openadapt_flow.compiler.compile import REPRODUCIBLE_CREATED_AT +from openadapt_flow.runtime import identity_template, render_scale +from openadapt_flow.runtime.layout_drift import FINGERPRINT_ASSET +from tests.test_compiler import blank, draw_button, draw_text, write_frame + +SEED = b"test-reproducible-seed" + + +@pytest.fixture(autouse=True) +def _no_external_salt(monkeypatch): + monkeypatch.delenv(identity_template.IDENTITY_SALT_ENV, raising=False) + + +def _recording(root: Path, recording_id: str, created_at: str) -> Path: + rec = root / f"rec-{recording_id}" + (rec / "frames").mkdir(parents=True) + before = blank() + # A row: name | priority | [Open] button, so the click gets an identity + # band (the identity-template salt) and landmarks (the fingerprint salt). + draw_text(before, 40, 430, "Jane Sample") + draw_text(before, 400, 430, "High") + draw_button(before, 560, 400, 160, 48, "Open") + after = before.copy() + draw_text(after, 420, 244, "Patient Chart Overview") + write_frame(rec, 0, "before", before) + write_frame(rec, 0, "after", after) + (rec / "events.jsonl").write_text( + json.dumps({"i": 0, "kind": "click", "x": 640, "y": 424, "t": 1.0}) + "\n" + ) + (rec / "meta.json").write_text( + json.dumps( + { + "id": recording_id, + "created_at": created_at, + "viewport": [1280, 800], + "app_url": "http://x/", + "params": {}, + } + ) + ) + return rec + + +def _compile(tmp_path: Path, tag: str, recording: Path, **kwargs): + bundle = tmp_path / f"bundle-{tag}" + workflow = compile_recording(recording, bundle, name="repro", **kwargs) + manifest = json.loads((bundle / "manifest.json").read_text()) + return workflow, bundle, manifest["content_digest"] + + +def _salts(workflow, bundle: Path) -> tuple[set[str], str]: + identity = { + step.anchor.identity_template.salt + for step in workflow.steps + if step.anchor is not None and step.anchor.identity_template is not None + } + # Read the asset the way the compiler wrote it: sealed under the default + # at-rest policy, plain only when the suite opts out. + from openadapt_flow import sealed_set + + fingerprint = bundle / FINGERPRINT_ASSET + scale = "" + if sealed_set.is_file(fingerprint): + scale = json.loads(sealed_set.read_text(fingerprint)).get("scale_landmarks", {}) + scale = scale.get("salt", "") if isinstance(scale, dict) else "" + return identity, scale + + +def test_seeded_salt_is_stable_and_shaped_like_a_random_one(): + salt = identity_template.new_salt_hex(SEED, purpose="identity") + assert salt == identity_template.new_salt_hex(SEED, purpose="identity") + assert len(salt) == len(identity_template.new_salt_hex()) == 32 + bytes.fromhex(salt) + assert salt != identity_template.new_salt_hex(SEED, purpose="scale-landmarks") + assert salt != identity_template.new_salt_hex(b"other", purpose="identity") + assert render_scale.new_salt_hex(SEED) == render_scale.new_salt_hex(SEED) + assert render_scale.new_salt_hex(SEED) != salt + + +def test_unseeded_salts_stay_random(): + assert identity_template.new_salt_hex() != identity_template.new_salt_hex() + assert render_scale.new_salt_hex() != render_scale.new_salt_hex() + + +def test_external_salt_still_wins_over_a_seed(monkeypatch): + monkeypatch.setenv(identity_template.IDENTITY_SALT_ENV, "operator-secret") + assert identity_template.new_salt_hex(SEED) == "" + assert render_scale.new_salt_hex(SEED) == "" + + +@pytest.mark.parametrize("seed", [b"", "a string"]) +def test_bad_seed_is_refused(seed): + with pytest.raises(ValueError): + identity_template.new_salt_hex(seed) # type: ignore[arg-type] + + +def test_same_seed_gives_the_same_digest(tmp_path): + first = _recording(tmp_path, "a" * 32, "2026-07-06T10:00:00+00:00") + second = _recording(tmp_path, "b" * 32, "2026-07-06T10:05:00+00:00") + wf1, b1, d1 = _compile(tmp_path, "1", first, reproducible_seed=SEED) + wf2, b2, d2 = _compile(tmp_path, "2", second, reproducible_seed=SEED) + + assert d1 == d2 + assert wf1.created_at == wf2.created_at == REPRODUCIBLE_CREATED_AT + assert wf1.recording_id == wf2.recording_id + assert wf1.recording_id not in {"a" * 32, "b" * 32} + assert len(wf1.recording_id) == 32 + identity1, scale1 = _salts(wf1, b1) + assert identity1, "the fixture must exercise the identity-template salt" + assert scale1, "the fixture must exercise the layout-fingerprint salt" + assert (identity1, scale1) == _salts(wf2, b2) + + +def test_no_seed_keeps_fresh_salts_and_the_recording_id(tmp_path): + recording = _recording(tmp_path, "c" * 32, "2026-07-06T10:00:00+00:00") + wf1, b1, d1 = _compile(tmp_path, "1", recording) + wf2, b2, d2 = _compile(tmp_path, "2", recording) + + assert d1 != d2 + assert wf1.recording_id == "c" * 32 + assert wf1.created_at != REPRODUCIBLE_CREATED_AT + identity1, scale1 = _salts(wf1, b1) + identity2, scale2 = _salts(wf2, b2) + assert identity1 and identity1.isdisjoint(identity2) + assert scale1 and scale1 != scale2 + + +def test_different_seeds_give_different_digests(tmp_path): + recording = _recording(tmp_path, "d" * 32, "2026-07-06T10:00:00+00:00") + _, _, d1 = _compile(tmp_path, "1", recording, reproducible_seed=SEED) + _, _, d2 = _compile(tmp_path, "2", recording, reproducible_seed=b"other") + assert d1 != d2 diff --git a/scripts/ci/flow_test_durations.json b/scripts/ci/flow_test_durations.json index f2748f5217..e513949a72 100644 --- a/scripts/ci/flow_test_durations.json +++ b/scripts/ci/flow_test_durations.json @@ -668,6 +668,7 @@ "tests/test_report.py": 0.2, "tests/test_report_redaction.py": 0.7, "tests/test_report_transaction_outcome.py": 0.1, + "tests/test_reproducible_compile.py": 3.9, "tests/test_request_binding.py": 8.6, "tests/test_request_binding_integration.py": 12.4, "tests/test_resolver.py": 0.3, diff --git a/tests/test_quickstart_reproducible.py b/tests/test_quickstart_reproducible.py new file mode 100644 index 0000000000..c677c4bce1 --- /dev/null +++ b/tests/test_quickstart_reproducible.py @@ -0,0 +1,61 @@ +"""The quickstart compiles its synthetic tutorial reproducibly. + +OpenAdapt Cloud lists a published tutorial Seal only when its bundle digest is +pinned, so every quickstart must compile the same bundle. The quickstart +passes a constant ``reproducible_seed`` to the compiler for the bundled +tutorial; an older compiler without the keyword compiles as before. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +pytest.importorskip("openadapt_flow.compiler.compile") + + +def _compile(tmp_path, monkeypatch): + import openadapt_flow.compiler as compiler + import openadapt_flow.tutorial as tutorial + + from openadapt.quickstart.engine import FlowEngine + + calls = [] + + def fake_compile(recording_dir, bundle_dir, **kwargs): + calls.append(kwargs) + return SimpleNamespace(steps=[object()] * 6, name=kwargs["name"]) + + monkeypatch.setattr(compiler, "compile_recording", fake_compile) + monkeypatch.setattr(tutorial, "consequential_step", lambda workflow: None) + monkeypatch.setattr(tutorial, "certify_tutorial", lambda workflow: None) + assert FlowEngine(tmp_path, visible=False).compile() == 6 + return calls + + +def test_the_tutorial_compile_passes_the_reproducible_seed(tmp_path, monkeypatch): + import openadapt_flow.compiler.compile as compile_module + + from openadapt.quickstart.engine import TUTORIAL_REPRODUCIBLE_SEED + + def new_inner(recording_dir, out_bundle_dir, *, name, reproducible_seed=None): + raise AssertionError("not called") + + # Independent of the installed openadapt-flow version. + monkeypatch.setattr(compile_module, "_compile_recording", new_inner) + + (kwargs,) = _compile(tmp_path, monkeypatch) + assert kwargs["reproducible_seed"] == TUTORIAL_REPRODUCIBLE_SEED + assert isinstance(TUTORIAL_REPRODUCIBLE_SEED, bytes) and TUTORIAL_REPRODUCIBLE_SEED + + +def test_an_older_compiler_without_the_keyword_still_compiles(tmp_path, monkeypatch): + import openadapt_flow.compiler.compile as compile_module + + def old_inner(recording_dir, out_bundle_dir, *, name, mine_effects=False): + raise AssertionError("not called") + + monkeypatch.setattr(compile_module, "_compile_recording", old_inner) + (kwargs,) = _compile(tmp_path, monkeypatch) + assert "reproducible_seed" not in kwargs