From 9919b2d4cf9a38251ec81fd2c4765b4ba454a8ca Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 00:54:35 -0500 Subject: [PATCH 1/7] feat(verify): add FreshReloadSummaryOracle and ConfirmationPdfOracle for third-party portal read-back --- .../verify/src/openadapt_verify/__init__.py | 12 + .../src/openadapt_verify/portal_readback.py | 529 ++++++++++++++++++ packages/verify/tests/test_portal_readback.py | 429 ++++++++++++++ 3 files changed, 970 insertions(+) create mode 100644 packages/verify/src/openadapt_verify/portal_readback.py create mode 100644 packages/verify/tests/test_portal_readback.py diff --git a/packages/verify/src/openadapt_verify/__init__.py b/packages/verify/src/openadapt_verify/__init__.py index 5fb1d8a7a0..8c55d4cafb 100644 --- a/packages/verify/src/openadapt_verify/__init__.py +++ b/packages/verify/src/openadapt_verify/__init__.py @@ -26,17 +26,29 @@ from openadapt_flow.write_receipt import verify as verify_receipt from openadapt_verify.guard import checked_write, verified +from openadapt_verify.portal_readback import ( + ConfirmationPdfOracle, + FieldCheck, + FreshReloadSummaryOracle, + PortalReadbackResult, + ReloadProof, +) __version__ = "0.2.0" __all__ = [ "Actor", "AlreadyWritten", + "ConfirmationPdfOracle", "Contract", + "FieldCheck", + "FreshReloadSummaryOracle", "LocalSealVerification", "Outcome", + "PortalReadbackResult", "PortableReceiptVerification", "ReceiptError", + "ReloadProof", "Scope", "WriteBlocked", "WriteGuard", diff --git a/packages/verify/src/openadapt_verify/portal_readback.py b/packages/verify/src/openadapt_verify/portal_readback.py new file mode 100644 index 0000000000..61f48ab820 --- /dev/null +++ b/packages/verify/src/openadapt_verify/portal_readback.py @@ -0,0 +1,529 @@ +"""Third-party portal independent read-back oracles (no DB/API access required). + +Provides two fail-closed verification oracles for third-party web portals (such as +insurance carrier quoting portals or payer portals) where direct SQL or backend +API read-back is unavailable: + +1. ``FreshReloadSummaryOracle``: + Requires cryptographic/session proof of a fresh navigation or full page reload + distinct from the submit DOM, then diffs extracted summary fields against the + expected intake record. Stale in-memory DOM without reload proof -> ``HALT``. + Missing required field -> ``ABSTAIN`` (overall verdict ``HALT``). + Mismatched field -> ``REFUTED`` (overall verdict ``HALT``). + +2. ``ConfirmationPdfOracle``: + Extracts persisted field values from a downloaded quote/submission confirmation + PDF using Python stdlib only (supports uncompressed and ``FlateDecode`` PDF + text streams), normalizes currency/dates/booleans, and diffs every agreed field + against the expected record with per-field provenance and SHA-256 digest. +""" + +from __future__ import annotations + +import datetime as dt +import hashlib +import re +import zlib +from dataclasses import asdict, dataclass +from decimal import Decimal, InvalidOperation +from pathlib import Path +from typing import Any, Literal, Mapping, Sequence + +FieldStatus = Literal["CONFIRMED", "REFUTED", "ABSTAIN"] +Verdict = Literal["VERIFIED", "HALT"] +NavigationType = Literal["reload", "fresh_navigation", "new_session", "same_dom"] + +_VALID_RELOAD_NAV_TYPES = frozenset({"reload", "fresh_navigation", "new_session"}) + +_CURRENCY_RE = re.compile( + r"^\s*([$€£])?\s*([+-]?\d{1,3}(?:,\d{3})*(?:\.\d+)?|[+-]?\d+(?:\.\d+)?)\s*$" +) +_DATE_FORMATS = ( + "%Y-%m-%d", + "%m/%d/%Y", + "%m-%d-%Y", + "%b %d, %Y", + "%B %d, %Y", + "%d %b %Y", + "%d %B %Y", +) +_BOOL_TRUE = frozenset({"true", "yes", "y", "checked", "on"}) +_BOOL_FALSE = frozenset({"false", "no", "n", "unchecked", "off"}) + + +@dataclass(frozen=True) +class ReloadProof: + """Evidence proving the summary page was freshly loaded after commit.""" + + navigation_type: str + submit_url: str + summary_url: str + submit_dom_token: str + summary_dom_token: str + reloaded_at_utc: str = "" + + def validate(self) -> tuple[bool, str]: + if self.navigation_type not in _VALID_RELOAD_NAV_TYPES: + return ( + False, + f"stale_in_memory_dom_without_reload_proof: navigation_type={self.navigation_type!r}", + ) + if not self.submit_dom_token.strip() or not self.summary_dom_token.strip(): + return ( + False, + "stale_in_memory_dom_without_reload_proof: missing submit/summary DOM tokens", + ) + if self.submit_dom_token.strip() == self.summary_dom_token.strip(): + return ( + False, + "stale_in_memory_dom_without_reload_proof: summary_dom_token matches submit_dom_token", + ) + return True, "fresh_reload_confirmed" + + +@dataclass(frozen=True) +class FieldCheck: + field: str + expected: Any + observed: Any + normalized_expected: str + normalized_observed: str | None + status: FieldStatus + provenance: str + + +@dataclass(frozen=True) +class PortalReadbackResult: + verdict: Verdict + channel: str + reason: str + checks: tuple[FieldCheck, ...] + confirmed_count: int + refuted_count: int + abstained_count: int + artifact_sha256: str | None = None + + def to_dict(self) -> dict[str, Any]: + return { + **asdict(self), + "checks": [asdict(c) for c in self.checks], + } + + +def normalize_field_value(value: Any, *, field_type: str | None = None) -> str: + """Normalize currency, dates, booleans, and text without blurring identifier look-alikes.""" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float, Decimal)) and not isinstance(value, bool): + dec = Decimal(str(value)) + return ( + f"{dec.quantize(Decimal('0.01'))}" + if field_type == "currency" + else str(dec.normalize()) + ) + + text = " ".join(str(value).strip().split()) + low = text.lower() + + if field_type == "boolean" or low in _BOOL_TRUE or low in _BOOL_FALSE: + if low in _BOOL_TRUE: + return "true" + if low in _BOOL_FALSE: + return "false" + + if field_type == "date" or re.search( + r"^\d{4}-\d{2}-\d{2}$|^\d{1,2}[/-]\d{1,2}[/-]\d{4}$|^[A-Za-z]{3,9}\s+\d{1,2},\s+\d{4}$", + text, + ): + for fmt in _DATE_FORMATS: + try: + parsed = dt.datetime.strptime(text, fmt).date() + return parsed.isoformat() + except ValueError: + continue + + m_cur = _CURRENCY_RE.match(text) + if m_cur and ( + field_type == "currency" or m_cur.group(1) is not None or "," in m_cur.group(2) + ): + raw_num = m_cur.group(2).replace(",", "") + try: + dec = Decimal(raw_num) + return f"{dec.quantize(Decimal('0.01'))}" + except InvalidOperation: + pass + + if field_type == "number": + try: + return str(Decimal(text.replace(",", "")).normalize()) + except InvalidOperation: + pass + + return text + + +def _compare_fields( + expected_fields: Mapping[str, Any], + observed_fields: Mapping[str, Any], + *, + field_types: Mapping[str, str] | None = None, + provenance_map: Mapping[str, str] | None = None, + default_provenance: str = "", +) -> tuple[tuple[FieldCheck, ...], int, int, int]: + ftypes = field_types or {} + pmap = provenance_map or {} + checks: list[FieldCheck] = [] + confirmed = 0 + refuted = 0 + abstained = 0 + + for fname, exp_val in expected_fields.items(): + ftype = ftypes.get(fname) + norm_exp = normalize_field_value(exp_val, field_type=ftype) + obs_val = observed_fields.get(fname) + prov = pmap.get(fname, default_provenance) + + if obs_val is None or (isinstance(obs_val, str) and not obs_val.strip()): + abstained += 1 + checks.append( + FieldCheck( + field=fname, + expected=exp_val, + observed=obs_val, + normalized_expected=norm_exp, + normalized_observed=None, + status="ABSTAIN", + provenance=prov or "missing_in_readback", + ) + ) + continue + + # Infer currency comparison when either side carries a currency symbol + effective_type = ftype + if effective_type is None and ( + (isinstance(exp_val, str) and any(c in exp_val for c in "$€£")) + or (isinstance(obs_val, str) and any(c in obs_val for c in "$€£")) + ): + effective_type = "currency" + norm_exp = normalize_field_value(exp_val, field_type="currency") + + norm_obs = normalize_field_value(obs_val, field_type=effective_type) + if norm_obs == norm_exp: + confirmed += 1 + status: FieldStatus = "CONFIRMED" + else: + refuted += 1 + status = "REFUTED" + checks.append( + FieldCheck( + field=fname, + expected=exp_val, + observed=obs_val, + normalized_expected=norm_exp, + normalized_observed=norm_obs, + status=status, + provenance=prov, + ) + ) + + return tuple(checks), confirmed, refuted, abstained + + +class FreshReloadSummaryOracle: + """Verify persisted portal summary fields after an explicit fresh reload/navigation.""" + + def verify( + self, + expected_fields: Mapping[str, Any], + observed_summary_fields: Mapping[str, Any], + reload_proof: ReloadProof, + *, + field_types: Mapping[str, str] | None = None, + ) -> PortalReadbackResult: + if not expected_fields: + return PortalReadbackResult( + verdict="HALT", + channel="fresh_reload_summary", + reason="empty_expected_fields", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=0, + ) + + ok_reload, reload_reason = reload_proof.validate() + if not ok_reload: + return PortalReadbackResult( + verdict="HALT", + channel="fresh_reload_summary", + reason=reload_reason, + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + ) + + prov = f"fresh_reload:{reload_proof.navigation_type}:{reload_proof.summary_url}" + checks, confirmed, refuted, abstained = _compare_fields( + expected_fields, + observed_summary_fields, + field_types=field_types, + default_provenance=prov, + ) + + if refuted > 0: + return PortalReadbackResult( + verdict="HALT", + channel="fresh_reload_summary", + reason="field_mismatch", + checks=checks, + confirmed_count=confirmed, + refuted_count=refuted, + abstained_count=abstained, + ) + if abstained > 0: + return PortalReadbackResult( + verdict="HALT", + channel="fresh_reload_summary", + reason="missing_required_fields", + checks=checks, + confirmed_count=confirmed, + refuted_count=refuted, + abstained_count=abstained, + ) + return PortalReadbackResult( + verdict="VERIFIED", + channel="fresh_reload_summary", + reason="ok", + checks=checks, + confirmed_count=confirmed, + refuted_count=0, + abstained_count=0, + ) + + +def _unescape_pdf_literal(raw: str) -> str: + """Decode PDF literal string escapes (\\(, \\), \\\\, \\n, \\r, \\t, octal).""" + out: list[str] = [] + i = 0 + n = len(raw) + while i < n: + ch = raw[i] + if ch == "\\" and i + 1 < n: + nxt = raw[i + 1] + if nxt in ("(", ")", "\\"): + out.append(nxt) + i += 2 + elif nxt == "n": + out.append("\n") + i += 2 + elif nxt == "r": + out.append("\r") + i += 2 + elif nxt == "t": + out.append("\t") + i += 2 + elif nxt in "01234567": + oct_digits = raw[i + 1 : i + 4] + m = re.match(r"^[0-7]{1,3}", oct_digits) + if m: + out.append(chr(int(m.group(0), 8))) + i += 1 + len(m.group(0)) + else: + out.append(nxt) + i += 2 + else: + out.append(nxt) + i += 2 + else: + out.append(ch) + i += 1 + return "".join(out) + + +def _extract_text_from_content_stream(stream_bytes: bytes) -> list[str]: + """Extract text runs from PDF Tj / TJ operators in a decoded content stream.""" + text = stream_bytes.decode("latin-1", errors="ignore") + lines: list[str] = [] + + # Match both single literal `(text) Tj` and array `[(a) -20 (b)] TJ` + token_re = re.compile( + r"\(((?:\\.|[^\\()])*)\)\s*Tj|\[((?:[^\[\]]|\((?:\\.|[^\\()])*\))*)\]\s*TJ", + re.DOTALL, + ) + literal_re = re.compile(r"\(((?:\\.|[^\\()])*)\)") + + for m in token_re.finditer(text): + if m.group(1) is not None: + val = _unescape_pdf_literal(m.group(1)).strip() + if val: + lines.append(val) + elif m.group(2) is not None: + parts = [ + _unescape_pdf_literal(lm.group(1)) + for lm in literal_re.finditer(m.group(2)) + ] + joined = "".join(parts).strip() + if joined: + lines.append(joined) + return lines + + +def extract_pdf_text_stdlib(pdf_bytes: bytes) -> str: + """Extract readable text from uncompressed or FlateDecode PDF streams using stdlib only.""" + if not pdf_bytes.startswith(b"%PDF-"): + raise ValueError("missing %PDF- header") + + extracted_lines: list[str] = [] + stream_re = re.compile(rb"stream\r?\n(.*?)\r?\nendstream", re.DOTALL) + for m in stream_re.finditer(pdf_bytes): + raw_stream = m.group(1) + # Check whether preceding object dictionary indicates FlateDecode + prefix = pdf_bytes[max(0, m.start() - 256) : m.start()] + if b"/FlateDecode" in prefix: + try: + decoded = zlib.decompress(raw_stream) + except zlib.error: + continue + extracted_lines.extend(_extract_text_from_content_stream(decoded)) + else: + extracted_lines.extend(_extract_text_from_content_stream(raw_stream)) + + return "\n".join(extracted_lines) + + +def _default_labels_for_field(field_name: str) -> tuple[str, ...]: + human = field_name.replace("_", " ").strip() + return (human, field_name) + + +class ConfirmationPdfOracle: + """Extract and verify persisted fields from a downloaded quote confirmation PDF.""" + + def verify( + self, + pdf_path: str | Path, + expected_fields: Mapping[str, Any], + *, + field_labels: Mapping[str, Sequence[str]] | None = None, + field_patterns: Mapping[str, str] | None = None, + field_types: Mapping[str, str] | None = None, + ) -> PortalReadbackResult: + if not expected_fields: + return PortalReadbackResult( + verdict="HALT", + channel="confirmation_pdf", + reason="empty_expected_fields", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=0, + ) + + p = Path(pdf_path) + if not p.is_file(): + return PortalReadbackResult( + verdict="HALT", + channel="confirmation_pdf", + reason=f"missing_pdf: {p}", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + ) + + try: + raw_bytes = p.read_bytes() + pdf_sha256 = hashlib.sha256(raw_bytes).hexdigest() + pdf_text = extract_pdf_text_stdlib(raw_bytes) + except (OSError, ValueError) as exc: + return PortalReadbackResult( + verdict="HALT", + channel="confirmation_pdf", + reason=f"corrupt_or_unreadable_pdf: {exc}", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + ) + + if not pdf_text.strip(): + return PortalReadbackResult( + verdict="HALT", + channel="confirmation_pdf", + reason="corrupt_or_unreadable_pdf: no extractable text streams", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + artifact_sha256=pdf_sha256, + ) + + labels_cfg = field_labels or {} + patterns_cfg = field_patterns or {} + observed: dict[str, Any] = {} + provenance: dict[str, str] = {} + + for fname in expected_fields: + if fname in patterns_cfg: + m = re.search( + patterns_cfg[fname], pdf_text, re.IGNORECASE | re.MULTILINE + ) + if m: + val = m.group(1).strip() if m.lastindex else m.group(0).strip() + observed[fname] = val + provenance[fname] = f"pdf:{pdf_sha256[:12]}:regex:{fname}" + continue + + candidate_labels = labels_cfg.get(fname) or _default_labels_for_field(fname) + for lbl in candidate_labels: + pat = re.compile( + rf"(?:^|\n)\s*{re.escape(lbl)}\s*[:\-]\s*([^\n]+)", + re.IGNORECASE, + ) + m = pat.search(pdf_text) + if m: + observed[fname] = m.group(1).strip() + provenance[fname] = f"pdf:{pdf_sha256[:12]}:label={lbl!r}" + break + + checks, confirmed, refuted, abstained = _compare_fields( + expected_fields, + observed, + field_types=field_types, + provenance_map=provenance, + default_provenance=f"pdf:{pdf_sha256[:12]}:missing", + ) + + if refuted > 0: + return PortalReadbackResult( + verdict="HALT", + channel="confirmation_pdf", + reason="field_mismatch", + checks=checks, + confirmed_count=confirmed, + refuted_count=refuted, + abstained_count=abstained, + artifact_sha256=pdf_sha256, + ) + if abstained > 0: + return PortalReadbackResult( + verdict="HALT", + channel="confirmation_pdf", + reason="missing_required_fields", + checks=checks, + confirmed_count=confirmed, + refuted_count=refuted, + abstained_count=abstained, + artifact_sha256=pdf_sha256, + ) + return PortalReadbackResult( + verdict="VERIFIED", + channel="confirmation_pdf", + reason="ok", + checks=checks, + confirmed_count=confirmed, + refuted_count=0, + abstained_count=0, + artifact_sha256=pdf_sha256, + ) diff --git a/packages/verify/tests/test_portal_readback.py b/packages/verify/tests/test_portal_readback.py new file mode 100644 index 0000000000..53bdd3a157 --- /dev/null +++ b/packages/verify/tests/test_portal_readback.py @@ -0,0 +1,429 @@ +"""Tests for third-party portal independent read-back oracles (no DB/API access).""" + +from __future__ import annotations + +import json +import zlib +from pathlib import Path + +from openadapt_verify.portal_readback import ( + ConfirmationPdfOracle, + FreshReloadSummaryOracle, + ReloadProof, + extract_pdf_text_stdlib, + normalize_field_value, +) + + +def _escape_pdf_text(text: str) -> str: + return text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)") + + +def _make_synthetic_pdf( + lines: list[str], + *, + compress: bool = False, + use_tj_array: bool = False, +) -> bytes: + """Build a minimal valid PDF containing text lines in Tj or TJ operators.""" + ops: list[str] = ["BT", "/F1 12 Tf", "72 720 Td"] + for idx, line in enumerate(lines): + if idx > 0: + ops.append("0 -16 Td") + if use_tj_array and ":" in line: + left, right = line.split(":", 1) + ops.append( + f"[({_escape_pdf_text(left + ':')}) -10 ({_escape_pdf_text(right)})] TJ" + ) + else: + ops.append(f"({_escape_pdf_text(line)}) Tj") + ops.append("ET") + stream_data = "\n".join(ops).encode("latin-1") + + if compress: + payload = zlib.compress(stream_data) + stream_dict = f"<< /Length {len(payload)} /Filter /FlateDecode >>" + else: + payload = stream_data + stream_dict = f"<< /Length {len(payload)} >>" + + parts = [ + b"%PDF-1.4\n", + b"1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n", + b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n", + b"3 0 obj << /Type /Page /Parent 2 0 R /Contents 4 0 R >> endobj\n", + f"4 0 obj {stream_dict}\nstream\n".encode("latin-1") + + payload + + b"\nendstream\nendobj\n", + b"%%EOF\n", + ] + return b"".join(parts) + + +class TestFreshReloadSummaryOracle: + def test_happy_path_verified_with_normalization(self) -> None: + oracle = FreshReloadSummaryOracle() + proof = ReloadProof( + navigation_type="reload", + submit_url="https://carrier.example/quote/submit", + summary_url="https://carrier.example/quote/Q-90412/summary", + submit_dom_token="dom-submit-111", + summary_dom_token="dom-summary-222", + reloaded_at_utc="2026-11-23T05:10:00Z", + ) + expected = { + "insured_name": "Jordan Rivera", + "effective_date": "2026-03-14", + "deductible": 1000, + "prior_losses": 0, + "bundled_auto": True, + "quote_id": "MRN-88041", + } + observed = { + "insured_name": " Jordan Rivera ", + "effective_date": "03/14/2026", + "deductible": "$1,000.00", + "prior_losses": "0", + "bundled_auto": "Yes", + "quote_id": "MRN-88041", + } + + res = oracle.verify(expected, observed, proof) + + assert res.verdict == "VERIFIED" + assert res.channel == "fresh_reload_summary" + assert res.reason == "ok" + assert res.confirmed_count == 6 + assert res.refuted_count == 0 + assert res.abstained_count == 0 + assert all(c.status == "CONFIRMED" for c in res.checks) + assert all("fresh_reload:reload:" in c.provenance for c in res.checks) + # Ensure JSON serializability + payload = json.dumps(res.to_dict()) + assert "VERIFIED" in payload + + def test_stale_same_dom_halts_fail_closed(self) -> None: + oracle = FreshReloadSummaryOracle() + stale_proof = ReloadProof( + navigation_type="same_dom", + submit_url="https://carrier.example/quote/submit", + summary_url="https://carrier.example/quote/submit", + submit_dom_token="dom-111", + summary_dom_token="dom-222", + ) + res = oracle.verify({"prior_losses": 0}, {"prior_losses": 0}, stale_proof) + + assert res.verdict == "HALT" + assert "stale_in_memory_dom_without_reload_proof" in res.reason + assert res.confirmed_count == 0 + assert res.abstained_count == 1 + + def test_identical_dom_tokens_halt_fail_closed(self) -> None: + oracle = FreshReloadSummaryOracle() + same_token_proof = ReloadProof( + navigation_type="reload", + submit_url="https://carrier.example/quote/submit", + summary_url="https://carrier.example/quote/summary", + submit_dom_token="dom-same-token", + summary_dom_token="dom-same-token", + ) + res = oracle.verify({"prior_losses": 0}, {"prior_losses": 0}, same_token_proof) + + assert res.verdict == "HALT" + assert "summary_dom_token matches submit_dom_token" in res.reason + + def test_missing_dom_tokens_halt_fail_closed(self) -> None: + oracle = FreshReloadSummaryOracle() + missing_token_proof = ReloadProof( + navigation_type="fresh_navigation", + submit_url="https://carrier.example/quote/submit", + summary_url="https://carrier.example/quote/summary", + submit_dom_token="dom-submit-1", + summary_dom_token=" ", + ) + res = oracle.verify( + {"prior_losses": 0}, {"prior_losses": 0}, missing_token_proof + ) + + assert res.verdict == "HALT" + assert "missing submit/summary DOM tokens" in res.reason + + def test_field_mismatch_halts_with_refuted_check(self) -> None: + oracle = FreshReloadSummaryOracle() + proof = ReloadProof( + navigation_type="new_session", + submit_url="https://carrier.example/quote/submit", + summary_url="https://carrier.example/quote/summary", + submit_dom_token="dom-a", + summary_dom_token="dom-b", + ) + res = oracle.verify( + {"prior_losses": 0, "deductible": 1000}, + {"prior_losses": 2, "deductible": "$1,000.00"}, + proof, + ) + + assert res.verdict == "HALT" + assert res.reason == "field_mismatch" + assert res.confirmed_count == 1 + assert res.refuted_count == 1 + assert res.abstained_count == 0 + refuted = [c for c in res.checks if c.status == "REFUTED"] + assert len(refuted) == 1 + assert refuted[0].field == "prior_losses" + assert refuted[0].normalized_expected == "0" + assert refuted[0].normalized_observed == "2" + + def test_missing_required_field_abstains_and_halts(self) -> None: + oracle = FreshReloadSummaryOracle() + proof = ReloadProof( + navigation_type="reload", + submit_url="https://carrier.example/quote/submit", + summary_url="https://carrier.example/quote/summary", + submit_dom_token="dom-a", + summary_dom_token="dom-b", + ) + res = oracle.verify( + {"prior_losses": 0, "roof_year": 2018}, + {"prior_losses": 0}, + proof, + ) + + assert res.verdict == "HALT" + assert res.reason == "missing_required_fields" + assert res.confirmed_count == 1 + assert res.refuted_count == 0 + assert res.abstained_count == 1 + abstained = [c for c in res.checks if c.status == "ABSTAIN"] + assert len(abstained) == 1 + assert abstained[0].field == "roof_year" + + def test_lookalike_identifier_is_not_blurred(self) -> None: + oracle = FreshReloadSummaryOracle() + proof = ReloadProof( + navigation_type="reload", + submit_url="https://carrier.example/submit", + summary_url="https://carrier.example/summary", + submit_dom_token="dom-a", + summary_dom_token="dom-b", + ) + res = oracle.verify( + {"policy_ref": "MRN-88041"}, + {"policy_ref": "MRN-88O41"}, + proof, + ) + + assert res.verdict == "HALT" + assert res.reason == "field_mismatch" + assert res.refuted_count == 1 + + def test_empty_expected_fields_halts(self) -> None: + oracle = FreshReloadSummaryOracle() + proof = ReloadProof( + navigation_type="reload", + submit_url="https://carrier.example/submit", + summary_url="https://carrier.example/summary", + submit_dom_token="dom-a", + summary_dom_token="dom-b", + ) + res = oracle.verify({}, {"a": 1}, proof) + assert res.verdict == "HALT" + assert res.reason == "empty_expected_fields" + + +class TestConfirmationPdfOracle: + def test_uncompressed_quote_pdf_verified(self, tmp_path: Path) -> None: + pdf_path = tmp_path / "quote_confirmation.pdf" + pdf_bytes = _make_synthetic_pdf( + [ + "Carrier Quote Confirmation (Homeowners)", + "Insured Name: Jordan Rivera", + "Effective Date: 03/14/2026", + "Deductible: $1,000.00", + "Prior Losses: 0", + "Bundled Auto: Yes", + "Quote Number: NW-2026-88041", + ], + compress=False, + use_tj_array=True, + ) + pdf_path.write_bytes(pdf_bytes) + + oracle = ConfirmationPdfOracle() + res = oracle.verify( + pdf_path, + expected_fields={ + "insured_name": "Jordan Rivera", + "effective_date": "2026-03-14", + "deductible": 1000, + "prior_losses": 0, + "bundled_auto": True, + "quote_number": "NW-2026-88041", + }, + ) + + assert res.verdict == "VERIFIED" + assert res.channel == "confirmation_pdf" + assert res.reason == "ok" + assert res.confirmed_count == 6 + assert res.refuted_count == 0 + assert res.abstained_count == 0 + assert res.artifact_sha256 is not None and len(res.artifact_sha256) == 64 + assert all( + c.provenance.startswith(f"pdf:{res.artifact_sha256[:12]}:") + for c in res.checks + ) + + def test_flatedecode_compressed_pdf_verified(self, tmp_path: Path) -> None: + pdf_path = tmp_path / "quote_compressed.pdf" + pdf_bytes = _make_synthetic_pdf( + [ + "Named Insured: Taylor Chen", + "Policy Effective: March 14, 2026", + "Annual Premium: $2,450.50", + "Prior Claims: 0", + ], + compress=True, + ) + pdf_path.write_bytes(pdf_bytes) + + oracle = ConfirmationPdfOracle() + res = oracle.verify( + pdf_path, + expected_fields={ + "insured_name": "Taylor Chen", + "effective_date": "2026-03-14", + "annual_premium": "2450.50", + "prior_losses": 0, + }, + field_labels={ + "insured_name": ("Named Insured", "Insured Name"), + "effective_date": ("Policy Effective", "Effective Date"), + "prior_losses": ("Prior Claims", "Prior Losses"), + }, + field_types={"annual_premium": "currency"}, + ) + + assert res.verdict == "VERIFIED" + assert res.confirmed_count == 4 + assert res.artifact_sha256 is not None + + def test_pdf_field_mismatch_halts(self, tmp_path: Path) -> None: + pdf_path = tmp_path / "quote_mismatch.pdf" + pdf_path.write_bytes( + _make_synthetic_pdf( + [ + "Insured Name: Jordan Rivera", + "Prior Losses: 2", + "Deductible: $1,000.00", + ], + compress=True, + ) + ) + + oracle = ConfirmationPdfOracle() + res = oracle.verify( + pdf_path, + expected_fields={ + "insured_name": "Jordan Rivera", + "prior_losses": 0, + "deductible": 1000, + }, + ) + + assert res.verdict == "HALT" + assert res.reason == "field_mismatch" + assert res.confirmed_count == 2 + assert res.refuted_count == 1 + refuted = [c for c in res.checks if c.status == "REFUTED"] + assert refuted[0].field == "prior_losses" + assert refuted[0].normalized_observed == "2" + + def test_pdf_missing_required_field_abstains_and_halts( + self, tmp_path: Path + ) -> None: + pdf_path = tmp_path / "quote_partial.pdf" + pdf_path.write_bytes(_make_synthetic_pdf(["Insured Name: Jordan Rivera"])) + + oracle = ConfirmationPdfOracle() + res = oracle.verify( + pdf_path, + expected_fields={ + "insured_name": "Jordan Rivera", + "roof_year": 2018, + }, + ) + + assert res.verdict == "HALT" + assert res.reason == "missing_required_fields" + assert res.confirmed_count == 1 + assert res.abstained_count == 1 + + def test_missing_pdf_file_halts(self, tmp_path: Path) -> None: + oracle = ConfirmationPdfOracle() + res = oracle.verify(tmp_path / "does_not_exist.pdf", {"insured_name": "Jordan"}) + + assert res.verdict == "HALT" + assert res.reason.startswith("missing_pdf:") + assert res.abstained_count == 1 + + def test_corrupt_non_pdf_bytes_halt(self, tmp_path: Path) -> None: + bad_pdf = tmp_path / "corrupt.pdf" + bad_pdf.write_bytes(b"502 Bad Gateway") + + oracle = ConfirmationPdfOracle() + res = oracle.verify(bad_pdf, {"insured_name": "Jordan"}) + + assert res.verdict == "HALT" + assert "corrupt_or_unreadable_pdf" in res.reason + + def test_pdf_without_extractable_text_halts(self, tmp_path: Path) -> None: + image_only_pdf = tmp_path / "scanned_image_only.pdf" + image_only_pdf.write_bytes( + b"%PDF-1.4\n1 0 obj << /Length 4 >>\nstream\n\x00\x01\x02\x03\nendstream\nendobj\n%%EOF\n" + ) + + oracle = ConfirmationPdfOracle() + res = oracle.verify(image_only_pdf, {"insured_name": "Jordan"}) + + assert res.verdict == "HALT" + assert "no extractable text streams" in res.reason + assert res.artifact_sha256 is not None + + def test_custom_field_pattern_extraction(self, tmp_path: Path) -> None: + pdf_path = tmp_path / "regex_quote.pdf" + pdf_path.write_bytes( + _make_synthetic_pdf(["Confirmation #NW-99421 issued for $1,250.00"]) + ) + + oracle = ConfirmationPdfOracle() + res = oracle.verify( + pdf_path, + expected_fields={"quote_id": "NW-99421", "premium": 1250}, + field_patterns={ + "quote_id": r"Confirmation #([A-Z0-9-]+)", + "premium": r"issued for (\$[0-9,]+\.\d{2})", + }, + ) + + assert res.verdict == "VERIFIED" + assert res.confirmed_count == 2 + assert all(":regex:" in c.provenance for c in res.checks) + + def test_empty_expected_fields_halts(self, tmp_path: Path) -> None: + pdf_path = tmp_path / "any.pdf" + pdf_path.write_bytes(_make_synthetic_pdf(["Insured Name: Jordan"])) + oracle = ConfirmationPdfOracle() + res = oracle.verify(pdf_path, {}) + assert res.verdict == "HALT" + assert res.reason == "empty_expected_fields" + + +def test_normalize_and_extract_helpers() -> None: + assert normalize_field_value("$1,200.50") == "1200.50" + assert normalize_field_value("03/14/2026") == "2026-03-14" + assert normalize_field_value("Yes") == "true" + assert normalize_field_value("No") == "false" + + pdf_bytes = _make_synthetic_pdf(["Line (1): OK"], compress=False) + assert "Line (1): OK" in extract_pdf_text_stdlib(pdf_bytes) From 3fbf185b534f9175f48843dce1def67a2230778d Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 08:57:30 -0500 Subject: [PATCH 2/7] fix(verify): fix TJ regex backtracking (CodeQL) and allow >=105 verify facade tests --- .github/workflows/packages.yml | 2 +- packages/verify/src/openadapt_verify/portal_readback.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 1292dba79c..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) == 105, "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/packages/verify/src/openadapt_verify/portal_readback.py b/packages/verify/src/openadapt_verify/portal_readback.py index 61f48ab820..1db28043e5 100644 --- a/packages/verify/src/openadapt_verify/portal_readback.py +++ b/packages/verify/src/openadapt_verify/portal_readback.py @@ -346,9 +346,10 @@ def _extract_text_from_content_stream(stream_bytes: bytes) -> list[str]: text = stream_bytes.decode("latin-1", errors="ignore") lines: list[str] = [] - # Match both single literal `(text) Tj` and array `[(a) -20 (b)] TJ` + # Match both single literal `(text) Tj` and array `[(a) -20 (b)] TJ`. + # Alternatives inside the TJ array are strictly disjoint (no backtracking). token_re = re.compile( - r"\(((?:\\.|[^\\()])*)\)\s*Tj|\[((?:[^\[\]]|\((?:\\.|[^\\()])*\))*)\]\s*TJ", + r"\(((?:\\.|[^\\()])*)\)\s*Tj|\[((?:[^\[\]()]|\((?:\\.|[^\\()])*\))*)\]\s*TJ", re.DOTALL, ) literal_re = re.compile(r"\(((?:\\.|[^\\()])*)\)") From 0905415c4487242d21c5f9b29ec666632c76097d Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 09:19:17 -0500 Subject: [PATCH 3/7] fix(verify): enforce artifact_provenance, PDF integrity, ReloadProof URL/digest/producer, currency codes, and plain Decimal formatting --- .../src/openadapt_verify/portal_readback.py | 367 +++++++++++++-- packages/verify/tests/test_portal_readback.py | 427 +++++++++--------- 2 files changed, 545 insertions(+), 249 deletions(-) diff --git a/packages/verify/src/openadapt_verify/portal_readback.py b/packages/verify/src/openadapt_verify/portal_readback.py index 1db28043e5..d81709dca2 100644 --- a/packages/verify/src/openadapt_verify/portal_readback.py +++ b/packages/verify/src/openadapt_verify/portal_readback.py @@ -5,36 +5,56 @@ API read-back is unavailable: 1. ``FreshReloadSummaryOracle``: - Requires cryptographic/session proof of a fresh navigation or full page reload - distinct from the submit DOM, then diffs extracted summary fields against the - expected intake record. Stale in-memory DOM without reload proof -> ``HALT``. - Missing required field -> ``ABSTAIN`` (overall verdict ``HALT``). - Mismatched field -> ``REFUTED`` (overall verdict ``HALT``). + Requires an independent producer (``separate_session`` or ``system_of_record``), + valid same-origin ``submit_url`` / ``summary_url``, ISO-8601 ``reloaded_at_utc``, + a 64-hex ``summary_dom_sha256`` digest, and distinct non-empty DOM tokens + proving a fresh navigation/reload distinct from the submit DOM, then diffs + extracted summary fields against the expected intake record. 2. ``ConfirmationPdfOracle``: - Extracts persisted field values from a downloaded quote/submission confirmation - PDF using Python stdlib only (supports uncompressed and ``FlateDecode`` PDF - text streams), normalizes currency/dates/booleans, and diffs every agreed field - against the expected record with per-field provenance and SHA-256 digest. + Enforces artifact provenance via + :mod:`openadapt_flow.runtime.effects.artifact_provenance` (refusing ``unknown``, + ``acting_session``, ``Downloads``, ``playwright-artifacts-*``, and symlinks + escaping the store), checks PDF integrity (``%%EOF``, no incremental-update + shadowing, no silent ``FlateDecode`` decompression errors, optional + ``expected_fetch_sha256``), ignores invisible text (``3 Tr``), detects + ambiguous duplicate labels with conflicting values, preserves currency codes, + and diffs every field with per-field provenance and SHA-256 artifact digest. """ from __future__ import annotations import datetime as dt import hashlib +import hmac import re import zlib -from dataclasses import asdict, dataclass +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass, field from decimal import Decimal, InvalidOperation from pathlib import Path -from typing import Any, Literal, Mapping, Sequence +from typing import Any, Literal +from urllib.parse import urlsplit + +from openadapt_flow.runtime.effects.artifact_provenance import ( + ArtifactProducer, + grade_artifact, + parse_producer, +) FieldStatus = Literal["CONFIRMED", "REFUTED", "ABSTAIN"] Verdict = Literal["VERIFIED", "HALT"] +ReceiptVerdict = Literal["CONFIRMED", "REFUTED", "UNCERTAIN"] NavigationType = Literal["reload", "fresh_navigation", "new_session", "same_dom"] _VALID_RELOAD_NAV_TYPES = frozenset({"reload", "fresh_navigation", "new_session"}) +_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$") +_CURRENCY_SYMBOL_TO_CODE = { + "$": "USD", + "€": "EUR", + "£": "GBP", +} _CURRENCY_RE = re.compile( r"^\s*([$€£])?\s*([+-]?\d{1,3}(?:,\d{3})*(?:\.\d+)?|[+-]?\d+(?:\.\d+)?)\s*$" ) @@ -51,9 +71,39 @@ _BOOL_FALSE = frozenset({"false", "no", "n", "unchecked", "off"}) +def _valid_http_origin(url: str) -> str | None: + if not isinstance(url, str) or not url.strip(): + return None + parsed = urlsplit(url.strip()) + if parsed.scheme not in ("http", "https") or not parsed.netloc: + return None + return f"{parsed.scheme.lower()}://{parsed.netloc.lower()}" + + +def _valid_iso_utc(ts: str) -> bool: + if not isinstance(ts, str) or not ts.strip(): + return False + norm = ts.strip() + if norm.endswith("Z"): + norm = norm[:-1] + "+00:00" + try: + parsed = dt.datetime.fromisoformat(norm) + except ValueError: + return False + return parsed.tzinfo is not None + + +def _format_decimal_plain(dec: Decimal) -> str: + """Format a Decimal without scientific notation (e.g. 2000 -> '2000', not '2E+3').""" + text = format(dec, "f") + if "." in text: + text = text.rstrip("0").rstrip(".") + return "0" if text in ("", "-0") else text + + @dataclass(frozen=True) class ReloadProof: - """Evidence proving the summary page was freshly loaded after commit.""" + """Evidence proving the summary page was freshly loaded in an independent session.""" navigation_type: str submit_url: str @@ -61,13 +111,49 @@ class ReloadProof: submit_dom_token: str summary_dom_token: str reloaded_at_utc: str = "" + summary_dom_sha256: str = "" + producer: str | ArtifactProducer = ArtifactProducer.UNKNOWN def validate(self) -> tuple[bool, str]: + try: + parsed_producer = parse_producer(self.producer) + except ValueError as exc: + return False, f"unverified_producer_provenance: {exc}" + if parsed_producer not in ( + ArtifactProducer.SEPARATE_SESSION, + ArtifactProducer.SYSTEM_OF_RECORD, + ): + return ( + False, + f"unverified_producer_provenance: producer={parsed_producer.value!r} cannot issue VERIFIED", + ) if self.navigation_type not in _VALID_RELOAD_NAV_TYPES: return ( False, f"stale_in_memory_dom_without_reload_proof: navigation_type={self.navigation_type!r}", ) + submit_origin = _valid_http_origin(self.submit_url) + summary_origin = _valid_http_origin(self.summary_url) + if not submit_origin or not summary_origin: + return ( + False, + "stale_in_memory_dom_without_reload_proof: submit_url and summary_url must be valid http(s) URLs", + ) + if submit_origin != summary_origin: + return ( + False, + "stale_in_memory_dom_without_reload_proof: summary_url origin does not match submit_url origin", + ) + if not _valid_iso_utc(self.reloaded_at_utc): + return ( + False, + "stale_in_memory_dom_without_reload_proof: reloaded_at_utc must be a timezone-aware ISO-8601 timestamp", + ) + if not _SHA256_RE.match(self.summary_dom_sha256.strip()): + return ( + False, + "stale_in_memory_dom_without_reload_proof: summary_dom_sha256 must be a 64-hex SHA-256 digest", + ) if not self.submit_dom_token.strip() or not self.summary_dom_token.strip(): return ( False, @@ -102,6 +188,8 @@ class PortalReadbackResult: refuted_count: int abstained_count: int artifact_sha256: str | None = None + receipt_verdict: ReceiptVerdict = "UNCERTAIN" + provenance_evidence: dict[str, Any] = field(default_factory=dict) def to_dict(self) -> dict[str, Any]: return { @@ -111,7 +199,7 @@ def to_dict(self) -> dict[str, Any]: def normalize_field_value(value: Any, *, field_type: str | None = None) -> str: - """Normalize currency, dates, booleans, and text without blurring identifier look-alikes.""" + """Normalize currency, dates, booleans, and numbers without blurring look-alikes or currencies.""" if isinstance(value, bool): return "true" if value else "false" if isinstance(value, (int, float, Decimal)) and not isinstance(value, bool): @@ -119,7 +207,7 @@ def normalize_field_value(value: Any, *, field_type: str | None = None) -> str: return ( f"{dec.quantize(Decimal('0.01'))}" if field_type == "currency" - else str(dec.normalize()) + else _format_decimal_plain(dec) ) text = " ".join(str(value).strip().split()) @@ -148,20 +236,51 @@ def normalize_field_value(value: Any, *, field_type: str | None = None) -> str: ): raw_num = m_cur.group(2).replace(",", "") try: - dec = Decimal(raw_num) - return f"{dec.quantize(Decimal('0.01'))}" + dec = Decimal(raw_num).quantize(Decimal("0.01")) + sym = m_cur.group(1) + if sym is not None: + code = _CURRENCY_SYMBOL_TO_CODE.get(sym, sym) + return f"{code}:{dec}" + return f"{dec}" except InvalidOperation: pass if field_type == "number": try: - return str(Decimal(text.replace(",", "")).normalize()) + return _format_decimal_plain(Decimal(text.replace(",", ""))) except InvalidOperation: pass return text +def _strip_currency_code(norm: str) -> tuple[str | None, str]: + m = re.match(r"^([A-Z]{3}):([+-]?\d+\.\d{2})$", norm) + if m: + return m.group(1), m.group(2) + return None, norm + + +def _values_match(norm_exp: str, norm_obs: str) -> bool: + if norm_exp == norm_obs: + return True + exp_code, exp_num = _strip_currency_code(norm_exp) + obs_code, obs_num = _strip_currency_code(norm_obs) + # Two explicit currencies MUST match currency code (USD:500.00 != EUR:500.00). + if exp_code is not None and obs_code is not None: + return exp_code == obs_code and exp_num == obs_num + # If only one side carried a currency symbol (e.g. expected int 1000 vs "$1,000.00"), + # compare quantized numeric amounts. + if (exp_code is not None) != (obs_code is not None): + try: + return Decimal(exp_num).quantize(Decimal("0.01")) == Decimal( + obs_num + ).quantize(Decimal("0.01")) + except InvalidOperation: + return False + return False + + def _compare_fields( expected_fields: Mapping[str, Any], observed_fields: Mapping[str, Any], @@ -198,7 +317,6 @@ def _compare_fields( ) continue - # Infer currency comparison when either side carries a currency symbol effective_type = ftype if effective_type is None and ( (isinstance(exp_val, str) and any(c in exp_val for c in "$€£")) @@ -208,7 +326,7 @@ def _compare_fields( norm_exp = normalize_field_value(exp_val, field_type="currency") norm_obs = normalize_field_value(obs_val, field_type=effective_type) - if norm_obs == norm_exp: + if _values_match(norm_exp, norm_obs): confirmed += 1 status: FieldStatus = "CONFIRMED" else: @@ -230,7 +348,7 @@ def _compare_fields( class FreshReloadSummaryOracle: - """Verify persisted portal summary fields after an explicit fresh reload/navigation.""" + """Verify persisted portal summary fields after an independent fresh reload.""" def verify( self, @@ -243,6 +361,7 @@ def verify( if not expected_fields: return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="fresh_reload_summary", reason="empty_expected_fields", checks=(), @@ -255,6 +374,7 @@ def verify( if not ok_reload: return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="fresh_reload_summary", reason=reload_reason, checks=(), @@ -263,42 +383,59 @@ def verify( abstained_count=len(expected_fields), ) - prov = f"fresh_reload:{reload_proof.navigation_type}:{reload_proof.summary_url}" + parsed_producer = parse_producer(reload_proof.producer) + dom_sha = reload_proof.summary_dom_sha256.strip().lower() + prov = f"fresh_reload:{parsed_producer.value}:{reload_proof.navigation_type}:{reload_proof.summary_url}" checks, confirmed, refuted, abstained = _compare_fields( expected_fields, observed_summary_fields, field_types=field_types, default_provenance=prov, ) + prov_evidence = { + "producer": parsed_producer.value, + "navigation_type": reload_proof.navigation_type, + "reloaded_at_utc": reload_proof.reloaded_at_utc, + "summary_dom_sha256": dom_sha, + } if refuted > 0: return PortalReadbackResult( verdict="HALT", + receipt_verdict="REFUTED", channel="fresh_reload_summary", reason="field_mismatch", checks=checks, confirmed_count=confirmed, refuted_count=refuted, abstained_count=abstained, + artifact_sha256=dom_sha, + provenance_evidence=prov_evidence, ) if abstained > 0: return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="fresh_reload_summary", reason="missing_required_fields", checks=checks, confirmed_count=confirmed, refuted_count=refuted, abstained_count=abstained, + artifact_sha256=dom_sha, + provenance_evidence=prov_evidence, ) return PortalReadbackResult( verdict="VERIFIED", + receipt_verdict="CONFIRMED", channel="fresh_reload_summary", reason="ok", checks=checks, confirmed_count=confirmed, refuted_count=0, abstained_count=0, + artifact_sha256=dom_sha, + provenance_evidence=prov_evidence, ) @@ -342,27 +479,36 @@ def _unescape_pdf_literal(raw: str) -> str: def _extract_text_from_content_stream(stream_bytes: bytes) -> list[str]: - """Extract text runs from PDF Tj / TJ operators in a decoded content stream.""" + """Extract visible text runs from PDF Tj / TJ operators, skipping invisible (3 Tr) runs.""" text = stream_bytes.decode("latin-1", errors="ignore") lines: list[str] = [] + render_mode = 0 - # Match both single literal `(text) Tj` and array `[(a) -20 (b)] TJ`. + # Match rendering mode ` Tr`, single literal `(text) Tj`, and array `[(a) -20 (b)] TJ`. # Alternatives inside the TJ array are strictly disjoint (no backtracking). token_re = re.compile( - r"\(((?:\\.|[^\\()])*)\)\s*Tj|\[((?:[^\[\]()]|\((?:\\.|[^\\()])*\))*)\]\s*TJ", + r"\b([0-7])\s+Tr\b" + r"|\(((?:\\.|[^\\()])*)\)\s*Tj" + r"|\[((?:[^\[\]()]|\((?:\\.|[^\\()])*\))*)\]\s*TJ", re.DOTALL, ) literal_re = re.compile(r"\(((?:\\.|[^\\()])*)\)") for m in token_re.finditer(text): if m.group(1) is not None: - val = _unescape_pdf_literal(m.group(1)).strip() + render_mode = int(m.group(1)) + continue + if render_mode == 3: + # PDF render mode 3 is invisible text (neither fill nor stroke). + continue + if m.group(2) is not None: + val = _unescape_pdf_literal(m.group(2)).strip() if val: lines.append(val) - elif m.group(2) is not None: + elif m.group(3) is not None: parts = [ _unescape_pdf_literal(lm.group(1)) - for lm in literal_re.finditer(m.group(2)) + for lm in literal_re.finditer(m.group(3)) ] joined = "".join(parts).strip() if joined: @@ -371,21 +517,29 @@ def _extract_text_from_content_stream(stream_bytes: bytes) -> list[str]: def extract_pdf_text_stdlib(pdf_bytes: bytes) -> str: - """Extract readable text from uncompressed or FlateDecode PDF streams using stdlib only.""" + """Extract readable text from uncompressed or FlateDecode PDF streams using stdlib only. + + Fails closed on missing ``%PDF-`` header, missing or multiple ``%%EOF`` + markers (incremental-update shadowing), or corrupt ``/FlateDecode`` streams. + """ if not pdf_bytes.startswith(b"%PDF-"): raise ValueError("missing %PDF- header") + eof_count = pdf_bytes.count(b"%%EOF") + if eof_count == 0: + raise ValueError("missing %%EOF trailer") + if eof_count > 1: + raise ValueError("incremental PDF updates (multiple %%EOF) are not allowed") extracted_lines: list[str] = [] stream_re = re.compile(rb"stream\r?\n(.*?)\r?\nendstream", re.DOTALL) for m in stream_re.finditer(pdf_bytes): raw_stream = m.group(1) - # Check whether preceding object dictionary indicates FlateDecode prefix = pdf_bytes[max(0, m.start() - 256) : m.start()] if b"/FlateDecode" in prefix: try: decoded = zlib.decompress(raw_stream) - except zlib.error: - continue + except zlib.error as exc: + raise ValueError(f"corrupt FlateDecode stream: {exc}") from exc extracted_lines.extend(_extract_text_from_content_stream(decoded)) else: extracted_lines.extend(_extract_text_from_content_stream(raw_stream)) @@ -399,13 +553,16 @@ def _default_labels_for_field(field_name: str) -> tuple[str, ...]: class ConfirmationPdfOracle: - """Extract and verify persisted fields from a downloaded quote confirmation PDF.""" + """Extract and verify persisted fields from an independently obtained confirmation PDF.""" def verify( self, pdf_path: str | Path, expected_fields: Mapping[str, Any], *, + producer: str | ArtifactProducer = ArtifactProducer.UNKNOWN, + acting_roots: Sequence[str | Path] | None = None, + expected_fetch_sha256: str | None = None, field_labels: Mapping[str, Sequence[str]] | None = None, field_patterns: Mapping[str, str] | None = None, field_types: Mapping[str, str] | None = None, @@ -413,6 +570,7 @@ def verify( if not expected_fields: return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="confirmation_pdf", reason="empty_expected_fields", checks=(), @@ -425,6 +583,7 @@ def verify( if not p.is_file(): return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="confirmation_pdf", reason=f"missing_pdf: {p}", checks=(), @@ -433,24 +592,94 @@ def verify( abstained_count=len(expected_fields), ) + try: + grade = grade_artifact( + producer, + root=p.parent, + acting_roots=acting_roots, + observe_local=True, + ) + except ValueError as exc: + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + channel="confirmation_pdf", + reason=f"unverified_producer_provenance: {exc}", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + ) + + prov_evidence = grade.evidence() + if not grade.independent: + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + channel="confirmation_pdf", + reason=( + f"unverified_producer_provenance: producer={grade.producer.value!r} " + f"(check_level={grade.check_level.label}) cannot issue VERIFIED" + ), + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + provenance_evidence=prov_evidence, + ) + + acting_reason = grade.acting_artifact([p]) + if acting_reason: + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + channel="confirmation_pdf", + reason=f"unverified_producer_provenance: {acting_reason}", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + provenance_evidence=prov_evidence, + ) + try: raw_bytes = p.read_bytes() pdf_sha256 = hashlib.sha256(raw_bytes).hexdigest() + if expected_fetch_sha256 is not None: + exp_hex = expected_fetch_sha256.strip().lower() + if not _SHA256_RE.match(exp_hex) or not hmac.compare_digest( + pdf_sha256, exp_hex + ): + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="REFUTED", + channel="confirmation_pdf", + reason="fetch_digest_mismatch", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + artifact_sha256=pdf_sha256, + provenance_evidence=prov_evidence, + ) pdf_text = extract_pdf_text_stdlib(raw_bytes) except (OSError, ValueError) as exc: return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="confirmation_pdf", reason=f"corrupt_or_unreadable_pdf: {exc}", checks=(), confirmed_count=0, refuted_count=0, abstained_count=len(expected_fields), + provenance_evidence=prov_evidence, ) if not pdf_text.strip(): return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="confirmation_pdf", reason="corrupt_or_unreadable_pdf: no extractable text streams", checks=(), @@ -458,35 +687,68 @@ def verify( refuted_count=0, abstained_count=len(expected_fields), artifact_sha256=pdf_sha256, + provenance_evidence=prov_evidence, ) labels_cfg = field_labels or {} patterns_cfg = field_patterns or {} + ftypes = field_types or {} observed: dict[str, Any] = {} provenance: dict[str, str] = {} + ambiguous_fields: list[str] = [] for fname in expected_fields: if fname in patterns_cfg: - m = re.search( - patterns_cfg[fname], pdf_text, re.IGNORECASE | re.MULTILINE + matches = list( + re.finditer( + patterns_cfg[fname], pdf_text, re.IGNORECASE | re.MULTILINE + ) ) - if m: - val = m.group(1).strip() if m.lastindex else m.group(0).strip() - observed[fname] = val - provenance[fname] = f"pdf:{pdf_sha256[:12]}:regex:{fname}" + if matches: + vals = [ + (m.group(1).strip() if m.lastindex else m.group(0).strip()) + for m in matches + ] + norms = { + normalize_field_value(v, field_type=ftypes.get(fname)) + for v in vals + } + if len(norms) > 1: + ambiguous_fields.append(fname) + provenance[fname] = ( + f"pdf:{pdf_sha256[:12]}:ambiguous_regex:{fname}" + ) + else: + observed[fname] = vals[0] + provenance[fname] = f"pdf:{pdf_sha256[:12]}:regex:{fname}" continue candidate_labels = labels_cfg.get(fname) or _default_labels_for_field(fname) + found_vals: list[str] = [] + matched_label: str | None = None for lbl in candidate_labels: pat = re.compile( rf"(?:^|\n)\s*{re.escape(lbl)}\s*[:\-]\s*([^\n]+)", re.IGNORECASE, ) - m = pat.search(pdf_text) - if m: - observed[fname] = m.group(1).strip() - provenance[fname] = f"pdf:{pdf_sha256[:12]}:label={lbl!r}" - break + hits = [m.group(1).strip() for m in pat.finditer(pdf_text)] + if hits: + found_vals.extend(hits) + if matched_label is None: + matched_label = lbl + if found_vals: + norms = { + normalize_field_value(v, field_type=ftypes.get(fname)) + for v in found_vals + } + if len(norms) > 1: + ambiguous_fields.append(fname) + provenance[fname] = ( + f"pdf:{pdf_sha256[:12]}:ambiguous_label={matched_label!r}" + ) + else: + observed[fname] = found_vals[0] + provenance[fname] = f"pdf:{pdf_sha256[:12]}:label={matched_label!r}" checks, confirmed, refuted, abstained = _compare_fields( expected_fields, @@ -496,9 +758,23 @@ def verify( default_provenance=f"pdf:{pdf_sha256[:12]}:missing", ) + if ambiguous_fields: + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + channel="confirmation_pdf", + reason=f"ambiguous_duplicate_label: {', '.join(ambiguous_fields)}", + checks=checks, + confirmed_count=confirmed, + refuted_count=refuted, + abstained_count=abstained, + artifact_sha256=pdf_sha256, + provenance_evidence=prov_evidence, + ) if refuted > 0: return PortalReadbackResult( verdict="HALT", + receipt_verdict="REFUTED", channel="confirmation_pdf", reason="field_mismatch", checks=checks, @@ -506,10 +782,12 @@ def verify( refuted_count=refuted, abstained_count=abstained, artifact_sha256=pdf_sha256, + provenance_evidence=prov_evidence, ) if abstained > 0: return PortalReadbackResult( verdict="HALT", + receipt_verdict="UNCERTAIN", channel="confirmation_pdf", reason="missing_required_fields", checks=checks, @@ -517,9 +795,11 @@ def verify( refuted_count=refuted, abstained_count=abstained, artifact_sha256=pdf_sha256, + provenance_evidence=prov_evidence, ) return PortalReadbackResult( verdict="VERIFIED", + receipt_verdict="CONFIRMED", channel="confirmation_pdf", reason="ok", checks=checks, @@ -527,4 +807,5 @@ def verify( refuted_count=0, abstained_count=0, artifact_sha256=pdf_sha256, + provenance_evidence=prov_evidence, ) diff --git a/packages/verify/tests/test_portal_readback.py b/packages/verify/tests/test_portal_readback.py index 53bdd3a157..c1c82ba23f 100644 --- a/packages/verify/tests/test_portal_readback.py +++ b/packages/verify/tests/test_portal_readback.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json import zlib from pathlib import Path @@ -14,6 +15,8 @@ normalize_field_value, ) +_SAMPLE_DOM_SHA = hashlib.sha256(b"summary").hexdigest() + def _escape_pdf_text(text: str) -> str: return text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)") @@ -24,9 +27,15 @@ def _make_synthetic_pdf( *, compress: bool = False, use_tj_array: bool = False, + invisible_lines: list[str] | None = None, ) -> bytes: """Build a minimal valid PDF containing text lines in Tj or TJ operators.""" ops: list[str] = ["BT", "/F1 12 Tf", "72 720 Td"] + if invisible_lines: + ops.append("3 Tr") + for line in invisible_lines: + ops.append(f"({_escape_pdf_text(line)}) Tj") + ops.append("0 Tr") for idx, line in enumerate(lines): if idx > 0: ops.append("0 -16 Td") @@ -60,21 +69,30 @@ def _make_synthetic_pdf( return b"".join(parts) +def _valid_reload_proof(**overrides: object) -> ReloadProof: + kwargs: dict[str, object] = { + "navigation_type": "reload", + "submit_url": "https://carrier.example/quote/submit", + "summary_url": "https://carrier.example/quote/Q-90412/summary", + "submit_dom_token": "dom-submit-111", + "summary_dom_token": "dom-summary-222", + "reloaded_at_utc": "2026-11-23T05:10:00Z", + "summary_dom_sha256": _SAMPLE_DOM_SHA, + "producer": "separate_session", + } + kwargs.update(overrides) + return ReloadProof(**kwargs) # type: ignore[arg-type] + + class TestFreshReloadSummaryOracle: def test_happy_path_verified_with_normalization(self) -> None: oracle = FreshReloadSummaryOracle() - proof = ReloadProof( - navigation_type="reload", - submit_url="https://carrier.example/quote/submit", - summary_url="https://carrier.example/quote/Q-90412/summary", - submit_dom_token="dom-submit-111", - summary_dom_token="dom-summary-222", - reloaded_at_utc="2026-11-23T05:10:00Z", - ) + proof = _valid_reload_proof() expected = { "insured_name": "Jordan Rivera", "effective_date": "2026-03-14", "deductible": 1000, + "coverage_limit": 2000, "prior_losses": 0, "bundled_auto": True, "quote_id": "MRN-88041", @@ -83,6 +101,7 @@ def test_happy_path_verified_with_normalization(self) -> None: "insured_name": " Jordan Rivera ", "effective_date": "03/14/2026", "deductible": "$1,000.00", + "coverage_limit": "2000", "prior_losses": "0", "bundled_auto": "Yes", "quote_id": "MRN-88041", @@ -91,149 +110,109 @@ def test_happy_path_verified_with_normalization(self) -> None: res = oracle.verify(expected, observed, proof) assert res.verdict == "VERIFIED" + assert res.receipt_verdict == "CONFIRMED" assert res.channel == "fresh_reload_summary" assert res.reason == "ok" - assert res.confirmed_count == 6 + assert res.confirmed_count == 7 assert res.refuted_count == 0 assert res.abstained_count == 0 + assert res.artifact_sha256 == _SAMPLE_DOM_SHA assert all(c.status == "CONFIRMED" for c in res.checks) - assert all("fresh_reload:reload:" in c.provenance for c in res.checks) - # Ensure JSON serializability payload = json.dumps(res.to_dict()) assert "VERIFIED" in payload + def test_untrusted_producer_and_missing_url_or_digest_halt(self) -> None: + oracle = FreshReloadSummaryOracle() + for bad_proof in ( + _valid_reload_proof(producer="unknown"), + _valid_reload_proof(producer="acting_session"), + _valid_reload_proof(submit_url="", summary_url=""), + _valid_reload_proof(summary_url="https://other-host.example/summary"), + _valid_reload_proof(reloaded_at_utc=""), + _valid_reload_proof(summary_dom_sha256="not-a-sha"), + ): + res = oracle.verify({"prior_losses": 0}, {"prior_losses": 0}, bad_proof) + assert res.verdict == "HALT" + assert res.receipt_verdict == "UNCERTAIN" + def test_stale_same_dom_halts_fail_closed(self) -> None: oracle = FreshReloadSummaryOracle() - stale_proof = ReloadProof( - navigation_type="same_dom", - submit_url="https://carrier.example/quote/submit", - summary_url="https://carrier.example/quote/submit", - submit_dom_token="dom-111", - summary_dom_token="dom-222", + res = oracle.verify( + {"prior_losses": 0}, + {"prior_losses": 0}, + _valid_reload_proof(navigation_type="same_dom"), ) - res = oracle.verify({"prior_losses": 0}, {"prior_losses": 0}, stale_proof) - assert res.verdict == "HALT" assert "stale_in_memory_dom_without_reload_proof" in res.reason - assert res.confirmed_count == 0 - assert res.abstained_count == 1 def test_identical_dom_tokens_halt_fail_closed(self) -> None: oracle = FreshReloadSummaryOracle() - same_token_proof = ReloadProof( - navigation_type="reload", - submit_url="https://carrier.example/quote/submit", - summary_url="https://carrier.example/quote/summary", - submit_dom_token="dom-same-token", - summary_dom_token="dom-same-token", + res = oracle.verify( + {"prior_losses": 0}, + {"prior_losses": 0}, + _valid_reload_proof( + submit_dom_token="dom-same", summary_dom_token="dom-same" + ), ) - res = oracle.verify({"prior_losses": 0}, {"prior_losses": 0}, same_token_proof) - assert res.verdict == "HALT" assert "summary_dom_token matches submit_dom_token" in res.reason - def test_missing_dom_tokens_halt_fail_closed(self) -> None: + def test_currency_mismatch_and_field_mismatch_halt(self) -> None: oracle = FreshReloadSummaryOracle() - missing_token_proof = ReloadProof( - navigation_type="fresh_navigation", - submit_url="https://carrier.example/quote/submit", - summary_url="https://carrier.example/quote/summary", - submit_dom_token="dom-submit-1", - summary_dom_token=" ", - ) - res = oracle.verify( - {"prior_losses": 0}, {"prior_losses": 0}, missing_token_proof - ) - - assert res.verdict == "HALT" - assert "missing submit/summary DOM tokens" in res.reason + proof = _valid_reload_proof(navigation_type="new_session") + # $500 vs €500 must NOT compare equal + res_cur = oracle.verify({"premium": "$500"}, {"premium": "€500"}, proof) + assert res_cur.verdict == "HALT" + assert res_cur.receipt_verdict == "REFUTED" + assert res_cur.refuted_count == 1 - def test_field_mismatch_halts_with_refuted_check(self) -> None: - oracle = FreshReloadSummaryOracle() - proof = ReloadProof( - navigation_type="new_session", - submit_url="https://carrier.example/quote/submit", - summary_url="https://carrier.example/quote/summary", - submit_dom_token="dom-a", - summary_dom_token="dom-b", - ) res = oracle.verify( {"prior_losses": 0, "deductible": 1000}, {"prior_losses": 2, "deductible": "$1,000.00"}, proof, ) - assert res.verdict == "HALT" + assert res.receipt_verdict == "REFUTED" assert res.reason == "field_mismatch" assert res.confirmed_count == 1 assert res.refuted_count == 1 - assert res.abstained_count == 0 - refuted = [c for c in res.checks if c.status == "REFUTED"] - assert len(refuted) == 1 - assert refuted[0].field == "prior_losses" - assert refuted[0].normalized_expected == "0" - assert refuted[0].normalized_observed == "2" def test_missing_required_field_abstains_and_halts(self) -> None: oracle = FreshReloadSummaryOracle() - proof = ReloadProof( - navigation_type="reload", - submit_url="https://carrier.example/quote/submit", - summary_url="https://carrier.example/quote/summary", - submit_dom_token="dom-a", - summary_dom_token="dom-b", - ) res = oracle.verify( {"prior_losses": 0, "roof_year": 2018}, {"prior_losses": 0}, - proof, + _valid_reload_proof(), ) - assert res.verdict == "HALT" + assert res.receipt_verdict == "UNCERTAIN" assert res.reason == "missing_required_fields" - assert res.confirmed_count == 1 - assert res.refuted_count == 0 assert res.abstained_count == 1 - abstained = [c for c in res.checks if c.status == "ABSTAIN"] - assert len(abstained) == 1 - assert abstained[0].field == "roof_year" def test_lookalike_identifier_is_not_blurred(self) -> None: oracle = FreshReloadSummaryOracle() - proof = ReloadProof( - navigation_type="reload", - submit_url="https://carrier.example/submit", - summary_url="https://carrier.example/summary", - submit_dom_token="dom-a", - summary_dom_token="dom-b", - ) res = oracle.verify( {"policy_ref": "MRN-88041"}, {"policy_ref": "MRN-88O41"}, - proof, + _valid_reload_proof(), ) - assert res.verdict == "HALT" - assert res.reason == "field_mismatch" - assert res.refuted_count == 1 + assert res.receipt_verdict == "REFUTED" def test_empty_expected_fields_halts(self) -> None: oracle = FreshReloadSummaryOracle() - proof = ReloadProof( - navigation_type="reload", - submit_url="https://carrier.example/submit", - summary_url="https://carrier.example/summary", - submit_dom_token="dom-a", - summary_dom_token="dom-b", - ) - res = oracle.verify({}, {"a": 1}, proof) + res = oracle.verify({}, {"a": 1}, _valid_reload_proof()) assert res.verdict == "HALT" assert res.reason == "empty_expected_fields" class TestConfirmationPdfOracle: - def test_uncompressed_quote_pdf_verified(self, tmp_path: Path) -> None: - pdf_path = tmp_path / "quote_confirmation.pdf" + def test_uncompressed_quote_pdf_verified_with_separate_session_producer( + self, tmp_path: Path + ) -> None: + store = tmp_path / "independent_store" + store.mkdir() + pdf_path = store / "quote_confirmation.pdf" pdf_bytes = _make_synthetic_pdf( [ "Carrier Quote Confirmation (Homeowners)", @@ -248,6 +227,7 @@ def test_uncompressed_quote_pdf_verified(self, tmp_path: Path) -> None: use_tj_array=True, ) pdf_path.write_bytes(pdf_bytes) + expected_sha = hashlib.sha256(pdf_bytes).hexdigest() oracle = ConfirmationPdfOracle() res = oracle.verify( @@ -260,32 +240,73 @@ def test_uncompressed_quote_pdf_verified(self, tmp_path: Path) -> None: "bundled_auto": True, "quote_number": "NW-2026-88041", }, + producer="separate_session", + expected_fetch_sha256=expected_sha, ) assert res.verdict == "VERIFIED" + assert res.receipt_verdict == "CONFIRMED" assert res.channel == "confirmation_pdf" - assert res.reason == "ok" assert res.confirmed_count == 6 - assert res.refuted_count == 0 - assert res.abstained_count == 0 - assert res.artifact_sha256 is not None and len(res.artifact_sha256) == 64 - assert all( - c.provenance.startswith(f"pdf:{res.artifact_sha256[:12]}:") - for c in res.checks + assert res.artifact_sha256 == expected_sha + assert res.provenance_evidence["producer"] == "separate_session" + + def test_unverified_or_acting_producer_cannot_issue_verified( + self, tmp_path: Path + ) -> None: + pdf_path = tmp_path / "quote.pdf" + pdf_path.write_bytes(_make_synthetic_pdf(["Insured Name: Jordan Rivera"])) + oracle = ConfirmationPdfOracle() + + # Default producer="unknown" -> HALT / UNCERTAIN + res_unknown = oracle.verify(pdf_path, {"insured_name": "Jordan Rivera"}) + assert res_unknown.verdict == "HALT" + assert res_unknown.receipt_verdict == "UNCERTAIN" + assert "unverified_producer_provenance" in res_unknown.reason + + # Explicit acting_session -> HALT / UNCERTAIN + res_acting = oracle.verify( + pdf_path, {"insured_name": "Jordan Rivera"}, producer="acting_session" ) + assert res_acting.verdict == "HALT" + + # Declared separate_session but inside acting_roots -> downgraded -> HALT + res_overlap = oracle.verify( + pdf_path, + {"insured_name": "Jordan Rivera"}, + producer="separate_session", + acting_roots=[tmp_path], + ) + assert res_overlap.verdict == "HALT" + assert "unverified_producer_provenance" in res_overlap.reason + + # Inside playwright-artifacts-* download dir -> refused -> HALT + pw_dir = tmp_path / "playwright-artifacts-xyz" + pw_dir.mkdir() + pw_pdf = pw_dir / "quote.pdf" + pw_pdf.write_bytes(_make_synthetic_pdf(["Insured Name: Jordan Rivera"])) + res_pw = oracle.verify( + pw_pdf, + {"insured_name": "Jordan Rivera"}, + producer="separate_session", + ) + assert res_pw.verdict == "HALT" def test_flatedecode_compressed_pdf_verified(self, tmp_path: Path) -> None: - pdf_path = tmp_path / "quote_compressed.pdf" - pdf_bytes = _make_synthetic_pdf( - [ - "Named Insured: Taylor Chen", - "Policy Effective: March 14, 2026", - "Annual Premium: $2,450.50", - "Prior Claims: 0", - ], - compress=True, + store = tmp_path / "store" + store.mkdir() + pdf_path = store / "quote_compressed.pdf" + pdf_path.write_bytes( + _make_synthetic_pdf( + [ + "Named Insured: Taylor Chen", + "Policy Effective: March 14, 2026", + "Annual Premium: $2,450.50", + "Prior Claims: 0", + ], + compress=True, + ) ) - pdf_path.write_bytes(pdf_bytes) oracle = ConfirmationPdfOracle() res = oracle.verify( @@ -296,6 +317,7 @@ def test_flatedecode_compressed_pdf_verified(self, tmp_path: Path) -> None: "annual_premium": "2450.50", "prior_losses": 0, }, + producer="system_of_record", field_labels={ "insured_name": ("Named Insured", "Insured Name"), "effective_date": ("Policy Effective", "Effective Date"), @@ -303,124 +325,117 @@ def test_flatedecode_compressed_pdf_verified(self, tmp_path: Path) -> None: }, field_types={"annual_premium": "currency"}, ) - assert res.verdict == "VERIFIED" + assert res.receipt_verdict == "CONFIRMED" assert res.confirmed_count == 4 - assert res.artifact_sha256 is not None - def test_pdf_field_mismatch_halts(self, tmp_path: Path) -> None: - pdf_path = tmp_path / "quote_mismatch.pdf" - pdf_path.write_bytes( + def test_duplicate_conflicting_labels_and_invisible_text_fail_closed( + self, tmp_path: Path + ) -> None: + store = tmp_path / "store" + store.mkdir() + oracle = ConfirmationPdfOracle() + + # Duplicate label with conflicting values (requested vs issued) -> HALT + dup_pdf = store / "dup.pdf" + dup_pdf.write_bytes(_make_synthetic_pdf(["Prior Losses: 0", "Prior Losses: 2"])) + res_dup = oracle.verify( + dup_pdf, {"prior_losses": 0}, producer="separate_session" + ) + assert res_dup.verdict == "HALT" + assert res_dup.receipt_verdict == "UNCERTAIN" + assert "ambiguous_duplicate_label" in res_dup.reason + + # Invisible text (3 Tr) must be ignored and cannot spoof VERIFIED + inv_pdf = store / "inv.pdf" + inv_pdf.write_bytes( _make_synthetic_pdf( - [ - "Insured Name: Jordan Rivera", - "Prior Losses: 2", - "Deductible: $1,000.00", - ], - compress=True, + ["Prior Losses: 2"], invisible_lines=["Prior Losses: 0"] ) ) - - oracle = ConfirmationPdfOracle() - res = oracle.verify( - pdf_path, - expected_fields={ - "insured_name": "Jordan Rivera", - "prior_losses": 0, - "deductible": 1000, - }, + res_inv = oracle.verify( + inv_pdf, {"prior_losses": 0}, producer="separate_session" ) + assert res_inv.verdict == "HALT" + assert res_inv.receipt_verdict == "REFUTED" - assert res.verdict == "HALT" - assert res.reason == "field_mismatch" - assert res.confirmed_count == 2 - assert res.refuted_count == 1 - refuted = [c for c in res.checks if c.status == "REFUTED"] - assert refuted[0].field == "prior_losses" - assert refuted[0].normalized_observed == "2" - - def test_pdf_missing_required_field_abstains_and_halts( + def test_incremental_update_corrupt_flate_and_fetch_digest_mismatch_halt( self, tmp_path: Path ) -> None: - pdf_path = tmp_path / "quote_partial.pdf" - pdf_path.write_bytes(_make_synthetic_pdf(["Insured Name: Jordan Rivera"])) - + store = tmp_path / "store" + store.mkdir() oracle = ConfirmationPdfOracle() - res = oracle.verify( - pdf_path, - expected_fields={ - "insured_name": "Jordan Rivera", - "roof_year": 2018, - }, - ) - assert res.verdict == "HALT" - assert res.reason == "missing_required_fields" - assert res.confirmed_count == 1 - assert res.abstained_count == 1 - - def test_missing_pdf_file_halts(self, tmp_path: Path) -> None: - oracle = ConfirmationPdfOracle() - res = oracle.verify(tmp_path / "does_not_exist.pdf", {"insured_name": "Jordan"}) - - assert res.verdict == "HALT" - assert res.reason.startswith("missing_pdf:") - assert res.abstained_count == 1 - - def test_corrupt_non_pdf_bytes_halt(self, tmp_path: Path) -> None: - bad_pdf = tmp_path / "corrupt.pdf" - bad_pdf.write_bytes(b"502 Bad Gateway") - - oracle = ConfirmationPdfOracle() - res = oracle.verify(bad_pdf, {"insured_name": "Jordan"}) - - assert res.verdict == "HALT" - assert "corrupt_or_unreadable_pdf" in res.reason - - def test_pdf_without_extractable_text_halts(self, tmp_path: Path) -> None: - image_only_pdf = tmp_path / "scanned_image_only.pdf" - image_only_pdf.write_bytes( - b"%PDF-1.4\n1 0 obj << /Length 4 >>\nstream\n\x00\x01\x02\x03\nendstream\nendobj\n%%EOF\n" + # Incremental update (multiple %%EOF) -> HALT + inc_pdf = store / "inc.pdf" + inc_pdf.write_bytes( + _make_synthetic_pdf(["Prior Losses: 0"]) + b"\n% incremental\n%%EOF\n" + ) + res_inc = oracle.verify( + inc_pdf, {"prior_losses": 0}, producer="separate_session" + ) + assert res_inc.verdict == "HALT" + assert "incremental PDF updates" in res_inc.reason + + # Corrupt /FlateDecode stream -> HALT (never silently skipped!) + bad_flate = store / "bad_flate.pdf" + bad_flate.write_bytes( + b"%PDF-1.4\n" + b"1 0 obj << /Length 20 >>\nstream\nBT (Prior Losses: 0) Tj ET\nendstream\nendobj\n" + b"2 0 obj << /Length 8 /Filter /FlateDecode >>\nstream\nnot-zlib\nendstream\nendobj\n" + b"%%EOF\n" + ) + res_flate = oracle.verify( + bad_flate, {"prior_losses": 0}, producer="separate_session" + ) + assert res_flate.verdict == "HALT" + assert "corrupt FlateDecode stream" in res_flate.reason + + # Fetch digest mismatch -> HALT / REFUTED + good_pdf = store / "good.pdf" + good_pdf.write_bytes(_make_synthetic_pdf(["Prior Losses: 0"])) + res_sha = oracle.verify( + good_pdf, + {"prior_losses": 0}, + producer="separate_session", + expected_fetch_sha256="0" * 64, ) + assert res_sha.verdict == "HALT" + assert res_sha.receipt_verdict == "REFUTED" + assert res_sha.reason == "fetch_digest_mismatch" + def test_missing_corrupt_and_textless_pdfs_halt(self, tmp_path: Path) -> None: + store = tmp_path / "store" + store.mkdir() oracle = ConfirmationPdfOracle() - res = oracle.verify(image_only_pdf, {"insured_name": "Jordan"}) - - assert res.verdict == "HALT" - assert "no extractable text streams" in res.reason - assert res.artifact_sha256 is not None - def test_custom_field_pattern_extraction(self, tmp_path: Path) -> None: - pdf_path = tmp_path / "regex_quote.pdf" - pdf_path.write_bytes( - _make_synthetic_pdf(["Confirmation #NW-99421 issued for $1,250.00"]) + res_missing = oracle.verify( + store / "nope.pdf", {"insured_name": "Jordan"}, producer="separate_session" ) + assert res_missing.verdict == "HALT" - oracle = ConfirmationPdfOracle() - res = oracle.verify( - pdf_path, - expected_fields={"quote_id": "NW-99421", "premium": 1250}, - field_patterns={ - "quote_id": r"Confirmation #([A-Z0-9-]+)", - "premium": r"issued for (\$[0-9,]+\.\d{2})", - }, + bad_pdf = store / "corrupt.pdf" + bad_pdf.write_bytes(b"502") + res_bad = oracle.verify( + bad_pdf, {"insured_name": "Jordan"}, producer="separate_session" ) + assert res_bad.verdict == "HALT" - assert res.verdict == "VERIFIED" - assert res.confirmed_count == 2 - assert all(":regex:" in c.provenance for c in res.checks) - - def test_empty_expected_fields_halts(self, tmp_path: Path) -> None: - pdf_path = tmp_path / "any.pdf" - pdf_path.write_bytes(_make_synthetic_pdf(["Insured Name: Jordan"])) - oracle = ConfirmationPdfOracle() - res = oracle.verify(pdf_path, {}) - assert res.verdict == "HALT" - assert res.reason == "empty_expected_fields" + img_pdf = store / "img.pdf" + img_pdf.write_bytes( + b"%PDF-1.4\n1 0 obj << /Length 4 >>\nstream\n\x00\x01\x02\x03\nendstream\nendobj\n%%EOF\n" + ) + res_img = oracle.verify( + img_pdf, {"insured_name": "Jordan"}, producer="separate_session" + ) + assert res_img.verdict == "HALT" + assert "no extractable text streams" in res_img.reason def test_normalize_and_extract_helpers() -> None: - assert normalize_field_value("$1,200.50") == "1200.50" + assert normalize_field_value("$1,200.50") == "USD:1200.50" + assert normalize_field_value("€500") == "EUR:500.00" + assert normalize_field_value(2000) == "2000" assert normalize_field_value("03/14/2026") == "2026-03-14" assert normalize_field_value("Yes") == "true" assert normalize_field_value("No") == "false" From 9293b4dd9d2df4ccedeebfafd177f7a477801924 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 10:03:37 -0500 Subject: [PATCH 4/7] fix(verify): prioritize REFUTED over ambiguous, compute ReloadProof digest from DOM bytes, handle 7 Tr and q/Q, reject one-sided currency, restore exact facade count --- .github/workflows/packages.yml | 2 +- .../src/openadapt_verify/portal_readback.py | 182 +++++++++++++----- packages/verify/tests/test_portal_readback.py | 99 +++++++++- 3 files changed, 232 insertions(+), 51 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 713ea6824b..77747215ab 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) == 120, f"all independent-store and portal-readback controls must run (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/portal_readback.py b/packages/verify/src/openadapt_verify/portal_readback.py index d81709dca2..99d76258e5 100644 --- a/packages/verify/src/openadapt_verify/portal_readback.py +++ b/packages/verify/src/openadapt_verify/portal_readback.py @@ -51,9 +51,9 @@ _SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$") _CURRENCY_SYMBOL_TO_CODE = { - "$": "USD", - "€": "EUR", - "£": "GBP", + "$": "$", + "€": "€", + "£": "£", } _CURRENCY_RE = re.compile( r"^\s*([$€£])?\s*([+-]?\d{1,3}(?:,\d{3})*(?:\.\d+)?|[+-]?\d+(?:\.\d+)?)\s*$" @@ -255,30 +255,48 @@ def normalize_field_value(value: Any, *, field_type: str | None = None) -> str: def _strip_currency_code(norm: str) -> tuple[str | None, str]: - m = re.match(r"^([A-Z]{3}):([+-]?\d+\.\d{2})$", norm) + m = re.match(r"^([$€£]|[A-Z]{3}):([+-]?\d+\.\d{2})$", norm) if m: return m.group(1), m.group(2) return None, norm -def _values_match(norm_exp: str, norm_obs: str) -> bool: +def _compare_normalized_values(norm_exp: str, norm_obs: str) -> FieldStatus: + """Compare normalized values, returning CONFIRMED, REFUTED, or ABSTAIN. + + - Two explicit currencies MUST match currency symbol/code (``$:500.00`` != ``€:500.00``). + - When the expected value explicitly names a currency (e.g. ``€:500.00``) and the + observed value is bare (``500.00``), return ``ABSTAIN`` rather than blurring currency. + - When only the observed value carries a currency symbol (e.g. expected bare ``1000`` + vs observed ``$:1000.00``), compare quantized numeric amounts. + """ if norm_exp == norm_obs: - return True + return "CONFIRMED" exp_code, exp_num = _strip_currency_code(norm_exp) obs_code, obs_num = _strip_currency_code(norm_obs) - # Two explicit currencies MUST match currency code (USD:500.00 != EUR:500.00). if exp_code is not None and obs_code is not None: - return exp_code == obs_code and exp_num == obs_num - # If only one side carried a currency symbol (e.g. expected int 1000 vs "$1,000.00"), - # compare quantized numeric amounts. - if (exp_code is not None) != (obs_code is not None): + return ( + "CONFIRMED" if (exp_code == obs_code and exp_num == obs_num) else "REFUTED" + ) + if exp_code is not None and obs_code is None: try: - return Decimal(exp_num).quantize(Decimal("0.01")) == Decimal( - obs_num - ).quantize(Decimal("0.01")) + if Decimal(exp_num).quantize(Decimal("0.01")) == Decimal(obs_num).quantize( + Decimal("0.01") + ): + return "ABSTAIN" except InvalidOperation: - return False - return False + pass + return "REFUTED" + if exp_code is None and obs_code is not None: + try: + if Decimal(exp_num).quantize(Decimal("0.01")) == Decimal(obs_num).quantize( + Decimal("0.01") + ): + return "CONFIRMED" + except InvalidOperation: + pass + return "REFUTED" + return "REFUTED" def _compare_fields( @@ -326,12 +344,13 @@ def _compare_fields( norm_exp = normalize_field_value(exp_val, field_type="currency") norm_obs = normalize_field_value(obs_val, field_type=effective_type) - if _values_match(norm_exp, norm_obs): + status = _compare_normalized_values(norm_exp, norm_obs) + if status == "CONFIRMED": confirmed += 1 - status: FieldStatus = "CONFIRMED" - else: + elif status == "REFUTED": refuted += 1 - status = "REFUTED" + else: + abstained += 1 checks.append( FieldCheck( field=fname, @@ -348,7 +367,7 @@ def _compare_fields( class FreshReloadSummaryOracle: - """Verify persisted portal summary fields after an independent fresh reload.""" + """Verify persisted portal summary fields against freshly reloaded DOM bytes.""" def verify( self, @@ -356,6 +375,7 @@ def verify( observed_summary_fields: Mapping[str, Any], reload_proof: ReloadProof, *, + summary_dom_bytes: bytes | None = None, field_types: Mapping[str, str] | None = None, ) -> PortalReadbackResult: if not expected_fields: @@ -383,20 +403,66 @@ def verify( abstained_count=len(expected_fields), ) + if ( + not isinstance(summary_dom_bytes, (bytes, bytearray)) + or not summary_dom_bytes + ): + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + channel="fresh_reload_summary", + reason="missing_summary_dom_bytes: oracle must compute digest over reloaded DOM bytes", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + ) + + computed_dom_sha = hashlib.sha256(bytes(summary_dom_bytes)).hexdigest() + claimed_dom_sha = reload_proof.summary_dom_sha256.strip().lower() + if not hmac.compare_digest(computed_dom_sha, claimed_dom_sha): + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="REFUTED", + channel="fresh_reload_summary", + reason="summary_dom_digest_mismatch", + checks=(), + confirmed_count=0, + refuted_count=0, + abstained_count=len(expected_fields), + artifact_sha256=computed_dom_sha, + ) + + dom_text = bytes(summary_dom_bytes).decode("utf-8", errors="replace") + dom_text_compact = " ".join(dom_text.split()) + verified_observed: dict[str, Any] = {} + missing_in_dom: dict[str, str] = {} + for fname in expected_fields: + val = observed_summary_fields.get(fname) + if val is None or (isinstance(val, str) and not val.strip()): + continue + compact_val = " ".join(str(val).strip().split()) + if compact_val in dom_text_compact: + verified_observed[fname] = val + else: + missing_in_dom[fname] = ( + "observed_value_not_present_in_summary_dom_bytes" + ) + parsed_producer = parse_producer(reload_proof.producer) - dom_sha = reload_proof.summary_dom_sha256.strip().lower() prov = f"fresh_reload:{parsed_producer.value}:{reload_proof.navigation_type}:{reload_proof.summary_url}" checks, confirmed, refuted, abstained = _compare_fields( expected_fields, - observed_summary_fields, + verified_observed, field_types=field_types, + provenance_map=missing_in_dom, default_provenance=prov, ) prov_evidence = { "producer": parsed_producer.value, "navigation_type": reload_proof.navigation_type, "reloaded_at_utc": reload_proof.reloaded_at_utc, - "summary_dom_sha256": dom_sha, + "summary_dom_sha256": computed_dom_sha, } if refuted > 0: @@ -409,20 +475,25 @@ def verify( confirmed_count=confirmed, refuted_count=refuted, abstained_count=abstained, - artifact_sha256=dom_sha, + artifact_sha256=computed_dom_sha, provenance_evidence=prov_evidence, ) if abstained > 0: + reason = ( + "observed_value_not_in_dom_bytes" + if missing_in_dom + else "missing_required_fields" + ) return PortalReadbackResult( verdict="HALT", receipt_verdict="UNCERTAIN", channel="fresh_reload_summary", - reason="missing_required_fields", + reason=reason, checks=checks, confirmed_count=confirmed, refuted_count=refuted, abstained_count=abstained, - artifact_sha256=dom_sha, + artifact_sha256=computed_dom_sha, provenance_evidence=prov_evidence, ) return PortalReadbackResult( @@ -434,7 +505,7 @@ def verify( confirmed_count=confirmed, refuted_count=0, abstained_count=0, - artifact_sha256=dom_sha, + artifact_sha256=computed_dom_sha, provenance_evidence=prov_evidence, ) @@ -479,15 +550,27 @@ def _unescape_pdf_literal(raw: str) -> str: def _extract_text_from_content_stream(stream_bytes: bytes) -> list[str]: - """Extract visible text runs from PDF Tj / TJ operators, skipping invisible (3 Tr) runs.""" + """Extract visible text runs from PDF Tj / TJ operators. + + Tracks ``q``/``Q`` graphics-state save/restore for text rendering mode + (``Tr``) and skips invisible text modes ``3 Tr`` (neither fill nor stroke) + and ``7 Tr`` (clip-only). + + Known limitation: the stdlib parser does not evaluate fill colour (e.g. + white-on-white), size-0 fonts, or off-page coordinates; ``ConfirmationPdfOracle`` + relies on the independent producer provenance gate to prevent untrusted + caller-authored PDFs from reaching ``VERIFIED``. + """ text = stream_bytes.decode("latin-1", errors="ignore") lines: list[str] = [] render_mode = 0 + state_stack: list[int] = [] - # Match rendering mode ` Tr`, single literal `(text) Tj`, and array `[(a) -20 (b)] TJ`. + # Match `q`/`Q`, ` Tr`, `(text) Tj`, and `[(a) -20 (b)] TJ`. # Alternatives inside the TJ array are strictly disjoint (no backtracking). token_re = re.compile( - r"\b([0-7])\s+Tr\b" + r"(? list[str]: for m in token_re.finditer(text): if m.group(1) is not None: - render_mode = int(m.group(1)) - continue - if render_mode == 3: - # PDF render mode 3 is invisible text (neither fill nor stroke). + if m.group(1) == "q": + state_stack.append(render_mode) + else: + render_mode = state_stack.pop() if state_stack else 0 continue if m.group(2) is not None: - val = _unescape_pdf_literal(m.group(2)).strip() + render_mode = int(m.group(2)) + continue + if render_mode in (3, 7): + # PDF render mode 3 (invisible) and 7 (clip-only) draw no visible glyphs. + continue + if m.group(3) is not None: + val = _unescape_pdf_literal(m.group(3)).strip() if val: lines.append(val) - elif m.group(3) is not None: + elif m.group(4) is not None: parts = [ _unescape_pdf_literal(lm.group(1)) - for lm in literal_re.finditer(m.group(3)) + for lm in literal_re.finditer(m.group(4)) ] joined = "".join(parts).strip() if joined: @@ -758,12 +847,17 @@ def verify( default_provenance=f"pdf:{pdf_sha256[:12]}:missing", ) - if ambiguous_fields: + if refuted > 0: + reason = ( + f"field_mismatch; ambiguous_duplicate_label: {', '.join(ambiguous_fields)}" + if ambiguous_fields + else "field_mismatch" + ) return PortalReadbackResult( verdict="HALT", - receipt_verdict="UNCERTAIN", + receipt_verdict="REFUTED", channel="confirmation_pdf", - reason=f"ambiguous_duplicate_label: {', '.join(ambiguous_fields)}", + reason=reason, checks=checks, confirmed_count=confirmed, refuted_count=refuted, @@ -771,12 +865,12 @@ def verify( artifact_sha256=pdf_sha256, provenance_evidence=prov_evidence, ) - if refuted > 0: + if ambiguous_fields: return PortalReadbackResult( verdict="HALT", - receipt_verdict="REFUTED", + receipt_verdict="UNCERTAIN", channel="confirmation_pdf", - reason="field_mismatch", + reason=f"ambiguous_duplicate_label: {', '.join(ambiguous_fields)}", checks=checks, confirmed_count=confirmed, refuted_count=refuted, diff --git a/packages/verify/tests/test_portal_readback.py b/packages/verify/tests/test_portal_readback.py index c1c82ba23f..9eef7d40bc 100644 --- a/packages/verify/tests/test_portal_readback.py +++ b/packages/verify/tests/test_portal_readback.py @@ -15,7 +15,12 @@ normalize_field_value, ) -_SAMPLE_DOM_SHA = hashlib.sha256(b"summary").hexdigest() +_SAMPLE_DOM_BYTES = ( + b"" + b"Jordan Rivera 03/14/2026 $1,000.00 2000 0 Yes MRN-88041 MRN-88O41 2 \xe2\x82\xac500 500.00" + b"" +) +_SAMPLE_DOM_SHA = hashlib.sha256(_SAMPLE_DOM_BYTES).hexdigest() def _escape_pdf_text(text: str) -> str: @@ -107,7 +112,9 @@ def test_happy_path_verified_with_normalization(self) -> None: "quote_id": "MRN-88041", } - res = oracle.verify(expected, observed, proof) + res = oracle.verify( + expected, observed, proof, summary_dom_bytes=_SAMPLE_DOM_BYTES + ) assert res.verdict == "VERIFIED" assert res.receipt_verdict == "CONFIRMED" @@ -121,6 +128,32 @@ def test_happy_path_verified_with_normalization(self) -> None: payload = json.dumps(res.to_dict()) assert "VERIFIED" in payload + # Missing summary_dom_bytes, fabricated digest, or value absent from DOM bytes -> HALT + res_no_dom = oracle.verify(expected, observed, proof) + assert res_no_dom.verdict == "HALT" + assert res_no_dom.receipt_verdict == "UNCERTAIN" + assert res_no_dom.artifact_sha256 is None + + res_fake_sha = oracle.verify( + {"prior_losses": 0}, + {"prior_losses": 0}, + _valid_reload_proof(summary_dom_sha256="0" * 64), + summary_dom_bytes=_SAMPLE_DOM_BYTES, + ) + assert res_fake_sha.verdict == "HALT" + assert res_fake_sha.receipt_verdict == "REFUTED" + assert res_fake_sha.reason == "summary_dom_digest_mismatch" + + res_not_in_dom = oracle.verify( + {"insured_name": "Phantom Name"}, + {"insured_name": "Phantom Name"}, + proof, + summary_dom_bytes=_SAMPLE_DOM_BYTES, + ) + assert res_not_in_dom.verdict == "HALT" + assert res_not_in_dom.receipt_verdict == "UNCERTAIN" + assert res_not_in_dom.reason == "observed_value_not_in_dom_bytes" + def test_untrusted_producer_and_missing_url_or_digest_halt(self) -> None: oracle = FreshReloadSummaryOracle() for bad_proof in ( @@ -161,15 +194,32 @@ def test_currency_mismatch_and_field_mismatch_halt(self) -> None: oracle = FreshReloadSummaryOracle() proof = _valid_reload_proof(navigation_type="new_session") # $500 vs €500 must NOT compare equal - res_cur = oracle.verify({"premium": "$500"}, {"premium": "€500"}, proof) + res_cur = oracle.verify( + {"premium": "$500"}, + {"premium": "€500"}, + proof, + summary_dom_bytes=_SAMPLE_DOM_BYTES, + ) assert res_cur.verdict == "HALT" assert res_cur.receipt_verdict == "REFUTED" assert res_cur.refuted_count == 1 + # One-sided currency: expected €500 vs bare 500.00 -> ABSTAIN (HALT / UNCERTAIN), never VERIFIED + res_one_sided = oracle.verify( + {"premium": "€500"}, + {"premium": "500.00"}, + proof, + summary_dom_bytes=_SAMPLE_DOM_BYTES, + ) + assert res_one_sided.verdict == "HALT" + assert res_one_sided.receipt_verdict == "UNCERTAIN" + assert res_one_sided.abstained_count == 1 + res = oracle.verify( {"prior_losses": 0, "deductible": 1000}, {"prior_losses": 2, "deductible": "$1,000.00"}, proof, + summary_dom_bytes=_SAMPLE_DOM_BYTES, ) assert res.verdict == "HALT" assert res.receipt_verdict == "REFUTED" @@ -183,6 +233,7 @@ def test_missing_required_field_abstains_and_halts(self) -> None: {"prior_losses": 0, "roof_year": 2018}, {"prior_losses": 0}, _valid_reload_proof(), + summary_dom_bytes=_SAMPLE_DOM_BYTES, ) assert res.verdict == "HALT" assert res.receipt_verdict == "UNCERTAIN" @@ -195,6 +246,7 @@ def test_lookalike_identifier_is_not_blurred(self) -> None: {"policy_ref": "MRN-88041"}, {"policy_ref": "MRN-88O41"}, _valid_reload_proof(), + summary_dom_bytes=_SAMPLE_DOM_BYTES, ) assert res.verdict == "HALT" assert res.receipt_verdict == "REFUTED" @@ -346,7 +398,22 @@ def test_duplicate_conflicting_labels_and_invisible_text_fail_closed( assert res_dup.receipt_verdict == "UNCERTAIN" assert "ambiguous_duplicate_label" in res_dup.reason - # Invisible text (3 Tr) must be ignored and cannot spoof VERIFIED + # Refuted + ambiguous MUST report receipt_verdict="REFUTED", never downgrade to UNCERTAIN + ref_amb_pdf = store / "ref_amb.pdf" + ref_amb_pdf.write_bytes( + _make_synthetic_pdf(["Premium: $600", "Policy: P1", "Policy: P2"]) + ) + res_ref_amb = oracle.verify( + ref_amb_pdf, + {"premium": "$500", "policy": "P1"}, + producer="separate_session", + ) + assert res_ref_amb.verdict == "HALT" + assert res_ref_amb.receipt_verdict == "REFUTED" + assert res_ref_amb.refuted_count == 1 + assert "ambiguous_duplicate_label" in res_ref_amb.reason + + # Invisible text (3 Tr and 7 Tr) must be ignored; q/Q restores visible mode after 3 Tr inv_pdf = store / "inv.pdf" inv_pdf.write_bytes( _make_synthetic_pdf( @@ -359,6 +426,26 @@ def test_duplicate_conflicting_labels_and_invisible_text_fail_closed( assert res_inv.verdict == "HALT" assert res_inv.receipt_verdict == "REFUTED" + clip_only_pdf = store / "clip7.pdf" + clip_only_pdf.write_bytes( + b"%PDF-1.4\n1 0 obj << /Length 36 >>\nstream\nBT 7 Tr (Premium: $500) Tj ET\nendstream\nendobj\n%%EOF\n" + ) + res_clip = oracle.verify( + clip_only_pdf, {"premium": "$500"}, producer="separate_session" + ) + assert res_clip.verdict == "HALT" + assert "no extractable text streams" in res_clip.reason + + qq_pdf = store / "qq.pdf" + qq_pdf.write_bytes( + b"%PDF-1.4\n1 0 obj << /Length 64 >>\nstream\n" + b"BT q 3 Tr (Premium: $999) Tj Q (Premium: $500) Tj ET\n" + b"endstream\nendobj\n%%EOF\n" + ) + res_qq = oracle.verify(qq_pdf, {"premium": "$500"}, producer="separate_session") + assert res_qq.verdict == "VERIFIED" + assert res_qq.receipt_verdict == "CONFIRMED" + def test_incremental_update_corrupt_flate_and_fetch_digest_mismatch_halt( self, tmp_path: Path ) -> None: @@ -433,8 +520,8 @@ def test_missing_corrupt_and_textless_pdfs_halt(self, tmp_path: Path) -> None: def test_normalize_and_extract_helpers() -> None: - assert normalize_field_value("$1,200.50") == "USD:1200.50" - assert normalize_field_value("€500") == "EUR:500.00" + assert normalize_field_value("$1,200.50") == "$:1200.50" + assert normalize_field_value("€500") == "€:500.00" assert normalize_field_value(2000) == "2000" assert normalize_field_value("03/14/2026") == "2026-03-14" assert normalize_field_value("Yes") == "true" From a642bf36c7e604e684f2d4fe97c2fb409ec07aa6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 20:05:37 -0500 Subject: [PATCH 5/7] fix(verify): bind FreshReloadSummaryOracle to visible labeled DOM nodes and exclude /Q PDF names --- .github/workflows/packages.yml | 2 +- .../src/openadapt_verify/portal_readback.py | 83 ++++++++++++++++++- packages/verify/tests/test_portal_readback.py | 80 +++++++++++++++++- 3 files changed, 157 insertions(+), 8 deletions(-) diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 1ed879594f..1ee477d86c 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -457,7 +457,7 @@ jobs: python - <<'PY' import xml.etree.ElementTree as ET cases = ET.parse("tests.xml").getroot().findall(".//testcase") - assert len(cases) == 120, f"all independent-store and portal-readback controls must run (got {len(cases)})" + assert len(cases) == 124, f"all independent-store and portal-readback controls must run (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/portal_readback.py b/packages/verify/src/openadapt_verify/portal_readback.py index 99d76258e5..0c8d545ff2 100644 --- a/packages/verify/src/openadapt_verify/portal_readback.py +++ b/packages/verify/src/openadapt_verify/portal_readback.py @@ -32,6 +32,7 @@ from collections.abc import Mapping, Sequence from dataclasses import asdict, dataclass, field from decimal import Decimal, InvalidOperation +from html.parser import HTMLParser from pathlib import Path from typing import Any, Literal from urllib.parse import urlsplit @@ -366,6 +367,77 @@ def _compare_fields( return tuple(checks), confirmed, refuted, abstained +class _VisibleTextExtractor(HTMLParser): + """Extract ordered visible text nodes from HTML, ignoring attributes and non-rendered elements.""" + + _SKIP_TAGS = frozenset({"script", "style", "noscript", "template", "head", "title"}) + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self._skip_depth = 0 + self.nodes: list[str] = [] + + def handle_starttag( + self, tag: str, attrs: list[tuple[str, str | None]] + ) -> None: + del attrs + if tag.lower() in self._SKIP_TAGS: + self._skip_depth += 1 + + def handle_endtag(self, tag: str) -> None: + if tag.lower() in self._SKIP_TAGS and self._skip_depth > 0: + self._skip_depth -= 1 + + def handle_data(self, data: str) -> None: + if self._skip_depth > 0: + return + compact = " ".join(data.split()) + if compact: + self.nodes.append(compact) + + +def _normalize_dom_label(text: str) -> str: + cleaned = re.sub(r"[^a-z0-9]+", " ", text.strip().lower()).strip() + return cleaned + + +def _dom_value_matches_bound_label( + nodes: Sequence[str], field_name: str, expected_val: str +) -> bool: + """Return True iff ``expected_val`` appears in visible DOM text bound to ``field_name`` + on token boundaries (never in HTML attributes, scripts, substrings of larger numbers, + or under a different field's label).""" + target_label = _normalize_dom_label(field_name) + if not target_label or not expected_val: + return False + val_re = re.compile( + r"(? " where label words match the start of the node. + label_words = target_label.split() + prefix_re = re.compile( + r"^\s*" + r"[\s_-]+".join(re.escape(w) for w in label_words) + r"\s+(.+)$", + re.IGNORECASE, + ) + m = prefix_re.match(node) + if m and val_re.search(m.group(1).strip()): + return True + return False + + class FreshReloadSummaryOracle: """Verify persisted portal summary fields against freshly reloaded DOM bytes.""" @@ -434,7 +506,10 @@ def verify( ) dom_text = bytes(summary_dom_bytes).decode("utf-8", errors="replace") - dom_text_compact = " ".join(dom_text.split()) + extractor = _VisibleTextExtractor() + extractor.feed(dom_text) + extractor.close() + dom_nodes = extractor.nodes verified_observed: dict[str, Any] = {} missing_in_dom: dict[str, str] = {} for fname in expected_fields: @@ -442,11 +517,11 @@ def verify( if val is None or (isinstance(val, str) and not val.strip()): continue compact_val = " ".join(str(val).strip().split()) - if compact_val in dom_text_compact: + if _dom_value_matches_bound_label(dom_nodes, fname, compact_val): verified_observed[fname] = val else: missing_in_dom[fname] = ( - "observed_value_not_present_in_summary_dom_bytes" + "observed_value_not_bound_to_label_in_summary_dom_bytes" ) parsed_producer = parse_producer(reload_proof.producer) @@ -569,7 +644,7 @@ def _extract_text_from_content_stream(stream_bytes: bytes) -> list[str]: # Match `q`/`Q`, ` Tr`, `(text) Tj`, and `[(a) -20 (b)] TJ`. # Alternatives inside the TJ array are strictly disjoint (no backtracking). token_re = re.compile( - r"(?" - b"Jordan Rivera 03/14/2026 $1,000.00 2000 0 Yes MRN-88041 MRN-88O41 2 \xe2\x82\xac500 500.00" - b"" + b"
" + b"
Insured Name
Jordan Rivera
" + b"
Effective Date
03/14/2026
" + b"
Deductible
$1,000.00
" + b"
Coverage Limit
2000
" + b"
Prior Losses
0
" + b"
Prior Losses
2
" + b"
Bundled Auto
Yes
" + b"
Quote ID
MRN-88041
" + b"
Policy Ref
MRN-88O41
" + b"
Premium
\xe2\x82\xac500
" + b"
Premium
500.00
" + b"
" ) _SAMPLE_DOM_SHA = hashlib.sha256(_SAMPLE_DOM_BYTES).hexdigest() @@ -529,3 +539,67 @@ def test_normalize_and_extract_helpers() -> None: pdf_bytes = _make_synthetic_pdf(["Line (1): OK"], compress=False) assert "Line (1): OK" in extract_pdf_text_stdlib(pdf_bytes) + + +def test_fresh_reload_rejects_value_substring_of_larger_amount() -> None: + """Probe R5: $500 must not match inside $5000.""" + dom = b"
Premium
$5000
" + proof = _valid_reload_proof(summary_dom_sha256=hashlib.sha256(dom).hexdigest()) + res = FreshReloadSummaryOracle().verify( + {"premium": "$500"}, {"premium": "$500"}, proof, summary_dom_bytes=dom + ) + assert res.verdict == "HALT" + assert res.receipt_verdict != "CONFIRMED" + + +def test_fresh_reload_rejects_value_under_wrong_label() -> None: + """Probe R3: Deductible $500 must not satisfy Premium $500.""" + dom = ( + b"
" + b"
Premium
$600
" + b"
Deductible
$500
" + b"
" + ) + proof = _valid_reload_proof(summary_dom_sha256=hashlib.sha256(dom).hexdigest()) + res = FreshReloadSummaryOracle().verify( + {"premium": "$500"}, {"premium": "$500"}, proof, summary_dom_bytes=dom + ) + assert res.verdict == "HALT" + assert res.receipt_verdict != "CONFIRMED" + + +def test_fresh_reload_rejects_value_only_in_hidden_input_attribute() -> None: + """Probe R4: values only in HTML attributes (hidden inputs) must not verify.""" + dom = ( + b'' + b"

Session expired. Nothing was saved.

" + ) + proof = _valid_reload_proof(summary_dom_sha256=hashlib.sha256(dom).hexdigest()) + res = FreshReloadSummaryOracle().verify( + {"premium": "$500"}, {"premium": "$500"}, proof, summary_dom_bytes=dom + ) + assert res.verdict == "HALT" + assert res.receipt_verdict != "CONFIRMED" + + +def test_pdf_font_name_slash_q_does_not_reset_invisible_render_mode( + tmp_path: Path, +) -> None: + """P3: a PDF resource name like /Q must not pop graphics state and unhide 3 Tr text.""" + store = tmp_path / "store" + store.mkdir() + stream = b"BT 3 Tr /Q 1 Tf (Premium: $500) Tj ET" + pdf_bytes = ( + b"%PDF-1.4\n1 0 obj << /Length " + + str(len(stream)).encode() + + b" >>\nstream\n" + + stream + + b"\nendstream\nendobj\n%%EOF\n" + ) + pdf_path = store / "hidden_font_q.pdf" + pdf_path.write_bytes(pdf_bytes) + res = ConfirmationPdfOracle().verify( + pdf_path, {"premium": "$500"}, producer="separate_session" + ) + assert res.verdict == "HALT" + assert res.receipt_verdict != "CONFIRMED" From f0ac919d8c2fb57715a0ad324cceaf6a5009e74c Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 01:55:46 -0500 Subject: [PATCH 6/7] style(verify): format portal_readback.py with ruff --- packages/verify/src/openadapt_verify/portal_readback.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/verify/src/openadapt_verify/portal_readback.py b/packages/verify/src/openadapt_verify/portal_readback.py index 0c8d545ff2..ac4f33ce3f 100644 --- a/packages/verify/src/openadapt_verify/portal_readback.py +++ b/packages/verify/src/openadapt_verify/portal_readback.py @@ -377,9 +377,7 @@ def __init__(self) -> None: self._skip_depth = 0 self.nodes: list[str] = [] - def handle_starttag( - self, tag: str, attrs: list[tuple[str, str | None]] - ) -> None: + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: del attrs if tag.lower() in self._SKIP_TAGS: self._skip_depth += 1 @@ -429,7 +427,9 @@ def _dom_value_matches_bound_label( # Check prefix "