Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions openadapt/quickstart/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from __future__ import annotations

import contextlib
import importlib
import inspect
import json
import threading
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions packages/flow/docs/TUTORIAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions packages/flow/docs/phi_at_rest.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 45 additions & 5 deletions packages/flow/openadapt_flow/compiler/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import dataclasses
import difflib
import hashlib
import hmac
import json
import logging
import math
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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).
Expand All @@ -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")
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"):
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand All @@ -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:
Expand Down
32 changes: 28 additions & 4 deletions packages/flow/openadapt_flow/runtime/identity_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
)


# ---------------------------------------------------------------------------
Expand Down
6 changes: 4 additions & 2 deletions packages/flow/openadapt_flow/runtime/render_scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading