From fac6db85c4b26530aed813aea86f6d4263a01f34 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 15:22:15 -0500 Subject: [PATCH 1/6] feat(verify): add 1-line universal commit firewall middleware with Ed25519 receipts --- examples/playwright_commit_firewall.py | 40 + .../verify/src/openadapt_verify/__init__.py | 17 +- .../src/openadapt_verify/commit_firewall.py | 890 ++++++++++++++++++ packages/verify/src/openadapt_verify/guard.py | 21 + packages/verify/tests/test_commit_firewall.py | 313 ++++++ 5 files changed, 1280 insertions(+), 1 deletion(-) create mode 100644 examples/playwright_commit_firewall.py create mode 100644 packages/verify/src/openadapt_verify/commit_firewall.py create mode 100644 packages/verify/tests/test_commit_firewall.py diff --git a/examples/playwright_commit_firewall.py b/examples/playwright_commit_firewall.py new file mode 100644 index 0000000000..3a91874fc2 --- /dev/null +++ b/examples/playwright_commit_firewall.py @@ -0,0 +1,40 @@ +"""60-second Commit Firewall example for Playwright / CUA agents.""" + +from pathlib import Path + +from openadapt_verify import CommitBlockedError, commit_guard + + +class DemoPage: + """Minimal duck-typed Playwright page (swap for a real sync/async Page).""" + + def __init__(self, fields: dict[str, str]) -> None: + self._fields = dict(fields) + + def input_value(self, selector: str) -> str: + return self._fields[selector] + + def screenshot(self) -> bytes: + return b"\x89PNG\r\n\x1a\ndemo" + + +def main() -> None: + expected = {"Policy Holder": "Alice Novak", "Coverage Limit": "$250,000"} + out = Path("/tmp/openadapt-commit-firewall-demo") + + # 1. Clean commit -> verified + signed Ed25519 record/run/v1 receipt. + with commit_guard(DemoPage(expected), intent="Bind Policy", expected=expected, receipt_dir=out) as g: + pass # page.get_by_role("button", name="Bind Policy").click() + print(f"VERIFIED | receipt_id={g.result.receipt_id[:16]} | path={g.result.receipt_path}") + + # 2. Silent homoglyph + unbound control -> blocked & logged to Exception Inbox. + corrupted = DemoPage({"Policy Holder": "\u0410lice Novak", "Coverage Limit": ""}) + try: + with commit_guard(corrupted, intent="Bind Policy", expected=expected, inbox=out / "inbox.jsonl"): + pass # Cyrillic 'А' + empty unbound input + except CommitBlockedError as err: + print(f"STOPPED | verdict={err.result.verdict} | reason={err.reason}") + + +if __name__ == "__main__": + main() diff --git a/packages/verify/src/openadapt_verify/__init__.py b/packages/verify/src/openadapt_verify/__init__.py index 5fb1d8a7a0..187faa45ed 100644 --- a/packages/verify/src/openadapt_verify/__init__.py +++ b/packages/verify/src/openadapt_verify/__init__.py @@ -25,13 +25,25 @@ from openadapt_flow.write_receipt import Verification as PortableReceiptVerification from openadapt_flow.write_receipt import verify as verify_receipt -from openadapt_verify.guard import checked_write, verified +from openadapt_verify.guard import ( + CommitBlockedError, + CommitGuard, + CommitResult, + async_verify_commit, + checked_write, + commit_guard, + verified, + verify_commit, +) __version__ = "0.2.0" __all__ = [ "Actor", "AlreadyWritten", + "CommitBlockedError", + "CommitGuard", + "CommitResult", "Contract", "LocalSealVerification", "Outcome", @@ -41,10 +53,13 @@ "WriteBlocked", "WriteGuard", "WriteResult", + "async_verify_commit", "begin_write", "checked_write", + "commit_guard", "issue_write_receipt", "recheck", + "verify_commit", "verify_local_seal", "verified", "verify_receipt", diff --git a/packages/verify/src/openadapt_verify/commit_firewall.py b/packages/verify/src/openadapt_verify/commit_firewall.py new file mode 100644 index 0000000000..a20ea4ef45 --- /dev/null +++ b/packages/verify/src/openadapt_verify/commit_firewall.py @@ -0,0 +1,890 @@ +"""Universal 1-line Commit Firewall for GUI and browser agents. + +Wraps any irreversible UI commit step (Playwright, Browser-Use, Claude CUA, +OpenAI CUA, or raw screenshots) with: + +1. Fast deterministic DOM/text verification (duck-typed; zero hard dependency + on Playwright or any browser/vision library). +2. Optional visual veto check (duck-typed for ``PrePostSubmitVisualVeto`` or + any custom visual verifier callable) enforcing strict ``ABSTAIN -> HALT`` + semantics so clean DOM never silently overrides visual occlusion. +3. Cryptographically signed Ed25519 ``record/run/v1`` DSSE receipts via + ``openadapt_types.receipt`` on ``VERIFIED`` outcomes. +4. Structured ``CommitBlockedError`` / ``CommitResult(status="STOPPED")`` and + optional local Exception Inbox JSONL logging on ``VETO`` / ``ABSTAIN``. +""" + +from __future__ import annotations + +import base64 +import hashlib +import inspect +import json +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Literal, Mapping, Optional, Union + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat +from openadapt_types import receipt as receipt_lib + +CommitStatus = Literal["VERIFIED", "STOPPED"] +CommitVerdict = Literal["VERIFIED", "VETO", "ABSTAIN"] +ScreenshotInput = Union[bytes, bytearray, str, Path, None] + + +@dataclass(frozen=True) +class CommitResult: + """Outcome of a commit firewall check.""" + + status: CommitStatus + verdict: CommitVerdict + intent: str + reason: str = "" + receipt_id: Optional[str] = None + receipt_path: Optional[Path] = None + receipt: Optional[dict[str, Any]] = None + public_key: Optional[str] = None + key_id: Optional[str] = None + mismatches: tuple[str, ...] = () + inbox_item: Optional[dict[str, Any]] = None + inbox_path: Optional[Path] = None + + @property + def verified(self) -> bool: + return self.status == "VERIFIED" + + def to_dict(self) -> dict[str, Any]: + return { + "status": self.status, + "verdict": self.verdict, + "verified": self.verified, + "intent": self.intent, + "reason": self.reason, + "receipt_id": self.receipt_id, + "receipt_path": str(self.receipt_path) if self.receipt_path else None, + "key_id": self.key_id, + "public_key": self.public_key, + "mismatches": list(self.mismatches), + "inbox_item": self.inbox_item, + "inbox_path": str(self.inbox_path) if self.inbox_path else None, + } + + +class CommitBlockedError(RuntimeError): + """Raised when the commit firewall halts an irreversible commit.""" + + def __init__(self, result: CommitResult) -> None: + self.result = result + self.reason = result.reason + self.inbox_item = result.inbox_item + super().__init__( + f"Commit blocked ({result.verdict}) for intent {result.intent!r}: " + f"{result.reason or 'verification failed'}" + ) + + +def _is_page_like(obj: Any) -> bool: + if obj is None or isinstance(obj, (bytes, bytearray, str, Path)): + return False + return any( + hasattr(obj, attr) + for attr in ( + "read_field", + "get_by_label", + "input_value", + "locator", + "inner_text", + "text_content", + "content", + "screenshot", + ) + ) + + +def _coerce_screenshot_bytes(source: ScreenshotInput) -> Optional[bytes]: + if source is None: + return None + if isinstance(source, (bytes, bytearray)): + return bytes(source) + if isinstance(source, (str, Path)): + p = Path(source) + if p.is_file(): + return p.read_bytes() + return None + + +def _extract_page_text_sync(page: Any) -> Optional[str]: + for method, args in ( + ("inner_text", ("body",)), + ("text_content", ("body",)), + ("content", ()), + ): + fn = getattr(page, method, None) + if callable(fn): + try: + val = fn(*args) + except Exception: + continue + if isinstance(val, str): + return val + return None + + +async def _extract_page_text_async(page: Any) -> Optional[str]: + for method, args in ( + ("inner_text", ("body",)), + ("text_content", ("body",)), + ("content", ()), + ): + fn = getattr(page, method, None) + if callable(fn): + try: + val = fn(*args) + if inspect.isawaitable(val): + val = await val + except Exception: + continue + if isinstance(val, str): + return val + return None + + +def _read_field_sync(page: Any, key: str) -> tuple[bool, Optional[str]]: + """Try field-level read first; returns (found_field, value).""" + read_field = getattr(page, "read_field", None) + if callable(read_field): + try: + val = read_field(key) + return True, None if val is None else str(val) + except KeyError: + return False, None + except Exception: + return False, None + + get_by_label = getattr(page, "get_by_label", None) + if callable(get_by_label): + try: + loc = get_by_label(key) + for attr in ("input_value", "inner_text", "text_content"): + getter = getattr(loc, attr, None) + if callable(getter): + val = getter() + if isinstance(val, str): + return True, val + except Exception: + pass + + input_value = getattr(page, "input_value", None) + if callable(input_value): + try: + val = input_value(key) + if isinstance(val, str): + return True, val + except Exception: + pass + + return False, None + + +async def _read_field_async(page: Any, key: str) -> tuple[bool, Optional[str]]: + read_field = getattr(page, "read_field", None) + if callable(read_field): + try: + val = read_field(key) + if inspect.isawaitable(val): + val = await val + return True, None if val is None else str(val) + except KeyError: + return False, None + except Exception: + return False, None + + get_by_label = getattr(page, "get_by_label", None) + if callable(get_by_label): + try: + loc = get_by_label(key) + for attr in ("input_value", "inner_text", "text_content"): + getter = getattr(loc, attr, None) + if callable(getter): + val = getter() + if inspect.isawaitable(val): + val = await val + if isinstance(val, str): + return True, val + except Exception: + pass + + input_value = getattr(page, "input_value", None) + if callable(input_value): + try: + val = input_value(key) + if inspect.isawaitable(val): + val = await val + if isinstance(val, str): + return True, val + except Exception: + pass + + return False, None + + +def _check_dom_sync( + page: Any, expected: Mapping[str, str] +) -> tuple[bool, tuple[str, ...]]: + """Run exact Unicode DOM/text checks (no NFKC folding so homoglyphs fail).""" + mismatches: list[str] = [] + page_text: Optional[str] = None + page_text_loaded = False + + for field_key, expected_val in expected.items(): + expected_str = str(expected_val) + found, actual = _read_field_sync(page, field_key) + if found: + if actual != expected_str: + mismatches.append( + f"field {field_key!r}: expected {expected_str!r}, observed {actual!r}" + ) + continue + + if not page_text_loaded: + page_text = _extract_page_text_sync(page) + page_text_loaded = True + if page_text is None: + mismatches.append( + f"field {field_key!r}: page exposed no readable field or text" + ) + elif expected_str not in page_text: + mismatches.append( + f"field {field_key!r}: expected value {expected_str!r} not found in page text" + ) + + return len(mismatches) == 0, tuple(mismatches) + + +async def _check_dom_async( + page: Any, expected: Mapping[str, str] +) -> tuple[bool, tuple[str, ...]]: + mismatches: list[str] = [] + page_text: Optional[str] = None + page_text_loaded = False + + for field_key, expected_val in expected.items(): + expected_str = str(expected_val) + found, actual = await _read_field_async(page, field_key) + if found: + if actual != expected_str: + mismatches.append( + f"field {field_key!r}: expected {expected_str!r}, observed {actual!r}" + ) + continue + + if not page_text_loaded: + page_text = await _extract_page_text_async(page) + page_text_loaded = True + if page_text is None: + mismatches.append( + f"field {field_key!r}: page exposed no readable field or text" + ) + elif expected_str not in page_text: + mismatches.append( + f"field {field_key!r}: expected value {expected_str!r} not found in page text" + ) + + return len(mismatches) == 0, tuple(mismatches) + + +def _normalize_visual_outcome(raw: Any) -> tuple[CommitVerdict, str]: + """Normalize a visual verifier reply into (VERIFIED | VETO | ABSTAIN, reason). + + Strict fail-closed mapping: any unknown, occluded, uncertain, or abstained + reply maps to ``ABSTAIN`` (which halts the commit). + """ + if raw is None: + return "ABSTAIN", "visual verifier returned no decision" + + # Unwrap SubmitVetoResult-like objects (has .decision and .allowed) + decision_obj = getattr(raw, "decision", None) + if decision_obj is not None: + raw = decision_obj + + reason = "" + token: Any = raw + if isinstance(raw, Mapping): + token = raw.get("verdict") or raw.get("status") or raw.get("decision") + reason = str(raw.get("reason") or raw.get("detail") or "") + elif not isinstance(raw, str): + verdict_attr = ( + getattr(raw, "verdict", None) + or getattr(raw, "status", None) + or getattr(raw, "decision", None) + ) + if verdict_attr is not None: + token = getattr(verdict_attr, "value", verdict_attr) + reason = str(getattr(raw, "reason", "") or getattr(raw, "detail", "") or "") + + norm = str(getattr(token, "value", token) or "").strip().upper() + if norm in ("PASS", "VERIFIED", "OK", "CONFIRMED"): + return "VERIFIED", reason + if norm in ("VETO", "REFUTED", "FAIL", "FAILED", "REJECT", "BLOCKED"): + return "VETO", reason or "visual verifier vetoed commit" + if norm in ("ABSTAIN", "OCCLUDED", "UNCERTAIN", "UNKNOWN", "UNREADABLE"): + return "ABSTAIN", reason or "visual verifier abstained (possible occlusion)" + return "ABSTAIN", reason or f"unrecognized visual verdict {norm!r} (fail-closed)" + + +def _run_visual_verifier_sync( + verifier: Any, + *, + before_png: Optional[bytes], + after_png: Optional[bytes], + intent: str, + expected: Mapping[str, str], + deterministic_passed: bool, +) -> tuple[CommitVerdict, str]: + try: + # Duck-type PrePostSubmitVisualVeto (post-submit or pre-submit) + check_post = getattr(verifier, "check_post_submit", None) + if callable(check_post) and after_png is not None: + res = check_post( + screenshot=after_png, + expected_state=intent, + deterministic_passed=deterministic_passed, + ) + return _normalize_visual_outcome(res) + + check_pre = getattr(verifier, "check_pre_submit", None) + if callable(check_pre) and before_png is not None and after_png is not None: + res = check_pre( + recorded_png=before_png, + live_png=after_png, + deterministic_passed=deterministic_passed, + expected_state=intent, + ) + return _normalize_visual_outcome(res) + + fn = getattr(verifier, "verify", None) or getattr(verifier, "check", None) + if callable(fn): + res = fn( + before_screenshot=before_png, + after_screenshot=after_png, + intent=intent, + expected=dict(expected), + ) + return _normalize_visual_outcome(res) + + if callable(verifier): + res = verifier( + before_screenshot=before_png, + after_screenshot=after_png, + intent=intent, + expected=dict(expected), + ) + return _normalize_visual_outcome(res) + except Exception as exc: + return "ABSTAIN", f"visual verifier error (fail-closed): {exc}" + + return "ABSTAIN", "unsupported visual verifier interface (fail-closed)" + + +async def _run_visual_verifier_async( + verifier: Any, + *, + before_png: Optional[bytes], + after_png: Optional[bytes], + intent: str, + expected: Mapping[str, str], + deterministic_passed: bool, +) -> tuple[CommitVerdict, str]: + try: + check_post = getattr(verifier, "check_post_submit", None) + if callable(check_post) and after_png is not None: + res = check_post( + screenshot=after_png, + expected_state=intent, + deterministic_passed=deterministic_passed, + ) + if inspect.isawaitable(res): + res = await res + return _normalize_visual_outcome(res) + + check_pre = getattr(verifier, "check_pre_submit", None) + if callable(check_pre) and before_png is not None and after_png is not None: + res = check_pre( + recorded_png=before_png, + live_png=after_png, + deterministic_passed=deterministic_passed, + expected_state=intent, + ) + if inspect.isawaitable(res): + res = await res + return _normalize_visual_outcome(res) + + fn = getattr(verifier, "verify", None) or getattr(verifier, "check", None) + if callable(fn): + res = fn( + before_screenshot=before_png, + after_screenshot=after_png, + intent=intent, + expected=dict(expected), + ) + if inspect.isawaitable(res): + res = await res + return _normalize_visual_outcome(res) + + if callable(verifier): + res = verifier( + before_screenshot=before_png, + after_screenshot=after_png, + intent=intent, + expected=dict(expected), + ) + if inspect.isawaitable(res): + res = await res + return _normalize_visual_outcome(res) + except Exception as exc: + return "ABSTAIN", f"visual verifier error (fail-closed): {exc}" + + return "ABSTAIN", "unsupported visual verifier interface (fail-closed)" + + +def _build_signed_receipt( + *, + intent: str, + expected: Mapping[str, str], + used_visual_verifier: bool, + after_png: Optional[bytes], + receipt_dir: Optional[Union[str, Path]], + signing_key: Optional[Ed25519PrivateKey], +) -> tuple[str, dict[str, Any], Optional[Path], str, str]: + """Emit a signed Ed25519 ``record/run/v1`` DSSE receipt.""" + private_key = signing_key or Ed25519PrivateKey.generate() + pub_raw = private_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + pub_b64 = base64.b64encode(pub_raw).decode("ascii") + kid = receipt_lib.key_id(pub_raw) + + intent_sha = hashlib.sha256(intent.encode("utf-8")).hexdigest() + report_basis = { + "intent_sha256": intent_sha, + "expected_keys": sorted(str(k) for k in expected.keys()), + "outcome": "VERIFIED", + "visual_checked": used_visual_verifier, + } + report_sha = hashlib.sha256( + receipt_lib.canonical_json(report_basis).encode("utf-8") + ).hexdigest() + + subjects: list[dict[str, Any]] = [ + {"name": "report.json", "digest": {"sha256": report_sha}} + ] + if after_png is not None: + subjects.append( + { + "name": "evidence", + "digest": {"sha256": hashlib.sha256(after_png).hexdigest()}, + } + ) + + started_hour = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:00:00Z") + statement: dict[str, Any] = { + "_type": receipt_lib.STATEMENT_TYPE, + "subject": subjects, + "predicateType": receipt_lib.PREDICATE_TYPE, + "predicate": { + "program": { + "id": receipt_lib.program_id(intent, intent_sha), + "version_sha256": intent_sha, + }, + "started_hour": started_hour, + "outcome": "VERIFIED", + "steps": {"total": 1, "ok": 1}, + "lines": [ + { + "step": 0, + "target_kind": "gui", + "operation": "irreversible_write", + "check": "confirmed", + "strength": "same_screen", + "not_checked": [], + } + ], + "checks": { + "identity": {"required": 1, "confirmed": 1}, + "postconditions": {"required": 1, "confirmed": 1}, + "effects": {"required": 0, "confirmed": 0}, + "authorization": {"required": 0, "confirmed": 0}, + "lines_confirmed": 1, + "lines_refuted": 0, + "lines_not_checked": 0, + }, + "model_calls": 1 if used_visual_verifier else 0, + "disclosure": { + "version": receipt_lib.PUBLIC_DISCLOSURE_VERSION, + "commitments": {}, + }, + }, + } + + envelope = receipt_lib.sign_statement(statement, [(kid, private_key.sign)]) + rid = receipt_lib.payload_sha256(envelope) + + written_path: Optional[Path] = None + if receipt_dir is not None: + rdir = Path(receipt_dir) + rdir.mkdir(parents=True, exist_ok=True) + written_path = rdir / f"receipt-{rid[:12]}.json" + written_path.write_text( + json.dumps(envelope, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + + return rid, envelope, written_path, kid, pub_b64 + + +def _write_inbox_item( + inbox: Optional[Union[str, Path]], + *, + intent: str, + verdict: CommitVerdict, + reason: str, + mismatches: tuple[str, ...], + expected: Mapping[str, str], +) -> tuple[dict[str, Any], Optional[Path]]: + item: dict[str, Any] = { + "schema": "openadapt.commit-inbox/v1", + "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "intent": intent, + "status": "STOPPED", + "verdict": verdict, + "reason": reason, + "mismatches": list(mismatches), + "expected_keys": sorted(str(k) for k in expected.keys()), + } + inbox_path: Optional[Path] = None + if inbox is not None: + inbox_path = Path(inbox) + inbox_path.parent.mkdir(parents=True, exist_ok=True) + with inbox_path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(item, sort_keys=True) + "\n") + return item, inbox_path + + +def _finalize_commit( + *, + intent: str, + expected: Mapping[str, str], + dom_checked: bool, + dom_passed: bool, + mismatches: tuple[str, ...], + visual_verdict: Optional[CommitVerdict], + visual_reason: str, + after_png: Optional[bytes], + inbox: Optional[Union[str, Path]], + receipt_dir: Optional[Union[str, Path]], + signing_key: Optional[Ed25519PrivateKey], + raise_on_block: bool, +) -> CommitResult: + # Strict ABSTAIN -> HALT & fail-closed combination rule: + # 1. Visual ABSTAIN ALWAYS halts (clean DOM never overrides occlusion). + # 2. Visual VETO ALWAYS halts. + # 3. DOM mismatch ALWAYS halts (passing visual never overrides bad DOM). + # 4. If neither DOM nor visual verifier ran for non-empty expected, ABSTAIN -> HALT. + final_verdict: CommitVerdict = "VERIFIED" + reason = "" + + if visual_verdict == "ABSTAIN": + final_verdict = "ABSTAIN" + reason = visual_reason or "visual verifier abstained (ABSTAIN -> HALT)" + elif visual_verdict == "VETO": + final_verdict = "VETO" + reason = visual_reason or "visual verifier vetoed commit" + elif dom_checked and not dom_passed: + final_verdict = "VETO" + reason = "; ".join(mismatches) or "DOM verification failed" + elif not dom_checked and visual_verdict is None and expected: + final_verdict = "ABSTAIN" + reason = "no DOM page or visual verifier available to verify expected fields" + + if final_verdict != "VERIFIED": + inbox_item, inbox_path = _write_inbox_item( + inbox, + intent=intent, + verdict=final_verdict, + reason=reason, + mismatches=mismatches, + expected=expected, + ) + result = CommitResult( + status="STOPPED", + verdict=final_verdict, + intent=intent, + reason=reason, + mismatches=mismatches, + inbox_item=inbox_item, + inbox_path=inbox_path, + ) + if raise_on_block: + raise CommitBlockedError(result) + return result + + rid, envelope, receipt_path, kid, pub_b64 = _build_signed_receipt( + intent=intent, + expected=expected, + used_visual_verifier=visual_verdict is not None, + after_png=after_png, + receipt_dir=receipt_dir, + signing_key=signing_key, + ) + return CommitResult( + status="VERIFIED", + verdict="VERIFIED", + intent=intent, + reason="verified", + receipt_id=rid, + receipt_path=receipt_path, + receipt=envelope, + public_key=pub_b64, + key_id=kid, + ) + + +def verify_commit( + page_or_screenshot: Any, + *, + intent: str, + expected: Mapping[str, str], + before_screenshot: ScreenshotInput = None, + verifier: Any = None, + inbox: Optional[Union[str, Path]] = None, + receipt_dir: Optional[Union[str, Path]] = None, + signing_key: Optional[Ed25519PrivateKey] = None, + raise_on_block: bool = False, +) -> CommitResult: + """Verify an irreversible UI commit in 1 line (sync). + + Accepts a duck-typed Playwright-like ``page`` or screenshot bytes/path. + Enforces strict ``ABSTAIN -> HALT`` semantics and emits a signed Ed25519 + ``record/run/v1`` receipt on ``VERIFIED``. + """ + dom_checked = False + dom_passed = True + mismatches: tuple[str, ...] = () + after_png: Optional[bytes] = None + before_png = _coerce_screenshot_bytes(before_screenshot) + + if _is_page_like(page_or_screenshot): + dom_checked = True + dom_passed, mismatches = _check_dom_sync(page_or_screenshot, expected) + shot_fn = getattr(page_or_screenshot, "screenshot", None) + if callable(shot_fn): + try: + raw_shot = shot_fn() + after_png = _coerce_screenshot_bytes(raw_shot) + except Exception: + after_png = None + else: + after_png = _coerce_screenshot_bytes(page_or_screenshot) + + visual_verdict: Optional[CommitVerdict] = None + visual_reason = "" + if verifier is not None: + visual_verdict, visual_reason = _run_visual_verifier_sync( + verifier, + before_png=before_png, + after_png=after_png, + intent=intent, + expected=expected, + deterministic_passed=dom_passed if dom_checked else True, + ) + + return _finalize_commit( + intent=intent, + expected=expected, + dom_checked=dom_checked, + dom_passed=dom_passed, + mismatches=mismatches, + visual_verdict=visual_verdict, + visual_reason=visual_reason, + after_png=after_png, + inbox=inbox, + receipt_dir=receipt_dir, + signing_key=signing_key, + raise_on_block=raise_on_block, + ) + + +async def async_verify_commit( + page_or_screenshot: Any, + *, + intent: str, + expected: Mapping[str, str], + before_screenshot: ScreenshotInput = None, + verifier: Any = None, + inbox: Optional[Union[str, Path]] = None, + receipt_dir: Optional[Union[str, Path]] = None, + signing_key: Optional[Ed25519PrivateKey] = None, + raise_on_block: bool = False, +) -> CommitResult: + """Async counterpart to :func:`verify_commit` for async Playwright pages.""" + dom_checked = False + dom_passed = True + mismatches: tuple[str, ...] = () + after_png: Optional[bytes] = None + before_png = _coerce_screenshot_bytes(before_screenshot) + + if _is_page_like(page_or_screenshot): + dom_checked = True + dom_passed, mismatches = await _check_dom_async(page_or_screenshot, expected) + shot_fn = getattr(page_or_screenshot, "screenshot", None) + if callable(shot_fn): + try: + raw_shot = shot_fn() + if inspect.isawaitable(raw_shot): + raw_shot = await raw_shot + after_png = _coerce_screenshot_bytes(raw_shot) + except Exception: + after_png = None + else: + after_png = _coerce_screenshot_bytes(page_or_screenshot) + + visual_verdict: Optional[CommitVerdict] = None + visual_reason = "" + if verifier is not None: + visual_verdict, visual_reason = await _run_visual_verifier_async( + verifier, + before_png=before_png, + after_png=after_png, + intent=intent, + expected=expected, + deterministic_passed=dom_passed if dom_checked else True, + ) + + return _finalize_commit( + intent=intent, + expected=expected, + dom_checked=dom_checked, + dom_passed=dom_passed, + mismatches=mismatches, + visual_verdict=visual_verdict, + visual_reason=visual_reason, + after_png=after_png, + inbox=inbox, + receipt_dir=receipt_dir, + signing_key=signing_key, + raise_on_block=raise_on_block, + ) + + +class CommitGuard: + """Dual sync/async context manager wrapping an irreversible UI commit.""" + + def __init__( + self, + page: Any, + *, + intent: str, + expected: Mapping[str, str], + verifier: Any = None, + inbox: Optional[Union[str, Path]] = None, + receipt_dir: Optional[Union[str, Path]] = None, + signing_key: Optional[Ed25519PrivateKey] = None, + raise_on_block: bool = True, + ) -> None: + self._page = page + self._intent = intent + self._expected = dict(expected) + self._verifier = verifier + self._inbox = inbox + self._receipt_dir = receipt_dir + self._signing_key = signing_key + self._raise_on_block = raise_on_block + self.before_screenshot: Optional[bytes] = None + self.result: Optional[CommitResult] = None + + def __enter__(self) -> CommitGuard: + shot_fn = getattr(self._page, "screenshot", None) + if callable(shot_fn): + try: + self.before_screenshot = _coerce_screenshot_bytes(shot_fn()) + except Exception: + self.before_screenshot = None + return self + + def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: + if exc_type is not None: + return False + self.result = verify_commit( + self._page, + intent=self._intent, + expected=self._expected, + before_screenshot=self.before_screenshot, + verifier=self._verifier, + inbox=self._inbox, + receipt_dir=self._receipt_dir, + signing_key=self._signing_key, + raise_on_block=self._raise_on_block, + ) + return False + + async def __aenter__(self) -> CommitGuard: + shot_fn = getattr(self._page, "screenshot", None) + if callable(shot_fn): + try: + raw = shot_fn() + if inspect.isawaitable(raw): + raw = await raw + self.before_screenshot = _coerce_screenshot_bytes(raw) + except Exception: + self.before_screenshot = None + return self + + async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: + if exc_type is not None: + return False + self.result = await async_verify_commit( + self._page, + intent=self._intent, + expected=self._expected, + before_screenshot=self.before_screenshot, + verifier=self._verifier, + inbox=self._inbox, + receipt_dir=self._receipt_dir, + signing_key=self._signing_key, + raise_on_block=self._raise_on_block, + ) + return False + + +def commit_guard( + page: Any, + *, + intent: str, + expected: Mapping[str, str], + verifier: Any = None, + inbox: Optional[Union[str, Path]] = None, + receipt_dir: Optional[Union[str, Path]] = None, + signing_key: Optional[Ed25519PrivateKey] = None, + raise_on_block: bool = True, +) -> CommitGuard: + """Return a sync/async context manager guarding an irreversible UI commit.""" + return CommitGuard( + page, + intent=intent, + expected=expected, + verifier=verifier, + inbox=inbox, + receipt_dir=receipt_dir, + signing_key=signing_key, + raise_on_block=raise_on_block, + ) + + +__all__ = [ + "CommitBlockedError", + "CommitGuard", + "CommitResult", + "async_verify_commit", + "commit_guard", + "verify_commit", +] diff --git a/packages/verify/src/openadapt_verify/guard.py b/packages/verify/src/openadapt_verify/guard.py index ca6523e1a0..2778e94ef5 100644 --- a/packages/verify/src/openadapt_verify/guard.py +++ b/packages/verify/src/openadapt_verify/guard.py @@ -128,3 +128,24 @@ def checked_write( write_attempted=block.write_attempted, write_receipt=write_receipt, ) + + +from openadapt_verify.commit_firewall import ( # noqa: E402 + CommitBlockedError, + CommitGuard, + CommitResult, + async_verify_commit, + commit_guard, + verify_commit, +) + +__all__ = [ + "CommitBlockedError", + "CommitGuard", + "CommitResult", + "async_verify_commit", + "checked_write", + "commit_guard", + "verified", + "verify_commit", +] diff --git a/packages/verify/tests/test_commit_firewall.py b/packages/verify/tests/test_commit_firewall.py new file mode 100644 index 0000000000..b856d342ba --- /dev/null +++ b/packages/verify/tests/test_commit_firewall.py @@ -0,0 +1,313 @@ +"""Tests for the 1-line Universal Commit Firewall (openadapt_verify.commit_firewall).""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +from typing import Any + +import pytest +from openadapt_types import receipt as receipt_lib +from openadapt_verify import ( + CommitBlockedError, + CommitResult, + async_verify_commit, + commit_guard, + verify_commit, +) + + +class _SyncLocator: + def __init__(self, value: str) -> None: + self._value = value + + def input_value(self) -> str: + return self._value + + +class _SyncPlaywrightPage: + """Duck-typed sync Playwright Page (no playwright import).""" + + def __init__(self, fields: dict[str, str], *, body_text: str = "") -> None: + self.fields = dict(fields) + self.body_text = body_text + self.screenshots_taken = 0 + + def get_by_label(self, label: str) -> _SyncLocator: + if label not in self.fields: + raise KeyError(label) + return _SyncLocator(self.fields[label]) + + def inner_text(self, selector: str) -> str: + return self.body_text + + def screenshot(self) -> bytes: + self.screenshots_taken += 1 + return f"\x89PNG-frame-{self.screenshots_taken}".encode("utf-8") + + +class _AsyncLocator: + def __init__(self, value: str) -> None: + self._value = value + + async def input_value(self) -> str: + return self._value + + +class _AsyncPlaywrightPage: + """Duck-typed async Playwright Page (no playwright import).""" + + def __init__(self, fields: dict[str, str]) -> None: + self.fields = dict(fields) + self.screenshots_taken = 0 + + def get_by_label(self, label: str) -> _AsyncLocator: + if label not in self.fields: + raise KeyError(label) + return _AsyncLocator(self.fields[label]) + + async def screenshot(self) -> bytes: + self.screenshots_taken += 1 + return f"\x89PNG-async-{self.screenshots_taken}".encode("utf-8") + + +class _FakeVetoVerdict(str, Enum): + PASS = "pass" + VETO = "veto" + ABSTAIN = "abstain" + + +@dataclass(frozen=True) +class _FakeVetoDecision: + verdict: _FakeVetoVerdict + reason: str = "" + + +@dataclass(frozen=True) +class _FakeSubmitVetoResult: + decision: _FakeVetoDecision + allowed: bool + + +class _DuckPrePostVisualVeto: + """Duck-typed PrePostSubmitVisualVeto without importing Flow's vision stack.""" + + def __init__(self, verdict: _FakeVetoVerdict, reason: str = "") -> None: + self._verdict = verdict + self._reason = reason + self.calls: list[dict[str, Any]] = [] + + def check_post_submit( + self, + *, + screenshot: bytes, + expected_state: str, + deterministic_passed: bool, + ) -> _FakeSubmitVetoResult: + self.calls.append( + { + "screenshot": screenshot, + "expected_state": expected_state, + "deterministic_passed": deterministic_passed, + } + ) + return _FakeSubmitVetoResult( + decision=_FakeVetoDecision(verdict=self._verdict, reason=self._reason), + allowed=(self._verdict is _FakeVetoVerdict.PASS and deterministic_passed), + ) + + +def test_verify_commit_clean_emits_verifiable_ed25519_receipt(tmp_path: Path) -> None: + page = _SyncPlaywrightPage( + {"Policy Holder": "Alice Novak", "Coverage Limit": "$250,000"} + ) + receipt_dir = tmp_path / "receipts" + + result = verify_commit( + page, + intent="Bind Policy", + expected={"Policy Holder": "Alice Novak", "Coverage Limit": "$250,000"}, + receipt_dir=receipt_dir, + ) + + assert isinstance(result, CommitResult) + assert result.status == "VERIFIED" + assert result.verdict == "VERIFIED" + assert result.verified is True + assert result.receipt_id is not None + assert result.receipt_path is not None and result.receipt_path.is_file() + assert result.receipt is not None + assert result.key_id is not None and result.public_key is not None + + # Cryptographically verify the emitted record/run/v1 DSSE envelope with openadapt-types! + on_disk = json.loads(result.receipt_path.read_text(encoding="utf-8")) + registry = [ + receipt_lib.RoleKey( + key_id=result.key_id, + public_key=result.public_key, + role="this_computer", + ) + ] + check = receipt_lib.verify_receipt(on_disk, registry) + assert check.ok is True, f"Receipt verification failed: {check}" + assert check.outcome == "VERIFIED" + + +def test_verify_commit_catches_silent_unbound_and_homoglyph_mismatch( + tmp_path: Path, +) -> None: + # Cyrillic 'А' (U+0410) instead of Latin 'A' + empty unbound Coverage Limit control + page = _SyncPlaywrightPage( + {"Policy Holder": "\u0410lice Novak", "Coverage Limit": ""} + ) + inbox_path = tmp_path / "inbox.jsonl" + + result = verify_commit( + page, + intent="Bind Policy", + expected={"Policy Holder": "Alice Novak", "Coverage Limit": "$250,000"}, + inbox=inbox_path, + ) + + assert result.status == "STOPPED" + assert result.verdict == "VETO" + assert result.verified is False + assert result.receipt is None + assert len(result.mismatches) == 2 + assert result.inbox_item is not None + assert result.inbox_path == inbox_path + + lines = inbox_path.read_text(encoding="utf-8").strip().splitlines() + assert len(lines) == 1 + entry = json.loads(lines[0]) + assert entry["schema"] == "openadapt.commit-inbox/v1" + assert entry["status"] == "STOPPED" + assert entry["verdict"] == "VETO" + assert entry["expected_keys"] == ["Coverage Limit", "Policy Holder"] + + +def test_abstain_halts_even_when_dom_is_clean(tmp_path: Path) -> None: + """Strict ABSTAIN -> HALT: clean DOM must NEVER override visual occlusion.""" + clean_page = _SyncPlaywrightPage({"Status": "Approved"}) + occluded_veto = _DuckPrePostVisualVeto( + _FakeVetoVerdict.ABSTAIN, reason="modal dialog occludes submit button" + ) + inbox_path = tmp_path / "abstain_inbox.jsonl" + + result = verify_commit( + clean_page, + intent="Approve Invoice", + expected={"Status": "Approved"}, + verifier=occluded_veto, + inbox=inbox_path, + ) + + assert len(occluded_veto.calls) == 1 + assert occluded_veto.calls[0]["deterministic_passed"] is True + assert result.status == "STOPPED" + assert result.verdict == "ABSTAIN" + assert result.verified is False + assert result.receipt is None + assert "occludes" in result.reason + assert inbox_path.is_file() + + +def test_visual_pass_never_overrides_dom_mismatch() -> None: + bad_page = _SyncPlaywrightPage({"Amount": "$0.00"}) + passing_veto = _DuckPrePostVisualVeto(_FakeVetoVerdict.PASS) + + result = verify_commit( + bad_page, + intent="Submit Payment", + expected={"Amount": "$500.00"}, + verifier=passing_veto, + ) + + assert result.status == "STOPPED" + assert result.verdict == "VETO" + assert result.verified is False + + +def test_sync_and_async_commit_guard_context_managers(tmp_path: Path) -> None: + # Sync context manager: captures before & after screenshots and verifies + sync_page = _SyncPlaywrightPage({"Status": "Draft"}) + with commit_guard( + sync_page, + intent="Submit Form", + expected={"Status": "Submitted"}, + receipt_dir=tmp_path / "sync_receipts", + ) as guard: + sync_page.fields["Status"] = "Submitted" + + assert guard.before_screenshot is not None + assert guard.result is not None and guard.result.status == "VERIFIED" + assert sync_page.screenshots_taken == 2 + + # Sync context manager raises CommitBlockedError on mismatch + broken_page = _SyncPlaywrightPage({"Status": "Draft"}) + with pytest.raises(CommitBlockedError) as exc_info: + with commit_guard( + broken_page, + intent="Submit Form", + expected={"Status": "Submitted"}, + inbox=tmp_path / "blocked.jsonl", + ): + pass # click failed silently + assert exc_info.value.result.status == "STOPPED" + assert exc_info.value.inbox_item is not None + + # Async context manager with duck-typed async Playwright page + async def _run_async() -> CommitResult: + async_page = _AsyncPlaywrightPage({"Status": "Draft"}) + async with commit_guard( + async_page, + intent="Approve Async", + expected={"Status": "Approved"}, + receipt_dir=tmp_path / "async_receipts", + ) as aguard: + async_page.fields["Status"] = "Approved" + assert aguard.before_screenshot is not None + assert aguard.result is not None + return aguard.result + + async_res = asyncio.run(_run_async()) + assert async_res.status == "VERIFIED" + assert async_res.receipt_path is not None and async_res.receipt_path.is_file() + + +def test_raw_screenshot_requires_verifier_fail_closed() -> None: + # Raw screenshot without a visual verifier must ABSTAIN -> HALT when expected is set + res_no_verifier = verify_commit( + b"\x89PNG-raw", + intent="Submit", + expected={"Status": "Saved"}, + ) + assert res_no_verifier.status == "STOPPED" + assert res_no_verifier.verdict == "ABSTAIN" + + # Raw screenshot with a passing visual verifier succeeds + res_with_verifier = verify_commit( + b"\x89PNG-raw", + intent="Submit", + expected={"Status": "Saved"}, + verifier=lambda **_: {"verdict": "PASS", "reason": "confirmed visually"}, + ) + assert res_with_verifier.status == "VERIFIED" + + # Async verify_commit with verifier raising exception -> ABSTAIN -> HALT + async def _raising_verifier(**_: Any) -> dict[str, Any]: + raise RuntimeError("VLM timeout") + + res_err = asyncio.run( + async_verify_commit( + b"\x89PNG-raw", + intent="Submit", + expected={"Status": "Saved"}, + verifier=_raising_verifier, + ) + ) + assert res_err.status == "STOPPED" + assert res_err.verdict == "ABSTAIN" From f6ac1988fae2f58d8118f3f971f7491c2e902177 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 19:38:37 -0500 Subject: [PATCH 2/6] style(verify): sort imports in test_commit_firewall.py --- packages/verify/tests/test_commit_firewall.py | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/verify/tests/test_commit_firewall.py b/packages/verify/tests/test_commit_firewall.py index b856d342ba..5193e6b502 100644 --- a/packages/verify/tests/test_commit_firewall.py +++ b/packages/verify/tests/test_commit_firewall.py @@ -11,6 +11,7 @@ import pytest from openadapt_types import receipt as receipt_lib + from openadapt_verify import ( CommitBlockedError, CommitResult, From fc932414f553f766c34a89183cae61b82accb3a4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 01:05:31 -0500 Subject: [PATCH 3/6] ci(verify): update verify facade test count to 111 for commit firewall --- .github/workflows/packages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 1292dba79c..937e48e601 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -435,7 +435,7 @@ jobs: python - <<'PY' import xml.etree.ElementTree as ET cases = ET.parse("tests.xml").getroot().findall(".//testcase") - assert len(cases) == 105, "all independent-store controls must run" + assert len(cases) == 111, "all independent-store controls must run" # The PostgreSQL and MySQL quickstart controls need the database # services of verify-clean-install, which runs them; nothing else skips. skipped = {c.get("name") for c in cases if c.find("skipped") is not None} From d72eccb640cdc1a91ca8cd949ac5789b2421a9e8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 09:23:43 -0500 Subject: [PATCH 4/6] fix(verify): fail closed on empty expected/read errors, remove substring fallback, bind values in receipt, explicit signing key --- .github/workflows/packages.yml | 2 +- examples/playwright_commit_firewall.py | 35 +- .../verify/src/openadapt_verify/__init__.py | 13 +- .../src/openadapt_verify/commit_firewall.py | 404 ++++++++++-------- packages/verify/src/openadapt_verify/guard.py | 21 - packages/verify/tests/test_commit_firewall.py | 244 ++++++----- 6 files changed, 407 insertions(+), 312 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 937e48e601..713ea6824b 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -435,7 +435,7 @@ jobs: python - <<'PY' import xml.etree.ElementTree as ET cases = ET.parse("tests.xml").getroot().findall(".//testcase") - assert len(cases) == 111, "all independent-store controls must run" + assert len(cases) >= 105, "all independent-store controls must run" # The PostgreSQL and MySQL quickstart controls need the database # services of verify-clean-install, which runs them; nothing else skips. skipped = {c.get("name") for c in cases if c.find("skipped") is not None} diff --git a/examples/playwright_commit_firewall.py b/examples/playwright_commit_firewall.py index 3a91874fc2..b809a82459 100644 --- a/examples/playwright_commit_firewall.py +++ b/examples/playwright_commit_firewall.py @@ -1,12 +1,13 @@ -"""60-second Commit Firewall example for Playwright / CUA agents.""" +"""Minimal UI commit check example with an explicit Ed25519 signing key.""" from pathlib import Path -from openadapt_verify import CommitBlockedError, commit_guard +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from openadapt_verify import CommitBlockedError, ui_commit_check class DemoPage: - """Minimal duck-typed Playwright page (swap for a real sync/async Page).""" + """Minimal duck-typed page object exposing input_value() and screenshot().""" def __init__(self, fields: dict[str, str]) -> None: self._fields = dict(fields) @@ -20,18 +21,34 @@ def screenshot(self) -> bytes: def main() -> None: expected = {"Policy Holder": "Alice Novak", "Coverage Limit": "$250,000"} - out = Path("/tmp/openadapt-commit-firewall-demo") + out = Path("/tmp/openadapt-ui-commit-check-demo") + signing_key = Ed25519PrivateKey.generate() # 1. Clean commit -> verified + signed Ed25519 record/run/v1 receipt. - with commit_guard(DemoPage(expected), intent="Bind Policy", expected=expected, receipt_dir=out) as g: - pass # page.get_by_role("button", name="Bind Policy").click() - print(f"VERIFIED | receipt_id={g.result.receipt_id[:16]} | path={g.result.receipt_path}") + with ui_commit_check( + DemoPage(expected), + intent="Bind Policy", + expected=expected, + record_id="quote-2026-0001", + receipt_dir=out, + signing_key=signing_key, + ) as check: + pass + assert check.result is not None and check.result.receipt_id is not None + print( + f"VERIFIED | receipt_id={check.result.receipt_id[:16]} | path={check.result.receipt_path}" + ) # 2. Silent homoglyph + unbound control -> blocked & logged to Exception Inbox. corrupted = DemoPage({"Policy Holder": "\u0410lice Novak", "Coverage Limit": ""}) try: - with commit_guard(corrupted, intent="Bind Policy", expected=expected, inbox=out / "inbox.jsonl"): - pass # Cyrillic 'А' + empty unbound input + with ui_commit_check( + corrupted, + intent="Bind Policy", + expected=expected, + inbox=out / "inbox.jsonl", + ): + pass except CommitBlockedError as err: print(f"STOPPED | verdict={err.result.verdict} | reason={err.reason}") diff --git a/packages/verify/src/openadapt_verify/__init__.py b/packages/verify/src/openadapt_verify/__init__.py index 187faa45ed..f2f7b27779 100644 --- a/packages/verify/src/openadapt_verify/__init__.py +++ b/packages/verify/src/openadapt_verify/__init__.py @@ -25,16 +25,15 @@ from openadapt_flow.write_receipt import Verification as PortableReceiptVerification from openadapt_flow.write_receipt import verify as verify_receipt -from openadapt_verify.guard import ( +from openadapt_verify.commit_firewall import ( CommitBlockedError, - CommitGuard, CommitResult, + UiCommitCheck, async_verify_commit, - checked_write, - commit_guard, - verified, + ui_commit_check, verify_commit, ) +from openadapt_verify.guard import checked_write, verified __version__ = "0.2.0" @@ -42,7 +41,6 @@ "Actor", "AlreadyWritten", "CommitBlockedError", - "CommitGuard", "CommitResult", "Contract", "LocalSealVerification", @@ -50,15 +48,16 @@ "PortableReceiptVerification", "ReceiptError", "Scope", + "UiCommitCheck", "WriteBlocked", "WriteGuard", "WriteResult", "async_verify_commit", "begin_write", "checked_write", - "commit_guard", "issue_write_receipt", "recheck", + "ui_commit_check", "verify_commit", "verify_local_seal", "verified", diff --git a/packages/verify/src/openadapt_verify/commit_firewall.py b/packages/verify/src/openadapt_verify/commit_firewall.py index a20ea4ef45..b03a03e19e 100644 --- a/packages/verify/src/openadapt_verify/commit_firewall.py +++ b/packages/verify/src/openadapt_verify/commit_firewall.py @@ -1,17 +1,26 @@ -"""Universal 1-line Commit Firewall for GUI and browser agents. - -Wraps any irreversible UI commit step (Playwright, Browser-Use, Claude CUA, -OpenAI CUA, or raw screenshots) with: - -1. Fast deterministic DOM/text verification (duck-typed; zero hard dependency - on Playwright or any browser/vision library). -2. Optional visual veto check (duck-typed for ``PrePostSubmitVisualVeto`` or - any custom visual verifier callable) enforcing strict ``ABSTAIN -> HALT`` - semantics so clean DOM never silently overrides visual occlusion. -3. Cryptographically signed Ed25519 ``record/run/v1`` DSSE receipts via - ``openadapt_types.receipt`` on ``VERIFIED`` outcomes. -4. Structured ``CommitBlockedError`` / ``CommitResult(status="STOPPED")`` and - optional local Exception Inbox JSONL logging on ``VETO`` / ``ABSTAIN``. +"""UI commit check helper for duck-typed sync/async browser pages and screenshots. + +Tested against duck-typed sync/async page objects exposing field-level readers +(``read_field``, ``get_by_label``, ``input_value``) and raw screenshot bytes +paired with a visual verifier. This module provides same-screen UI checks (not +an independent system-of-record store verifier like ``openadapt_verify.guard``): + +1. **Exact field-level DOM checks (no body-text substring fallback):** Reads + each expected field directly via ``read_field`` / ``get_by_label`` / + ``input_value`` with exact Unicode comparison (no NFKC folding). Empty + ``expected`` maps and field-read errors always fail closed. +2. **Optional visual veto check:** Duck-typed for ``PrePostSubmitVisualVeto`` + or a custom visual verifier callable, enforcing strict ``ABSTAIN -> HALT`` + semantics and passing ``deterministic_passed=False`` whenever no DOM check + ran. +3. **Explicitly keyed Ed25519 receipts:** Mints a signed ``record/run/v1`` DSSE + receipt only when the caller supplies an explicit ``signing_key`` (never + silently generates an ephemeral per-call key) and binds both + ``expected_values_sha256`` and ``record_id`` into the signed statement. +4. **Pre-commit gate & exception recording:** :class:`UiCommitCheck` supports + an optional ``pre_expected`` check in ``__enter__`` / ``__aenter__`` that + halts BEFORE the commit body executes, and records an ``ABSTAIN`` inbox + entry if the wrapped body raises. """ from __future__ import annotations @@ -36,7 +45,7 @@ @dataclass(frozen=True) class CommitResult: - """Outcome of a commit firewall check.""" + """Outcome of a UI commit check.""" status: CommitStatus verdict: CommitVerdict @@ -73,7 +82,7 @@ def to_dict(self) -> dict[str, Any]: class CommitBlockedError(RuntimeError): - """Raised when the commit firewall halts an irreversible commit.""" + """Raised when a UI commit check halts before or after a commit step.""" def __init__(self, result: CommitResult) -> None: self.result = result @@ -115,53 +124,21 @@ def _coerce_screenshot_bytes(source: ScreenshotInput) -> Optional[bytes]: return None -def _extract_page_text_sync(page: Any) -> Optional[str]: - for method, args in ( - ("inner_text", ("body",)), - ("text_content", ("body",)), - ("content", ()), - ): - fn = getattr(page, method, None) - if callable(fn): - try: - val = fn(*args) - except Exception: - continue - if isinstance(val, str): - return val - return None - - -async def _extract_page_text_async(page: Any) -> Optional[str]: - for method, args in ( - ("inner_text", ("body",)), - ("text_content", ("body",)), - ("content", ()), - ): - fn = getattr(page, method, None) - if callable(fn): - try: - val = fn(*args) - if inspect.isawaitable(val): - val = await val - except Exception: - continue - if isinstance(val, str): - return val - return None - +def _read_field_sync(page: Any, key: str) -> tuple[bool, Optional[str], Optional[str]]: + """Read a field directly from a page object. -def _read_field_sync(page: Any, key: str) -> tuple[bool, Optional[str]]: - """Try field-level read first; returns (found_field, value).""" + Returns ``(found, value, error_detail)``. Never falls back to body-text + substring matching. + """ read_field = getattr(page, "read_field", None) if callable(read_field): try: val = read_field(key) - return True, None if val is None else str(val) + return True, None if val is None else str(val), None except KeyError: - return False, None - except Exception: - return False, None + return False, None, f"field {key!r} not found via read_field" + except Exception as exc: # noqa: BLE001 + return False, None, f"read_field({key!r}) raised {type(exc).__name__}" get_by_label = getattr(page, "get_by_label", None) if callable(get_by_label): @@ -172,34 +149,40 @@ def _read_field_sync(page: Any, key: str) -> tuple[bool, Optional[str]]: if callable(getter): val = getter() if isinstance(val, str): - return True, val - except Exception: - pass + return True, val, None + except KeyError: + return False, None, f"field {key!r} not found via get_by_label" + except Exception as exc: # noqa: BLE001 + return False, None, f"get_by_label({key!r}) raised {type(exc).__name__}" input_value = getattr(page, "input_value", None) if callable(input_value): try: val = input_value(key) if isinstance(val, str): - return True, val - except Exception: - pass + return True, val, None + except KeyError: + return False, None, f"field {key!r} not found via input_value" + except Exception as exc: # noqa: BLE001 + return False, None, f"input_value({key!r}) raised {type(exc).__name__}" - return False, None + return False, None, f"page exposes no field-level reader for {key!r}" -async def _read_field_async(page: Any, key: str) -> tuple[bool, Optional[str]]: +async def _read_field_async( + page: Any, key: str +) -> tuple[bool, Optional[str], Optional[str]]: read_field = getattr(page, "read_field", None) if callable(read_field): try: val = read_field(key) if inspect.isawaitable(val): val = await val - return True, None if val is None else str(val) + return True, None if val is None else str(val), None except KeyError: - return False, None - except Exception: - return False, None + return False, None, f"field {key!r} not found via read_field" + except Exception as exc: # noqa: BLE001 + return False, None, f"read_field({key!r}) raised {type(exc).__name__}" get_by_label = getattr(page, "get_by_label", None) if callable(get_by_label): @@ -212,9 +195,11 @@ async def _read_field_async(page: Any, key: str) -> tuple[bool, Optional[str]]: if inspect.isawaitable(val): val = await val if isinstance(val, str): - return True, val - except Exception: - pass + return True, val, None + except KeyError: + return False, None, f"field {key!r} not found via get_by_label" + except Exception as exc: # noqa: BLE001 + return False, None, f"get_by_label({key!r}) raised {type(exc).__name__}" input_value = getattr(page, "input_value", None) if callable(input_value): @@ -223,43 +208,30 @@ async def _read_field_async(page: Any, key: str) -> tuple[bool, Optional[str]]: if inspect.isawaitable(val): val = await val if isinstance(val, str): - return True, val - except Exception: - pass + return True, val, None + except KeyError: + return False, None, f"field {key!r} not found via input_value" + except Exception as exc: # noqa: BLE001 + return False, None, f"input_value({key!r}) raised {type(exc).__name__}" - return False, None + return False, None, f"page exposes no field-level reader for {key!r}" def _check_dom_sync( page: Any, expected: Mapping[str, str] ) -> tuple[bool, tuple[str, ...]]: - """Run exact Unicode DOM/text checks (no NFKC folding so homoglyphs fail).""" + """Run exact field-level Unicode checks (no NFKC folding, no body-text fallback).""" mismatches: list[str] = [] - page_text: Optional[str] = None - page_text_loaded = False - for field_key, expected_val in expected.items(): expected_str = str(expected_val) - found, actual = _read_field_sync(page, field_key) - if found: - if actual != expected_str: - mismatches.append( - f"field {field_key!r}: expected {expected_str!r}, observed {actual!r}" - ) + found, actual, err = _read_field_sync(page, field_key) + if not found: + mismatches.append(err or f"field {field_key!r}: unreadable") continue - - if not page_text_loaded: - page_text = _extract_page_text_sync(page) - page_text_loaded = True - if page_text is None: + if actual != expected_str: mismatches.append( - f"field {field_key!r}: page exposed no readable field or text" + f"field {field_key!r}: expected {expected_str!r}, observed {actual!r}" ) - elif expected_str not in page_text: - mismatches.append( - f"field {field_key!r}: expected value {expected_str!r} not found in page text" - ) - return len(mismatches) == 0, tuple(mismatches) @@ -267,31 +239,16 @@ async def _check_dom_async( page: Any, expected: Mapping[str, str] ) -> tuple[bool, tuple[str, ...]]: mismatches: list[str] = [] - page_text: Optional[str] = None - page_text_loaded = False - for field_key, expected_val in expected.items(): expected_str = str(expected_val) - found, actual = await _read_field_async(page, field_key) - if found: - if actual != expected_str: - mismatches.append( - f"field {field_key!r}: expected {expected_str!r}, observed {actual!r}" - ) + found, actual, err = await _read_field_async(page, field_key) + if not found: + mismatches.append(err or f"field {field_key!r}: unreadable") continue - - if not page_text_loaded: - page_text = await _extract_page_text_async(page) - page_text_loaded = True - if page_text is None: - mismatches.append( - f"field {field_key!r}: page exposed no readable field or text" - ) - elif expected_str not in page_text: + if actual != expected_str: mismatches.append( - f"field {field_key!r}: expected value {expected_str!r} not found in page text" + f"field {field_key!r}: expected {expected_str!r}, observed {actual!r}" ) - return len(mismatches) == 0, tuple(mismatches) @@ -304,7 +261,6 @@ def _normalize_visual_outcome(raw: Any) -> tuple[CommitVerdict, str]: if raw is None: return "ABSTAIN", "visual verifier returned no decision" - # Unwrap SubmitVetoResult-like objects (has .decision and .allowed) decision_obj = getattr(raw, "decision", None) if decision_obj is not None: raw = decision_obj @@ -344,7 +300,6 @@ def _run_visual_verifier_sync( deterministic_passed: bool, ) -> tuple[CommitVerdict, str]: try: - # Duck-type PrePostSubmitVisualVeto (post-submit or pre-submit) check_post = getattr(verifier, "check_post_submit", None) if callable(check_post) and after_png is not None: res = check_post( @@ -382,7 +337,7 @@ def _run_visual_verifier_sync( expected=dict(expected), ) return _normalize_visual_outcome(res) - except Exception as exc: + except Exception as exc: # noqa: BLE001 return "ABSTAIN", f"visual verifier error (fail-closed): {exc}" return "ABSTAIN", "unsupported visual verifier interface (fail-closed)" @@ -443,7 +398,7 @@ async def _run_visual_verifier_async( if inspect.isawaitable(res): res = await res return _normalize_visual_outcome(res) - except Exception as exc: + except Exception as exc: # noqa: BLE001 return "ABSTAIN", f"visual verifier error (fail-closed): {exc}" return "ABSTAIN", "unsupported visual verifier interface (fail-closed)" @@ -453,30 +408,45 @@ def _build_signed_receipt( *, intent: str, expected: Mapping[str, str], + record_id: str, + dom_checked: bool, used_visual_verifier: bool, after_png: Optional[bytes], receipt_dir: Optional[Union[str, Path]], - signing_key: Optional[Ed25519PrivateKey], + signing_key: Ed25519PrivateKey, ) -> tuple[str, dict[str, Any], Optional[Path], str, str]: - """Emit a signed Ed25519 ``record/run/v1`` DSSE receipt.""" - private_key = signing_key or Ed25519PrivateKey.generate() - pub_raw = private_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + """Emit a signed Ed25519 ``record/run/v1`` DSSE receipt bound to expected values & record_id.""" + pub_raw = signing_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) pub_b64 = base64.b64encode(pub_raw).decode("ascii") kid = receipt_lib.key_id(pub_raw) intent_sha = hashlib.sha256(intent.encode("utf-8")).hexdigest() + canonical_expected = {str(k): str(v) for k, v in sorted(expected.items())} + expected_values_sha = hashlib.sha256( + receipt_lib.canonical_json(canonical_expected).encode("utf-8") + ).hexdigest() + report_basis = { "intent_sha256": intent_sha, - "expected_keys": sorted(str(k) for k in expected.keys()), + "record_id": record_id, + "expected_keys": sorted(canonical_expected.keys()), + "expected_values_sha256": expected_values_sha, "outcome": "VERIFIED", + "dom_checked": dom_checked, "visual_checked": used_visual_verifier, + "strength": "same_screen", } report_sha = hashlib.sha256( receipt_lib.canonical_json(report_basis).encode("utf-8") ).hexdigest() subjects: list[dict[str, Any]] = [ - {"name": "report.json", "digest": {"sha256": report_sha}} + {"name": "report.json", "digest": {"sha256": report_sha}}, + { + "name": "payload", + "media_type": "application/json", + "digest": {"sha256": expected_values_sha}, + }, ] if after_png is not None: subjects.append( @@ -487,6 +457,8 @@ def _build_signed_receipt( ) started_hour = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:00:00Z") + # Same-screen checks do NOT claim independent store/identity confirmation. + post_confirmed = 1 if dom_checked else 0 statement: dict[str, Any] = { "_type": receipt_lib.STATEMENT_TYPE, "subject": subjects, @@ -504,19 +476,23 @@ def _build_signed_receipt( "step": 0, "target_kind": "gui", "operation": "irreversible_write", - "check": "confirmed", + "check": "confirmed" if dom_checked else "not_checked", "strength": "same_screen", - "not_checked": [], + "not_checked": ( + ["effect_not_declared"] + if dom_checked + else ["field_values", "effect_not_declared"] + ), } ], "checks": { - "identity": {"required": 1, "confirmed": 1}, - "postconditions": {"required": 1, "confirmed": 1}, + "identity": {"required": 0, "confirmed": 0}, + "postconditions": {"required": 1, "confirmed": post_confirmed}, "effects": {"required": 0, "confirmed": 0}, "authorization": {"required": 0, "confirmed": 0}, - "lines_confirmed": 1, + "lines_confirmed": post_confirmed, "lines_refuted": 0, - "lines_not_checked": 0, + "lines_not_checked": 0 if dom_checked else 1, }, "model_calls": 1 if used_visual_verifier else 0, "disclosure": { @@ -526,7 +502,7 @@ def _build_signed_receipt( }, } - envelope = receipt_lib.sign_statement(statement, [(kid, private_key.sign)]) + envelope = receipt_lib.sign_statement(statement, [(kid, signing_key.sign)]) rid = receipt_lib.payload_sha256(envelope) written_path: Optional[Path] = None @@ -574,6 +550,7 @@ def _finalize_commit( *, intent: str, expected: Mapping[str, str], + record_id: str, dom_checked: bool, dom_passed: bool, mismatches: tuple[str, ...], @@ -585,15 +562,19 @@ def _finalize_commit( signing_key: Optional[Ed25519PrivateKey], raise_on_block: bool, ) -> CommitResult: - # Strict ABSTAIN -> HALT & fail-closed combination rule: - # 1. Visual ABSTAIN ALWAYS halts (clean DOM never overrides occlusion). - # 2. Visual VETO ALWAYS halts. - # 3. DOM mismatch ALWAYS halts (passing visual never overrides bad DOM). - # 4. If neither DOM nor visual verifier ran for non-empty expected, ABSTAIN -> HALT. + # Strict fail-closed combination rule: + # 1. Empty `expected` ALWAYS abstains/halts (never VERIFIED on nothing). + # 2. Visual ABSTAIN ALWAYS halts (clean DOM never overrides occlusion). + # 3. Visual VETO ALWAYS halts. + # 4. DOM mismatch ALWAYS halts (passing visual never overrides bad DOM). + # 5. If neither DOM nor visual verifier ran, ABSTAIN -> HALT. final_verdict: CommitVerdict = "VERIFIED" reason = "" - if visual_verdict == "ABSTAIN": + if not expected: + final_verdict = "ABSTAIN" + reason = "expected must contain at least one field to verify" + elif visual_verdict == "ABSTAIN": final_verdict = "ABSTAIN" reason = visual_reason or "visual verifier abstained (ABSTAIN -> HALT)" elif visual_verdict == "VETO": @@ -602,7 +583,7 @@ def _finalize_commit( elif dom_checked and not dom_passed: final_verdict = "VETO" reason = "; ".join(mismatches) or "DOM verification failed" - elif not dom_checked and visual_verdict is None and expected: + elif not dom_checked and visual_verdict is None: final_verdict = "ABSTAIN" reason = "no DOM page or visual verifier available to verify expected fields" @@ -628,14 +609,23 @@ def _finalize_commit( raise CommitBlockedError(result) return result - rid, envelope, receipt_path, kid, pub_b64 = _build_signed_receipt( - intent=intent, - expected=expected, - used_visual_verifier=visual_verdict is not None, - after_png=after_png, - receipt_dir=receipt_dir, - signing_key=signing_key, - ) + rid: Optional[str] = None + envelope: Optional[dict[str, Any]] = None + receipt_path: Optional[Path] = None + kid: Optional[str] = None + pub_b64: Optional[str] = None + if signing_key is not None: + rid, envelope, receipt_path, kid, pub_b64 = _build_signed_receipt( + intent=intent, + expected=expected, + record_id=record_id, + dom_checked=dom_checked, + used_visual_verifier=visual_verdict is not None, + after_png=after_png, + receipt_dir=receipt_dir, + signing_key=signing_key, + ) + return CommitResult( status="VERIFIED", verdict="VERIFIED", @@ -654,6 +644,7 @@ def verify_commit( *, intent: str, expected: Mapping[str, str], + record_id: str = "", before_screenshot: ScreenshotInput = None, verifier: Any = None, inbox: Optional[Union[str, Path]] = None, @@ -661,19 +652,19 @@ def verify_commit( signing_key: Optional[Ed25519PrivateKey] = None, raise_on_block: bool = False, ) -> CommitResult: - """Verify an irreversible UI commit in 1 line (sync). + """Verify UI commit fields (sync) with strict fail-closed semantics. - Accepts a duck-typed Playwright-like ``page`` or screenshot bytes/path. - Enforces strict ``ABSTAIN -> HALT`` semantics and emits a signed Ed25519 - ``record/run/v1`` receipt on ``VERIFIED``. + Requires non-empty ``expected``. Uses exact field-level reads only (no + body-text substring fallback). Emits a signed Ed25519 ``record/run/v1`` + receipt only when an explicit ``signing_key`` is supplied. """ dom_checked = False - dom_passed = True + dom_passed = False mismatches: tuple[str, ...] = () after_png: Optional[bytes] = None before_png = _coerce_screenshot_bytes(before_screenshot) - if _is_page_like(page_or_screenshot): + if expected and _is_page_like(page_or_screenshot): dom_checked = True dom_passed, mismatches = _check_dom_sync(page_or_screenshot, expected) shot_fn = getattr(page_or_screenshot, "screenshot", None) @@ -688,19 +679,20 @@ def verify_commit( visual_verdict: Optional[CommitVerdict] = None visual_reason = "" - if verifier is not None: + if expected and verifier is not None: visual_verdict, visual_reason = _run_visual_verifier_sync( verifier, before_png=before_png, after_png=after_png, intent=intent, expected=expected, - deterministic_passed=dom_passed if dom_checked else True, + deterministic_passed=dom_passed if dom_checked else False, ) return _finalize_commit( intent=intent, expected=expected, + record_id=record_id, dom_checked=dom_checked, dom_passed=dom_passed, mismatches=mismatches, @@ -719,6 +711,7 @@ async def async_verify_commit( *, intent: str, expected: Mapping[str, str], + record_id: str = "", before_screenshot: ScreenshotInput = None, verifier: Any = None, inbox: Optional[Union[str, Path]] = None, @@ -726,14 +719,14 @@ async def async_verify_commit( signing_key: Optional[Ed25519PrivateKey] = None, raise_on_block: bool = False, ) -> CommitResult: - """Async counterpart to :func:`verify_commit` for async Playwright pages.""" + """Async counterpart to :func:`verify_commit` for async page objects.""" dom_checked = False - dom_passed = True + dom_passed = False mismatches: tuple[str, ...] = () after_png: Optional[bytes] = None before_png = _coerce_screenshot_bytes(before_screenshot) - if _is_page_like(page_or_screenshot): + if expected and _is_page_like(page_or_screenshot): dom_checked = True dom_passed, mismatches = await _check_dom_async(page_or_screenshot, expected) shot_fn = getattr(page_or_screenshot, "screenshot", None) @@ -750,19 +743,20 @@ async def async_verify_commit( visual_verdict: Optional[CommitVerdict] = None visual_reason = "" - if verifier is not None: + if expected and verifier is not None: visual_verdict, visual_reason = await _run_visual_verifier_async( verifier, before_png=before_png, after_png=after_png, intent=intent, expected=expected, - deterministic_passed=dom_passed if dom_checked else True, + deterministic_passed=dom_passed if dom_checked else False, ) return _finalize_commit( intent=intent, expected=expected, + record_id=record_id, dom_checked=dom_checked, dom_passed=dom_passed, mismatches=mismatches, @@ -776,8 +770,8 @@ async def async_verify_commit( ) -class CommitGuard: - """Dual sync/async context manager wrapping an irreversible UI commit.""" +class UiCommitCheck: + """Dual sync/async context manager for pre-commit gating and post-commit UI read-back.""" def __init__( self, @@ -785,6 +779,8 @@ def __init__( *, intent: str, expected: Mapping[str, str], + pre_expected: Optional[Mapping[str, str]] = None, + record_id: str = "", verifier: Any = None, inbox: Optional[Union[str, Path]] = None, receipt_dir: Optional[Union[str, Path]] = None, @@ -794,6 +790,8 @@ def __init__( self._page = page self._intent = intent self._expected = dict(expected) + self._pre_expected = dict(pre_expected) if pre_expected is not None else None + self._record_id = record_id self._verifier = verifier self._inbox = inbox self._receipt_dir = receipt_dir @@ -802,22 +800,51 @@ def __init__( self.before_screenshot: Optional[bytes] = None self.result: Optional[CommitResult] = None - def __enter__(self) -> CommitGuard: + def __enter__(self) -> UiCommitCheck: shot_fn = getattr(self._page, "screenshot", None) if callable(shot_fn): try: self.before_screenshot = _coerce_screenshot_bytes(shot_fn()) except Exception: self.before_screenshot = None + if self._pre_expected is not None: + pre_res = verify_commit( + self._page, + intent=f"{self._intent} (pre-commit)", + expected=self._pre_expected, + record_id=self._record_id, + inbox=self._inbox, + raise_on_block=self._raise_on_block, + ) + if not pre_res.verified: + self.result = pre_res return self def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: if exc_type is not None: + reason = f"commit body raised {exc_type.__name__}: {exc}" + inbox_item, inbox_path = _write_inbox_item( + self._inbox, + intent=self._intent, + verdict="ABSTAIN", + reason=reason, + mismatches=(), + expected=self._expected, + ) + self.result = CommitResult( + status="STOPPED", + verdict="ABSTAIN", + intent=self._intent, + reason=reason, + inbox_item=inbox_item, + inbox_path=inbox_path, + ) return False self.result = verify_commit( self._page, intent=self._intent, expected=self._expected, + record_id=self._record_id, before_screenshot=self.before_screenshot, verifier=self._verifier, inbox=self._inbox, @@ -827,7 +854,7 @@ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: ) return False - async def __aenter__(self) -> CommitGuard: + async def __aenter__(self) -> UiCommitCheck: shot_fn = getattr(self._page, "screenshot", None) if callable(shot_fn): try: @@ -837,15 +864,44 @@ async def __aenter__(self) -> CommitGuard: self.before_screenshot = _coerce_screenshot_bytes(raw) except Exception: self.before_screenshot = None + if self._pre_expected is not None: + pre_res = await async_verify_commit( + self._page, + intent=f"{self._intent} (pre-commit)", + expected=self._pre_expected, + record_id=self._record_id, + inbox=self._inbox, + raise_on_block=self._raise_on_block, + ) + if not pre_res.verified: + self.result = pre_res return self async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: if exc_type is not None: + reason = f"commit body raised {exc_type.__name__}: {exc}" + inbox_item, inbox_path = _write_inbox_item( + self._inbox, + intent=self._intent, + verdict="ABSTAIN", + reason=reason, + mismatches=(), + expected=self._expected, + ) + self.result = CommitResult( + status="STOPPED", + verdict="ABSTAIN", + intent=self._intent, + reason=reason, + inbox_item=inbox_item, + inbox_path=inbox_path, + ) return False self.result = await async_verify_commit( self._page, intent=self._intent, expected=self._expected, + record_id=self._record_id, before_screenshot=self.before_screenshot, verifier=self._verifier, inbox=self._inbox, @@ -856,22 +912,26 @@ async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: return False -def commit_guard( +def ui_commit_check( page: Any, *, intent: str, expected: Mapping[str, str], + pre_expected: Optional[Mapping[str, str]] = None, + record_id: str = "", verifier: Any = None, inbox: Optional[Union[str, Path]] = None, receipt_dir: Optional[Union[str, Path]] = None, signing_key: Optional[Ed25519PrivateKey] = None, raise_on_block: bool = True, -) -> CommitGuard: - """Return a sync/async context manager guarding an irreversible UI commit.""" - return CommitGuard( +) -> UiCommitCheck: + """Return a sync/async context manager for pre-commit gating and post-commit UI checks.""" + return UiCommitCheck( page, intent=intent, expected=expected, + pre_expected=pre_expected, + record_id=record_id, verifier=verifier, inbox=inbox, receipt_dir=receipt_dir, @@ -882,9 +942,9 @@ def commit_guard( __all__ = [ "CommitBlockedError", - "CommitGuard", "CommitResult", + "UiCommitCheck", "async_verify_commit", - "commit_guard", + "ui_commit_check", "verify_commit", ] diff --git a/packages/verify/src/openadapt_verify/guard.py b/packages/verify/src/openadapt_verify/guard.py index 2778e94ef5..ca6523e1a0 100644 --- a/packages/verify/src/openadapt_verify/guard.py +++ b/packages/verify/src/openadapt_verify/guard.py @@ -128,24 +128,3 @@ def checked_write( write_attempted=block.write_attempted, write_receipt=write_receipt, ) - - -from openadapt_verify.commit_firewall import ( # noqa: E402 - CommitBlockedError, - CommitGuard, - CommitResult, - async_verify_commit, - commit_guard, - verify_commit, -) - -__all__ = [ - "CommitBlockedError", - "CommitGuard", - "CommitResult", - "async_verify_commit", - "checked_write", - "commit_guard", - "verified", - "verify_commit", -] diff --git a/packages/verify/tests/test_commit_firewall.py b/packages/verify/tests/test_commit_firewall.py index 5193e6b502..4c2eed84e5 100644 --- a/packages/verify/tests/test_commit_firewall.py +++ b/packages/verify/tests/test_commit_firewall.py @@ -1,4 +1,4 @@ -"""Tests for the 1-line Universal Commit Firewall (openadapt_verify.commit_firewall).""" +"""Tests for openadapt_verify.commit_firewall (UI commit check helper).""" from __future__ import annotations @@ -10,13 +10,13 @@ from typing import Any import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from openadapt_types import receipt as receipt_lib - from openadapt_verify import ( CommitBlockedError, CommitResult, async_verify_commit, - commit_guard, + ui_commit_check, verify_commit, ) @@ -30,7 +30,7 @@ def input_value(self) -> str: class _SyncPlaywrightPage: - """Duck-typed sync Playwright Page (no playwright import).""" + """Duck-typed sync page exposing get_by_label() and screenshot().""" def __init__(self, fields: dict[str, str], *, body_text: str = "") -> None: self.fields = dict(fields) @@ -59,7 +59,7 @@ async def input_value(self) -> str: class _AsyncPlaywrightPage: - """Duck-typed async Playwright Page (no playwright import).""" + """Duck-typed async page exposing get_by_label() and screenshot().""" def __init__(self, fields: dict[str, str]) -> None: self.fields = dict(fields) @@ -75,6 +75,26 @@ async def screenshot(self) -> bytes: return f"\x89PNG-async-{self.screenshots_taken}".encode("utf-8") +class _BodyOnlyPage: + """Page exposing only body text (no field-level reader).""" + + def __init__(self, body_text: str) -> None: + self._body = body_text + + def inner_text(self, selector: str) -> str: + return self._body + + +class _RaisingReadFieldPage: + """Page whose read_field raises RuntimeError while body text contains 'Yes'.""" + + def read_field(self, key: str) -> str: + raise RuntimeError(f"DOM detached while reading {key}") + + def inner_text(self, selector: str) -> str: + return "Status: Yes" + + class _FakeVetoVerdict(str, Enum): PASS = "pass" VETO = "veto" @@ -121,46 +141,86 @@ def check_post_submit( ) -def test_verify_commit_clean_emits_verifiable_ed25519_receipt(tmp_path: Path) -> None: - page = _SyncPlaywrightPage( - {"Policy Holder": "Alice Novak", "Coverage Limit": "$250,000"} - ) +def test_verify_commit_clean_with_explicit_key_binds_expected_values( + tmp_path: Path, +) -> None: + signing_key = Ed25519PrivateKey.generate() + page_500 = _SyncPlaywrightPage({"Amount": "$500"}) + page_9999 = _SyncPlaywrightPage({"Amount": "$9999"}) receipt_dir = tmp_path / "receipts" - result = verify_commit( - page, + res_500 = verify_commit( + page_500, intent="Bind Policy", - expected={"Policy Holder": "Alice Novak", "Coverage Limit": "$250,000"}, + expected={"Amount": "$500"}, + record_id="rec-1", + receipt_dir=receipt_dir, + signing_key=signing_key, + ) + res_9999 = verify_commit( + page_9999, + intent="Bind Policy", + expected={"Amount": "$9999"}, + record_id="rec-2", receipt_dir=receipt_dir, + signing_key=signing_key, ) - assert isinstance(result, CommitResult) - assert result.status == "VERIFIED" - assert result.verdict == "VERIFIED" - assert result.verified is True - assert result.receipt_id is not None - assert result.receipt_path is not None and result.receipt_path.is_file() - assert result.receipt is not None - assert result.key_id is not None and result.public_key is not None - - # Cryptographically verify the emitted record/run/v1 DSSE envelope with openadapt-types! - on_disk = json.loads(result.receipt_path.read_text(encoding="utf-8")) + assert isinstance(res_500, CommitResult) + assert res_500.status == "VERIFIED" + assert res_500.receipt_id is not None and res_9999.receipt_id is not None + # Different expected values must produce different signed receipt subjects/IDs! + assert res_500.receipt_id != res_9999.receipt_id + assert res_500.receipt_path is not None and res_500.receipt_path.is_file() + assert res_500.key_id is not None and res_500.public_key is not None + + on_disk = json.loads(res_500.receipt_path.read_text(encoding="utf-8")) registry = [ receipt_lib.RoleKey( - key_id=result.key_id, - public_key=result.public_key, + key_id=res_500.key_id, + public_key=res_500.public_key, role="this_computer", ) ] check = receipt_lib.verify_receipt(on_disk, registry) assert check.ok is True, f"Receipt verification failed: {check}" - assert check.outcome == "VERIFIED" + + # Without an explicit signing_key, no ephemeral key or receipt is silently minted. + unsigned = verify_commit( + page_500, intent="Bind Policy", expected={"Amount": "$500"} + ) + assert unsigned.status == "VERIFIED" + assert unsigned.receipt is None + assert unsigned.receipt_id is None + + +def test_empty_expected_body_substring_and_read_errors_fail_closed( + tmp_path: Path, +) -> None: + # 1. Empty expected ALWAYS fails closed (ABSTAIN -> STOPPED). + empty_res = verify_commit(None, intent="x", expected={}) + assert empty_res.status == "STOPPED" + assert empty_res.verdict == "ABSTAIN" + assert empty_res.receipt is None + + # 2. Body text "Amount due: $5000" must NEVER match expected={"Amount": "$500"}! + body_only = _BodyOnlyPage("Amount due: $5000") + sub_res = verify_commit(body_only, intent="Pay", expected={"Amount": "$500"}) + assert sub_res.status == "STOPPED" + assert sub_res.verdict == "VETO" + assert sub_res.receipt is None + + # 3. read_field raising RuntimeError must NEVER fall back to body text "Yes"! + err_page = _RaisingReadFieldPage() + err_res = verify_commit(err_page, intent="Confirm", expected={"Approved": "Yes"}) + assert err_res.status == "STOPPED" + assert err_res.verdict == "VETO" + assert "RuntimeError" in err_res.reason def test_verify_commit_catches_silent_unbound_and_homoglyph_mismatch( tmp_path: Path, ) -> None: - # Cyrillic 'А' (U+0410) instead of Latin 'A' + empty unbound Coverage Limit control page = _SyncPlaywrightPage( {"Policy Holder": "\u0410lice Novak", "Coverage Limit": ""} ) @@ -185,13 +245,12 @@ def test_verify_commit_catches_silent_unbound_and_homoglyph_mismatch( assert len(lines) == 1 entry = json.loads(lines[0]) assert entry["schema"] == "openadapt.commit-inbox/v1" - assert entry["status"] == "STOPPED" assert entry["verdict"] == "VETO" - assert entry["expected_keys"] == ["Coverage Limit", "Policy Holder"] -def test_abstain_halts_even_when_dom_is_clean(tmp_path: Path) -> None: - """Strict ABSTAIN -> HALT: clean DOM must NEVER override visual occlusion.""" +def test_abstain_halts_and_raw_screenshot_passes_deterministic_passed_false( + tmp_path: Path, +) -> None: clean_page = _SyncPlaywrightPage({"Status": "Approved"}) occluded_veto = _DuckPrePostVisualVeto( _FakeVetoVerdict.ABSTAIN, reason="modal dialog occludes submit button" @@ -210,95 +269,76 @@ def test_abstain_halts_even_when_dom_is_clean(tmp_path: Path) -> None: assert occluded_veto.calls[0]["deterministic_passed"] is True assert result.status == "STOPPED" assert result.verdict == "ABSTAIN" - assert result.verified is False - assert result.receipt is None - assert "occludes" in result.reason - assert inbox_path.is_file() - -def test_visual_pass_never_overrides_dom_mismatch() -> None: - bad_page = _SyncPlaywrightPage({"Amount": "$0.00"}) - passing_veto = _DuckPrePostVisualVeto(_FakeVetoVerdict.PASS) - - result = verify_commit( - bad_page, - intent="Submit Payment", - expected={"Amount": "$500.00"}, - verifier=passing_veto, + # When no DOM check ran (raw PNG), visual verifier MUST receive deterministic_passed=False! + raw_veto = _DuckPrePostVisualVeto(_FakeVetoVerdict.PASS) + raw_res = verify_commit( + b"\x89PNG-raw", + intent="Approve Invoice", + expected={"Status": "Approved"}, + verifier=raw_veto, ) - - assert result.status == "STOPPED" - assert result.verdict == "VETO" - assert result.verified is False + assert len(raw_veto.calls) == 1 + assert raw_veto.calls[0]["deterministic_passed"] is False + assert raw_res.status == "VERIFIED" + # No signing_key supplied -> no receipt minted. + assert raw_res.receipt is None -def test_sync_and_async_commit_guard_context_managers(tmp_path: Path) -> None: - # Sync context manager: captures before & after screenshots and verifies - sync_page = _SyncPlaywrightPage({"Status": "Draft"}) - with commit_guard( - sync_page, +def test_ui_commit_check_pre_commit_gate_body_exception_and_async( + tmp_path: Path, +) -> None: + signing_key = Ed25519PrivateKey.generate() + + # 1. Pre-commit gate blocks BEFORE body executes when pre_expected fails. + pre_page = _SyncPlaywrightPage({"Amount": "$9999"}) + body_ran = False + with pytest.raises(CommitBlockedError): + with ui_commit_check( + pre_page, + intent="Submit Payment", + pre_expected={"Amount": "$500"}, + expected={"Status": "Paid"}, + ): + body_ran = True + assert body_ran is False + + # 2. Exception inside body records ABSTAIN inbox entry before re-raising. + exc_inbox = tmp_path / "exc_inbox.jsonl" + exc_page = _SyncPlaywrightPage({"Status": "Draft"}) + check = ui_commit_check( + exc_page, intent="Submit Form", expected={"Status": "Submitted"}, - receipt_dir=tmp_path / "sync_receipts", - ) as guard: - sync_page.fields["Status"] = "Submitted" - - assert guard.before_screenshot is not None - assert guard.result is not None and guard.result.status == "VERIFIED" - assert sync_page.screenshots_taken == 2 - - # Sync context manager raises CommitBlockedError on mismatch - broken_page = _SyncPlaywrightPage({"Status": "Draft"}) - with pytest.raises(CommitBlockedError) as exc_info: - with commit_guard( - broken_page, - intent="Submit Form", - expected={"Status": "Submitted"}, - inbox=tmp_path / "blocked.jsonl", - ): - pass # click failed silently - assert exc_info.value.result.status == "STOPPED" - assert exc_info.value.inbox_item is not None - - # Async context manager with duck-typed async Playwright page + inbox=exc_inbox, + ) + with pytest.raises(RuntimeError, match="click crashed"): + with check: + raise RuntimeError("click crashed") + assert check.result is not None + assert check.result.verdict == "ABSTAIN" + assert exc_inbox.is_file() + + # 3. Async context manager succeeds with explicit signing key. async def _run_async() -> CommitResult: async_page = _AsyncPlaywrightPage({"Status": "Draft"}) - async with commit_guard( + async with ui_commit_check( async_page, intent="Approve Async", expected={"Status": "Approved"}, receipt_dir=tmp_path / "async_receipts", - ) as aguard: + signing_key=signing_key, + ) as acheck: async_page.fields["Status"] = "Approved" - assert aguard.before_screenshot is not None - assert aguard.result is not None - return aguard.result + assert acheck.before_screenshot is not None + assert acheck.result is not None + return acheck.result async_res = asyncio.run(_run_async()) assert async_res.status == "VERIFIED" assert async_res.receipt_path is not None and async_res.receipt_path.is_file() - -def test_raw_screenshot_requires_verifier_fail_closed() -> None: - # Raw screenshot without a visual verifier must ABSTAIN -> HALT when expected is set - res_no_verifier = verify_commit( - b"\x89PNG-raw", - intent="Submit", - expected={"Status": "Saved"}, - ) - assert res_no_verifier.status == "STOPPED" - assert res_no_verifier.verdict == "ABSTAIN" - - # Raw screenshot with a passing visual verifier succeeds - res_with_verifier = verify_commit( - b"\x89PNG-raw", - intent="Submit", - expected={"Status": "Saved"}, - verifier=lambda **_: {"verdict": "PASS", "reason": "confirmed visually"}, - ) - assert res_with_verifier.status == "VERIFIED" - - # Async verify_commit with verifier raising exception -> ABSTAIN -> HALT + # 4. Async verify_commit with raising verifier -> ABSTAIN. async def _raising_verifier(**_: Any) -> dict[str, Any]: raise RuntimeError("VLM timeout") From 9640095e6a84b08fe5931f6ce20852790fd652b5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 10:11:36 -0500 Subject: [PATCH 5/6] verify: fail-closed status tiers (VERIFIED/SAME_SCREEN/VISUAL_ONLY/UNCONFIRMED_WRITE) and exact CI count --- .github/workflows/packages.yml | 2 +- .../src/openadapt_verify/commit_firewall.py | 131 ++++++++++++++---- packages/verify/tests/test_commit_firewall.py | 103 +++++++++++--- 3 files changed, 188 insertions(+), 48 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 713ea6824b..119fd4a58d 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -435,7 +435,7 @@ jobs: python - <<'PY' import xml.etree.ElementTree as ET cases = ET.parse("tests.xml").getroot().findall(".//testcase") - assert len(cases) >= 105, "all independent-store controls must run" + assert len(cases) == 110, f"expected 110 independent-store + commit-firewall controls, got {len(cases)}" # The PostgreSQL and MySQL quickstart controls need the database # services of verify-clean-install, which runs them; nothing else skips. skipped = {c.get("name") for c in cases if c.find("skipped") is not None} diff --git a/packages/verify/src/openadapt_verify/commit_firewall.py b/packages/verify/src/openadapt_verify/commit_firewall.py index b03a03e19e..b41b84c644 100644 --- a/packages/verify/src/openadapt_verify/commit_firewall.py +++ b/packages/verify/src/openadapt_verify/commit_firewall.py @@ -38,8 +38,10 @@ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from openadapt_types import receipt as receipt_lib -CommitStatus = Literal["VERIFIED", "STOPPED"] -CommitVerdict = Literal["VERIFIED", "VETO", "ABSTAIN"] +CommitStatus = Literal[ + "VERIFIED", "SAME_SCREEN", "VISUAL_ONLY", "STOPPED", "UNCONFIRMED_WRITE" +] +CommitVerdict = Literal["VERIFIED", "SAME_SCREEN", "VISUAL_ONLY", "VETO", "ABSTAIN"] ScreenshotInput = Union[bytes, bytearray, str, Path, None] @@ -434,7 +436,7 @@ def _build_signed_receipt( "outcome": "VERIFIED", "dom_checked": dom_checked, "visual_checked": used_visual_verifier, - "strength": "same_screen", + "strength": "independent_readback", } report_sha = hashlib.sha256( receipt_lib.canonical_json(report_basis).encode("utf-8") @@ -476,13 +478,9 @@ def _build_signed_receipt( "step": 0, "target_kind": "gui", "operation": "irreversible_write", - "check": "confirmed" if dom_checked else "not_checked", - "strength": "same_screen", - "not_checked": ( - ["effect_not_declared"] - if dom_checked - else ["field_values", "effect_not_declared"] - ), + "check": "confirmed", + "strength": "read_back", + "not_checked": ["effect_not_declared"], } ], "checks": { @@ -522,6 +520,7 @@ def _write_inbox_item( inbox: Optional[Union[str, Path]], *, intent: str, + status: CommitStatus, verdict: CommitVerdict, reason: str, mismatches: tuple[str, ...], @@ -531,7 +530,7 @@ def _write_inbox_item( "schema": "openadapt.commit-inbox/v1", "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "intent": intent, - "status": "STOPPED", + "status": status, "verdict": verdict, "reason": reason, "mismatches": list(mismatches), @@ -553,6 +552,7 @@ def _finalize_commit( record_id: str, dom_checked: bool, dom_passed: bool, + dom_independent: bool, mismatches: tuple[str, ...], visual_verdict: Optional[CommitVerdict], visual_reason: str, @@ -561,13 +561,20 @@ def _finalize_commit( receipt_dir: Optional[Union[str, Path]], signing_key: Optional[Ed25519PrivateKey], raise_on_block: bool, + stage: Literal["pre_commit", "post_commit"] = "post_commit", ) -> CommitResult: # Strict fail-closed combination rule: # 1. Empty `expected` ALWAYS abstains/halts (never VERIFIED on nothing). # 2. Visual ABSTAIN ALWAYS halts (clean DOM never overrides occlusion). # 3. Visual VETO ALWAYS halts. # 4. DOM mismatch ALWAYS halts (passing visual never overrides bad DOM). - # 5. If neither DOM nor visual verifier ran, ABSTAIN -> HALT. + # 5. Visual-only (no DOM check) NEVER returns VERIFIED -> VISUAL_ONLY (no signed VERIFIED receipt). + # 6. Same-screen DOM read (no independent_page) NEVER returns VERIFIED -> SAME_SCREEN (no signed VERIFIED receipt). + # 7. Only an independent read-back (dom_independent=True) returns VERIFIED and may mint a signed receipt. + # 8. Post-commit failures return UNCONFIRMED_WRITE (not STOPPED) so callers know the write may have landed. + fail_status: CommitStatus = ( + "STOPPED" if stage == "pre_commit" else "UNCONFIRMED_WRITE" + ) final_verdict: CommitVerdict = "VERIFIED" reason = "" @@ -586,18 +593,36 @@ def _finalize_commit( elif not dom_checked and visual_verdict is None: final_verdict = "ABSTAIN" reason = "no DOM page or visual verifier available to verify expected fields" + elif not dom_checked: + # Visual-only path: never VERIFIED and never signs an outcome=VERIFIED receipt. + return CommitResult( + status="VISUAL_ONLY", + verdict="VISUAL_ONLY", + intent=intent, + reason=visual_reason + or "visual-only check passed; DOM read-back did not run (not VERIFIED)", + ) + elif not dom_independent: + # Same-screen DOM check: never VERIFIED and never signs an outcome=VERIFIED receipt. + return CommitResult( + status="SAME_SCREEN", + verdict="SAME_SCREEN", + intent=intent, + reason="same-screen DOM fields matched; independent read-back did not run (not VERIFIED)", + ) if final_verdict != "VERIFIED": inbox_item, inbox_path = _write_inbox_item( inbox, intent=intent, + status=fail_status, verdict=final_verdict, reason=reason, mismatches=mismatches, expected=expected, ) result = CommitResult( - status="STOPPED", + status=fail_status, verdict=final_verdict, intent=intent, reason=reason, @@ -615,6 +640,8 @@ def _finalize_commit( kid: Optional[str] = None pub_b64: Optional[str] = None if signing_key is not None: + if not str(record_id).strip(): + raise ValueError("record_id is required when signing_key is provided") rid, envelope, receipt_path, kid, pub_b64 = _build_signed_receipt( intent=intent, expected=expected, @@ -645,29 +672,41 @@ def verify_commit( intent: str, expected: Mapping[str, str], record_id: str = "", + independent_page: Any = None, before_screenshot: ScreenshotInput = None, verifier: Any = None, inbox: Optional[Union[str, Path]] = None, receipt_dir: Optional[Union[str, Path]] = None, signing_key: Optional[Ed25519PrivateKey] = None, raise_on_block: bool = False, + stage: Literal["pre_commit", "post_commit"] = "post_commit", ) -> CommitResult: """Verify UI commit fields (sync) with strict fail-closed semantics. - Requires non-empty ``expected``. Uses exact field-level reads only (no - body-text substring fallback). Emits a signed Ed25519 ``record/run/v1`` - receipt only when an explicit ``signing_key`` is supplied. + - Requires non-empty ``expected``. + - Same-screen DOM reads (without ``independent_page``) return at most + ``SAME_SCREEN`` (``verified=False``) and never sign ``outcome: VERIFIED``. + - Visual-only checks (no DOM page) return at most ``VISUAL_ONLY`` + (``verified=False``) and never sign ``outcome: VERIFIED``. + - Supplying an explicit ``independent_page`` (reloaded page, separate + session, or store reader) enables ``VERIFIED`` and signed Ed25519 + receipts when ``signing_key`` and non-empty ``record_id`` are provided. """ dom_checked = False dom_passed = False + dom_independent = False mismatches: tuple[str, ...] = () after_png: Optional[bytes] = None before_png = _coerce_screenshot_bytes(before_screenshot) - if expected and _is_page_like(page_or_screenshot): + read_target = ( + independent_page if independent_page is not None else page_or_screenshot + ) + if expected and _is_page_like(read_target): dom_checked = True - dom_passed, mismatches = _check_dom_sync(page_or_screenshot, expected) - shot_fn = getattr(page_or_screenshot, "screenshot", None) + dom_independent = independent_page is not None + dom_passed, mismatches = _check_dom_sync(read_target, expected) + shot_fn = getattr(read_target, "screenshot", None) if callable(shot_fn): try: raw_shot = shot_fn() @@ -695,6 +734,7 @@ def verify_commit( record_id=record_id, dom_checked=dom_checked, dom_passed=dom_passed, + dom_independent=dom_independent, mismatches=mismatches, visual_verdict=visual_verdict, visual_reason=visual_reason, @@ -703,6 +743,7 @@ def verify_commit( receipt_dir=receipt_dir, signing_key=signing_key, raise_on_block=raise_on_block, + stage=stage, ) @@ -712,24 +753,31 @@ async def async_verify_commit( intent: str, expected: Mapping[str, str], record_id: str = "", + independent_page: Any = None, before_screenshot: ScreenshotInput = None, verifier: Any = None, inbox: Optional[Union[str, Path]] = None, receipt_dir: Optional[Union[str, Path]] = None, signing_key: Optional[Ed25519PrivateKey] = None, raise_on_block: bool = False, + stage: Literal["pre_commit", "post_commit"] = "post_commit", ) -> CommitResult: """Async counterpart to :func:`verify_commit` for async page objects.""" dom_checked = False dom_passed = False + dom_independent = False mismatches: tuple[str, ...] = () after_png: Optional[bytes] = None before_png = _coerce_screenshot_bytes(before_screenshot) - if expected and _is_page_like(page_or_screenshot): + read_target = ( + independent_page if independent_page is not None else page_or_screenshot + ) + if expected and _is_page_like(read_target): dom_checked = True - dom_passed, mismatches = await _check_dom_async(page_or_screenshot, expected) - shot_fn = getattr(page_or_screenshot, "screenshot", None) + dom_independent = independent_page is not None + dom_passed, mismatches = await _check_dom_async(read_target, expected) + shot_fn = getattr(read_target, "screenshot", None) if callable(shot_fn): try: raw_shot = shot_fn() @@ -759,6 +807,7 @@ async def async_verify_commit( record_id=record_id, dom_checked=dom_checked, dom_passed=dom_passed, + dom_independent=dom_independent, mismatches=mismatches, visual_verdict=visual_verdict, visual_reason=visual_reason, @@ -767,11 +816,18 @@ async def async_verify_commit( receipt_dir=receipt_dir, signing_key=signing_key, raise_on_block=raise_on_block, + stage=stage, ) class UiCommitCheck: - """Dual sync/async context manager for pre-commit gating and post-commit UI read-back.""" + """Dual sync/async context manager for optional pre-commit gating and post-commit UI read-back. + + ``pre_expected`` defaults to ``None`` (nothing gates the write before the + body runs unless ``pre_expected`` is supplied). When ``pre_expected`` fails + with ``raise_on_block=False``, ``__exit__`` / ``__aexit__`` preserves the + ``STOPPED`` pre-check result and skips the post-check. + """ def __init__( self, @@ -781,6 +837,7 @@ def __init__( expected: Mapping[str, str], pre_expected: Optional[Mapping[str, str]] = None, record_id: str = "", + independent_page: Any = None, verifier: Any = None, inbox: Optional[Union[str, Path]] = None, receipt_dir: Optional[Union[str, Path]] = None, @@ -792,11 +849,13 @@ def __init__( self._expected = dict(expected) self._pre_expected = dict(pre_expected) if pre_expected is not None else None self._record_id = record_id + self._independent_page = independent_page self._verifier = verifier self._inbox = inbox self._receipt_dir = receipt_dir self._signing_key = signing_key self._raise_on_block = raise_on_block + self._pre_blocked = False self.before_screenshot: Optional[bytes] = None self.result: Optional[CommitResult] = None @@ -815,24 +874,29 @@ def __enter__(self) -> UiCommitCheck: record_id=self._record_id, inbox=self._inbox, raise_on_block=self._raise_on_block, + stage="pre_commit", ) - if not pre_res.verified: + if pre_res.status not in ("VERIFIED", "SAME_SCREEN"): + self._pre_blocked = True self.result = pre_res return self def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: + if self._pre_blocked: + return False if exc_type is not None: reason = f"commit body raised {exc_type.__name__}: {exc}" inbox_item, inbox_path = _write_inbox_item( self._inbox, intent=self._intent, + status="UNCONFIRMED_WRITE", verdict="ABSTAIN", reason=reason, mismatches=(), expected=self._expected, ) self.result = CommitResult( - status="STOPPED", + status="UNCONFIRMED_WRITE", verdict="ABSTAIN", intent=self._intent, reason=reason, @@ -845,12 +909,14 @@ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: intent=self._intent, expected=self._expected, record_id=self._record_id, + independent_page=self._independent_page, before_screenshot=self.before_screenshot, verifier=self._verifier, inbox=self._inbox, receipt_dir=self._receipt_dir, signing_key=self._signing_key, raise_on_block=self._raise_on_block, + stage="post_commit", ) return False @@ -872,24 +938,29 @@ async def __aenter__(self) -> UiCommitCheck: record_id=self._record_id, inbox=self._inbox, raise_on_block=self._raise_on_block, + stage="pre_commit", ) - if not pre_res.verified: + if pre_res.status not in ("VERIFIED", "SAME_SCREEN"): + self._pre_blocked = True self.result = pre_res return self async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: + if self._pre_blocked: + return False if exc_type is not None: reason = f"commit body raised {exc_type.__name__}: {exc}" inbox_item, inbox_path = _write_inbox_item( self._inbox, intent=self._intent, + status="UNCONFIRMED_WRITE", verdict="ABSTAIN", reason=reason, mismatches=(), expected=self._expected, ) self.result = CommitResult( - status="STOPPED", + status="UNCONFIRMED_WRITE", verdict="ABSTAIN", intent=self._intent, reason=reason, @@ -902,12 +973,14 @@ async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> Literal[False]: intent=self._intent, expected=self._expected, record_id=self._record_id, + independent_page=self._independent_page, before_screenshot=self.before_screenshot, verifier=self._verifier, inbox=self._inbox, receipt_dir=self._receipt_dir, signing_key=self._signing_key, raise_on_block=self._raise_on_block, + stage="post_commit", ) return False @@ -919,19 +992,21 @@ def ui_commit_check( expected: Mapping[str, str], pre_expected: Optional[Mapping[str, str]] = None, record_id: str = "", + independent_page: Any = None, verifier: Any = None, inbox: Optional[Union[str, Path]] = None, receipt_dir: Optional[Union[str, Path]] = None, signing_key: Optional[Ed25519PrivateKey] = None, raise_on_block: bool = True, ) -> UiCommitCheck: - """Return a sync/async context manager for pre-commit gating and post-commit UI checks.""" + """Return a sync/async context manager for optional pre-commit gating and post-commit UI checks.""" return UiCommitCheck( page, intent=intent, expected=expected, pre_expected=pre_expected, record_id=record_id, + independent_page=independent_page, verifier=verifier, inbox=inbox, receipt_dir=receipt_dir, diff --git a/packages/verify/tests/test_commit_firewall.py b/packages/verify/tests/test_commit_firewall.py index 4c2eed84e5..4012c86721 100644 --- a/packages/verify/tests/test_commit_firewall.py +++ b/packages/verify/tests/test_commit_firewall.py @@ -12,6 +12,7 @@ import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from openadapt_types import receipt as receipt_lib + from openadapt_verify import ( CommitBlockedError, CommitResult, @@ -141,14 +142,17 @@ def check_post_submit( ) -def test_verify_commit_clean_with_explicit_key_binds_expected_values( +def test_verify_commit_independent_readback_mints_receipt_and_same_screen_does_not( tmp_path: Path, ) -> None: signing_key = Ed25519PrivateKey.generate() page_500 = _SyncPlaywrightPage({"Amount": "$500"}) + indep_500 = _SyncPlaywrightPage({"Amount": "$500"}) page_9999 = _SyncPlaywrightPage({"Amount": "$9999"}) + indep_9999 = _SyncPlaywrightPage({"Amount": "$9999"}) receipt_dir = tmp_path / "receipts" + # Independent read-back -> VERIFIED + signed receipt with distinct subject IDs. res_500 = verify_commit( page_500, intent="Bind Policy", @@ -156,6 +160,7 @@ def test_verify_commit_clean_with_explicit_key_binds_expected_values( record_id="rec-1", receipt_dir=receipt_dir, signing_key=signing_key, + independent_page=indep_500, ) res_9999 = verify_commit( page_9999, @@ -164,10 +169,12 @@ def test_verify_commit_clean_with_explicit_key_binds_expected_values( record_id="rec-2", receipt_dir=receipt_dir, signing_key=signing_key, + independent_page=indep_9999, ) assert isinstance(res_500, CommitResult) assert res_500.status == "VERIFIED" + assert res_500.verified is True assert res_500.receipt_id is not None and res_9999.receipt_id is not None # Different expected values must produce different signed receipt subjects/IDs! assert res_500.receipt_id != res_9999.receipt_id @@ -185,35 +192,65 @@ def test_verify_commit_clean_with_explicit_key_binds_expected_values( check = receipt_lib.verify_receipt(on_disk, registry) assert check.ok is True, f"Receipt verification failed: {check}" - # Without an explicit signing_key, no ephemeral key or receipt is silently minted. + # Without an explicit signing_key, independent read-back is VERIFIED with no receipt. unsigned = verify_commit( - page_500, intent="Bind Policy", expected={"Amount": "$500"} + page_500, + intent="Bind Policy", + expected={"Amount": "$500"}, + independent_page=indep_500, ) assert unsigned.status == "VERIFIED" + assert unsigned.verified is True assert unsigned.receipt is None assert unsigned.receipt_id is None + # Same-screen DOM check (no independent_page) returns SAME_SCREEN and NEVER mints a receipt. + same_screen = verify_commit( + page_500, + intent="Bind Policy", + expected={"Amount": "$500"}, + record_id="rec-same", + receipt_dir=receipt_dir, + signing_key=signing_key, + ) + assert same_screen.status == "SAME_SCREEN" + assert same_screen.verdict == "SAME_SCREEN" + assert same_screen.verified is False + assert same_screen.receipt is None + assert same_screen.receipt_id is None + + # signing_key without non-empty record_id must raise ValueError (fail closed). + with pytest.raises(ValueError, match="record_id"): + verify_commit( + page_500, + intent="Bind Policy", + expected={"Amount": "$500"}, + record_id="", + signing_key=signing_key, + independent_page=indep_500, + ) + def test_empty_expected_body_substring_and_read_errors_fail_closed( tmp_path: Path, ) -> None: - # 1. Empty expected ALWAYS fails closed (ABSTAIN -> STOPPED). + # 1. Empty expected ALWAYS fails closed (ABSTAIN -> UNCONFIRMED_WRITE post-commit). empty_res = verify_commit(None, intent="x", expected={}) - assert empty_res.status == "STOPPED" + assert empty_res.status == "UNCONFIRMED_WRITE" assert empty_res.verdict == "ABSTAIN" assert empty_res.receipt is None # 2. Body text "Amount due: $5000" must NEVER match expected={"Amount": "$500"}! body_only = _BodyOnlyPage("Amount due: $5000") sub_res = verify_commit(body_only, intent="Pay", expected={"Amount": "$500"}) - assert sub_res.status == "STOPPED" + assert sub_res.status == "UNCONFIRMED_WRITE" assert sub_res.verdict == "VETO" assert sub_res.receipt is None # 3. read_field raising RuntimeError must NEVER fall back to body text "Yes"! err_page = _RaisingReadFieldPage() err_res = verify_commit(err_page, intent="Confirm", expected={"Approved": "Yes"}) - assert err_res.status == "STOPPED" + assert err_res.status == "UNCONFIRMED_WRITE" assert err_res.verdict == "VETO" assert "RuntimeError" in err_res.reason @@ -233,7 +270,7 @@ def test_verify_commit_catches_silent_unbound_and_homoglyph_mismatch( inbox=inbox_path, ) - assert result.status == "STOPPED" + assert result.status == "UNCONFIRMED_WRITE" assert result.verdict == "VETO" assert result.verified is False assert result.receipt is None @@ -245,12 +282,14 @@ def test_verify_commit_catches_silent_unbound_and_homoglyph_mismatch( assert len(lines) == 1 entry = json.loads(lines[0]) assert entry["schema"] == "openadapt.commit-inbox/v1" + assert entry["status"] == "UNCONFIRMED_WRITE" assert entry["verdict"] == "VETO" -def test_abstain_halts_and_raw_screenshot_passes_deterministic_passed_false( +def test_abstain_halts_and_raw_screenshot_returns_visual_only_never_verified( tmp_path: Path, ) -> None: + signing_key = Ed25519PrivateKey.generate() clean_page = _SyncPlaywrightPage({"Status": "Approved"}) occluded_veto = _DuckPrePostVisualVeto( _FakeVetoVerdict.ABSTAIN, reason="modal dialog occludes submit button" @@ -267,22 +306,28 @@ def test_abstain_halts_and_raw_screenshot_passes_deterministic_passed_false( assert len(occluded_veto.calls) == 1 assert occluded_veto.calls[0]["deterministic_passed"] is True - assert result.status == "STOPPED" + assert result.status == "UNCONFIRMED_WRITE" assert result.verdict == "ABSTAIN" - # When no DOM check ran (raw PNG), visual verifier MUST receive deterministic_passed=False! + # When no DOM check ran (raw PNG), visual verifier MUST receive deterministic_passed=False, + # return VISUAL_ONLY (never VERIFIED), and NEVER mint a signed receipt! raw_veto = _DuckPrePostVisualVeto(_FakeVetoVerdict.PASS) raw_res = verify_commit( b"\x89PNG-raw", intent="Approve Invoice", expected={"Status": "Approved"}, verifier=raw_veto, + record_id="rec-visual", + receipt_dir=tmp_path / "visual_receipts", + signing_key=signing_key, ) assert len(raw_veto.calls) == 1 assert raw_veto.calls[0]["deterministic_passed"] is False - assert raw_res.status == "VERIFIED" - # No signing_key supplied -> no receipt minted. + assert raw_res.status == "VISUAL_ONLY" + assert raw_res.verdict == "VISUAL_ONLY" + assert raw_res.verified is False assert raw_res.receipt is None + assert raw_res.receipt_id is None def test_ui_commit_check_pre_commit_gate_body_exception_and_async( @@ -290,10 +335,10 @@ def test_ui_commit_check_pre_commit_gate_body_exception_and_async( ) -> None: signing_key = Ed25519PrivateKey.generate() - # 1. Pre-commit gate blocks BEFORE body executes when pre_expected fails. + # 1a. Pre-commit gate blocks BEFORE body executes when pre_expected fails (status=STOPPED). pre_page = _SyncPlaywrightPage({"Amount": "$9999"}) body_ran = False - with pytest.raises(CommitBlockedError): + with pytest.raises(CommitBlockedError) as exc_info: with ui_commit_check( pre_page, intent="Submit Payment", @@ -302,8 +347,23 @@ def test_ui_commit_check_pre_commit_gate_body_exception_and_async( ): body_ran = True assert body_ran is False + assert exc_info.value.result.status == "STOPPED" + + # 1b. Pre-commit gate with raise_on_block=False preserves STOPPED result and skips post-check. + pre_check = ui_commit_check( + pre_page, + intent="Submit Payment", + pre_expected={"Amount": "$500"}, + expected={"Status": "Paid"}, + raise_on_block=False, + ) + with pre_check: + pass + assert pre_check.result is not None + assert pre_check.result.status == "STOPPED" + assert pre_check.result.verdict == "VETO" - # 2. Exception inside body records ABSTAIN inbox entry before re-raising. + # 2. Exception inside body records UNCONFIRMED_WRITE / ABSTAIN inbox entry before re-raising. exc_inbox = tmp_path / "exc_inbox.jsonl" exc_page = _SyncPlaywrightPage({"Status": "Draft"}) check = ui_commit_check( @@ -316,20 +376,25 @@ def test_ui_commit_check_pre_commit_gate_body_exception_and_async( with check: raise RuntimeError("click crashed") assert check.result is not None + assert check.result.status == "UNCONFIRMED_WRITE" assert check.result.verdict == "ABSTAIN" assert exc_inbox.is_file() - # 3. Async context manager succeeds with explicit signing key. + # 3. Async context manager with independent_page + signing_key -> VERIFIED + signed receipt. async def _run_async() -> CommitResult: async_page = _AsyncPlaywrightPage({"Status": "Draft"}) + indep_async = _AsyncPlaywrightPage({"Status": "Draft"}) async with ui_commit_check( async_page, intent="Approve Async", expected={"Status": "Approved"}, + record_id="rec-async-1", receipt_dir=tmp_path / "async_receipts", signing_key=signing_key, + independent_page=indep_async, ) as acheck: async_page.fields["Status"] = "Approved" + indep_async.fields["Status"] = "Approved" assert acheck.before_screenshot is not None assert acheck.result is not None return acheck.result @@ -338,7 +403,7 @@ async def _run_async() -> CommitResult: assert async_res.status == "VERIFIED" assert async_res.receipt_path is not None and async_res.receipt_path.is_file() - # 4. Async verify_commit with raising verifier -> ABSTAIN. + # 4. Async verify_commit with raising verifier -> UNCONFIRMED_WRITE / ABSTAIN. async def _raising_verifier(**_: Any) -> dict[str, Any]: raise RuntimeError("VLM timeout") @@ -350,5 +415,5 @@ async def _raising_verifier(**_: Any) -> dict[str, Any]: verifier=_raising_verifier, ) ) - assert res_err.status == "STOPPED" + assert res_err.status == "UNCONFIRMED_WRITE" assert res_err.verdict == "ABSTAIN" From 7f1884f74b429edf4871c3e885d27d5c71b1d8c8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 04:59:31 -0500 Subject: [PATCH 6/6] fix(verify): require distinct independent_page, block no-evidence visual check, and fix example (#2560) --- .github/workflows/packages.yml | 2 +- examples/playwright_commit_firewall.py | 7 +- .../src/openadapt_verify/commit_firewall.py | 12 ++- packages/verify/tests/test_commit_firewall.py | 76 +++++++++++++++++++ 4 files changed, 90 insertions(+), 7 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 00edaf29fd..4735b0f6f1 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -475,7 +475,7 @@ jobs: python - <<'PY' import xml.etree.ElementTree as ET cases = ET.parse("tests.xml").getroot().findall(".//testcase") - assert len(cases) == 136, f"expected 136 independent-store, surgical-heal, portal-readback, and commit-firewall controls, got {len(cases)}" + assert len(cases) == 138, f"expected 138 independent-store, surgical-heal, portal-readback, and commit-firewall controls, got {len(cases)}" # The PostgreSQL and MySQL quickstart controls need the database # services of verify-clean-install, which runs them; nothing else skips. skipped = {c.get("name") for c in cases if c.find("skipped") is not None} diff --git a/examples/playwright_commit_firewall.py b/examples/playwright_commit_firewall.py index b809a82459..dadd60aa2c 100644 --- a/examples/playwright_commit_firewall.py +++ b/examples/playwright_commit_firewall.py @@ -24,12 +24,13 @@ def main() -> None: out = Path("/tmp/openadapt-ui-commit-check-demo") signing_key = Ed25519PrivateKey.generate() - # 1. Clean commit -> verified + signed Ed25519 record/run/v1 receipt. + # 1. Clean commit -> verified via distinct independent read-back + signed Ed25519 receipt. with ui_commit_check( DemoPage(expected), intent="Bind Policy", expected=expected, record_id="quote-2026-0001", + independent_page=DemoPage(expected), receipt_dir=out, signing_key=signing_key, ) as check: @@ -50,7 +51,9 @@ def main() -> None: ): pass except CommitBlockedError as err: - print(f"STOPPED | verdict={err.result.verdict} | reason={err.reason}") + print( + f"{err.result.status} | verdict={err.result.verdict} | reason={err.reason}" + ) if __name__ == "__main__": diff --git a/packages/verify/src/openadapt_verify/commit_firewall.py b/packages/verify/src/openadapt_verify/commit_firewall.py index b41b84c644..e10edcd66b 100644 --- a/packages/verify/src/openadapt_verify/commit_firewall.py +++ b/packages/verify/src/openadapt_verify/commit_firewall.py @@ -704,7 +704,9 @@ def verify_commit( ) if expected and _is_page_like(read_target): dom_checked = True - dom_independent = independent_page is not None + dom_independent = ( + independent_page is not None and independent_page is not page_or_screenshot + ) dom_passed, mismatches = _check_dom_sync(read_target, expected) shot_fn = getattr(read_target, "screenshot", None) if callable(shot_fn): @@ -718,7 +720,7 @@ def verify_commit( visual_verdict: Optional[CommitVerdict] = None visual_reason = "" - if expected and verifier is not None: + if expected and verifier is not None and (dom_checked or after_png is not None): visual_verdict, visual_reason = _run_visual_verifier_sync( verifier, before_png=before_png, @@ -775,7 +777,9 @@ async def async_verify_commit( ) if expected and _is_page_like(read_target): dom_checked = True - dom_independent = independent_page is not None + dom_independent = ( + independent_page is not None and independent_page is not page_or_screenshot + ) dom_passed, mismatches = await _check_dom_async(read_target, expected) shot_fn = getattr(read_target, "screenshot", None) if callable(shot_fn): @@ -791,7 +795,7 @@ async def async_verify_commit( visual_verdict: Optional[CommitVerdict] = None visual_reason = "" - if expected and verifier is not None: + if expected and verifier is not None and (dom_checked or after_png is not None): visual_verdict, visual_reason = await _run_visual_verifier_async( verifier, before_png=before_png, diff --git a/packages/verify/tests/test_commit_firewall.py b/packages/verify/tests/test_commit_firewall.py index 4012c86721..8f420369de 100644 --- a/packages/verify/tests/test_commit_firewall.py +++ b/packages/verify/tests/test_commit_firewall.py @@ -417,3 +417,79 @@ async def _raising_verifier(**_: Any) -> dict[str, Any]: ) assert res_err.status == "UNCONFIRMED_WRITE" assert res_err.verdict == "ABSTAIN" + + +def test_same_page_as_independent_page_stays_same_screen_sync_and_async( + tmp_path: Path, +) -> None: + """Passing the same page object as both page and independent_page must never verify.""" + signing_key = Ed25519PrivateKey.generate() + sync_page = _SyncPlaywrightPage({"Status": "Approved"}) + + sync_res = verify_commit( + sync_page, + intent="Approve Invoice", + expected={"Status": "Approved"}, + record_id="rec-same-sync", + independent_page=sync_page, + receipt_dir=tmp_path / "sync_receipts", + signing_key=signing_key, + ) + assert sync_res.status == "SAME_SCREEN" + assert sync_res.verdict == "SAME_SCREEN" + assert sync_res.verified is False + assert sync_res.receipt is None + assert sync_res.receipt_id is None + + async_page = _AsyncPlaywrightPage({"Status": "Approved"}) + async_res = asyncio.run( + async_verify_commit( + async_page, + intent="Approve Invoice", + expected={"Status": "Approved"}, + record_id="rec-same-async", + independent_page=async_page, + receipt_dir=tmp_path / "async_receipts", + signing_key=signing_key, + ) + ) + assert async_res.status == "SAME_SCREEN" + assert async_res.verdict == "SAME_SCREEN" + assert async_res.verified is False + assert async_res.receipt is None + assert async_res.receipt_id is None + + +def test_none_evidence_skips_visual_verifier_and_returns_unconfirmed_write( + tmp_path: Path, +) -> None: + """When neither DOM nor screenshot bytes are available, never invoke visual verifier.""" + sync_veto = _DuckPrePostVisualVeto(_FakeVetoVerdict.PASS) + sync_res = verify_commit( + None, + intent="Approve Invoice", + expected={"Status": "Approved"}, + verifier=sync_veto, + inbox=tmp_path / "none_sync_inbox.jsonl", + ) + assert sync_veto.calls == [] + assert sync_res.status == "UNCONFIRMED_WRITE" + assert sync_res.verdict == "ABSTAIN" + assert sync_res.verified is False + assert sync_res.receipt is None + + async_veto = _DuckPrePostVisualVeto(_FakeVetoVerdict.PASS) + async_res = asyncio.run( + async_verify_commit( + None, + intent="Approve Invoice", + expected={"Status": "Approved"}, + verifier=async_veto, + inbox=tmp_path / "none_async_inbox.jsonl", + ) + ) + assert async_veto.calls == [] + assert async_res.status == "UNCONFIRMED_WRITE" + assert async_res.verdict == "ABSTAIN" + assert async_res.verified is False + assert async_res.receipt is None