diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 66db6cec59..524e72ab6c 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -475,7 +475,7 @@ jobs: python - <<'PY' import xml.etree.ElementTree as ET cases = ET.parse("tests.xml").getroot().findall(".//testcase") - assert len(cases) == 110, f"expected 110 independent-store + surgical-heal controls, got {len(cases)}" + assert len(cases) == 131, f"expected 131 independent-store, surgical-heal, and portal-readback controls, got {len(cases)}" # The PostgreSQL and MySQL quickstart controls need the database # services of verify-clean-install, which runs them; nothing else skips. skipped = {c.get("name") for c in cases if c.find("skipped") is not None} diff --git a/packages/verify/src/openadapt_verify/__init__.py b/packages/verify/src/openadapt_verify/__init__.py index f718907963..f4fa0f5ad9 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.1" __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..ec4a33bb0c --- /dev/null +++ b/packages/verify/src/openadapt_verify/portal_readback.py @@ -0,0 +1,1014 @@ +"""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 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``: + 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 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 + +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 = { + "$": "$", + "€": "€", + "£": "£", +} +_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"}) + + +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 in an independent session.""" + + navigation_type: str + submit_url: str + summary_url: str + 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, + "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 + receipt_verdict: ReceiptVerdict = "UNCERTAIN" + provenance_evidence: dict[str, Any] = field(default_factory=dict) + + 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 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): + dec = Decimal(str(value)) + return ( + f"{dec.quantize(Decimal('0.01'))}" + if field_type == "currency" + else _format_decimal_plain(dec) + ) + + 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).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 _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 _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 "CONFIRMED" + exp_code, exp_num = _strip_currency_code(norm_exp) + obs_code, obs_num = _strip_currency_code(norm_obs) + if exp_code is not None and 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: + if Decimal(exp_num).quantize(Decimal("0.01")) == Decimal(obs_num).quantize( + Decimal("0.01") + ): + return "ABSTAIN" + except InvalidOperation: + 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( + 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 + + 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) + status = _compare_normalized_values(norm_exp, norm_obs) + if status == "CONFIRMED": + confirmed += 1 + elif status == "REFUTED": + refuted += 1 + else: + abstained += 1 + 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 _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_bound_values_for_label(nodes: Sequence[str], field_name: str) -> list[str]: + """Collect every visible DOM text value bound to ``field_name``.""" + target_label = _normalize_dom_label(field_name) + if not target_label: + return [] + 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, + ) + bound_values: list[str] = [] + for idx, node in enumerate(nodes): + # Case 1: Node is the exact label (with optional trailing colon), value is the next node. + if _normalize_dom_label(node.rstrip(":")) == target_label: + if idx + 1 < len(nodes): + bound_values.append(nodes[idx + 1].strip()) + continue + # Case 2: Same text node "Label: value" or "Label value". + if ":" in node: + left, right = node.split(":", 1) + if _normalize_dom_label(left) == target_label: + bound_values.append(right.strip()) + else: + m = prefix_re.match(node) + if m: + bound_values.append(m.group(1).strip()) + return bound_values + + +def _dom_label_binding_status( + nodes: Sequence[str], field_name: str, expected_val: str +) -> str: + """Classify visible DOM bindings for ``field_name`` against ``expected_val``. + + Returns: + - ``"matched"`` iff at least one visible binding matches ``expected_val`` on + token boundaries and no duplicate binding for the same label conflicts. + - ``"conflict"`` iff the same label appears multiple times with conflicting values. + - ``"missing"`` otherwise. + """ + if not expected_val: + return "missing" + bound_values = _dom_bound_values_for_label(nodes, field_name) + if not bound_values: + return "missing" + val_re = re.compile( + r"(? bool: + """Return True iff ``expected_val`` appears in visible DOM text bound to ``field_name`` + on token boundaries with no conflicting duplicate label values.""" + return _dom_label_binding_status(nodes, field_name, expected_val) == "matched" + + +class FreshReloadSummaryOracle: + """Verify persisted portal summary fields against freshly reloaded DOM bytes.""" + + def verify( + self, + expected_fields: Mapping[str, Any], + 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: + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + 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", + receipt_verdict="UNCERTAIN", + channel="fresh_reload_summary", + reason=reload_reason, + checks=(), + confirmed_count=0, + refuted_count=0, + 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") + 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: + 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()) + binding_status = _dom_label_binding_status(dom_nodes, fname, compact_val) + if binding_status == "matched": + verified_observed[fname] = val + elif binding_status == "conflict": + missing_in_dom[fname] = ( + "conflicting_duplicate_label_values_in_summary_dom_bytes" + ) + else: + missing_in_dom[fname] = ( + "observed_value_not_bound_to_label_in_summary_dom_bytes" + ) + + parsed_producer = parse_producer(reload_proof.producer) + prov = f"fresh_reload:{parsed_producer.value}:{reload_proof.navigation_type}:{reload_proof.summary_url}" + checks, confirmed, refuted, abstained = _compare_fields( + expected_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": computed_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=computed_dom_sha, + provenance_evidence=prov_evidence, + ) + if abstained > 0: + if any( + v == "conflicting_duplicate_label_values_in_summary_dom_bytes" + for v in missing_in_dom.values() + ): + reason = "conflicting_duplicate_label_values_in_dom_bytes" + elif missing_in_dom: + reason = "observed_value_not_in_dom_bytes" + else: + reason = "missing_required_fields" + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + channel="fresh_reload_summary", + reason=reason, + checks=checks, + confirmed_count=confirmed, + refuted_count=refuted, + abstained_count=abstained, + artifact_sha256=computed_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=computed_dom_sha, + provenance_evidence=prov_evidence, + ) + + +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 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 `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"(? str: + """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) + prefix = pdf_bytes[max(0, m.start() - 256) : m.start()] + if b"/FlateDecode" in prefix: + try: + decoded = zlib.decompress(raw_stream) + 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)) + + 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 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, + ) -> PortalReadbackResult: + if not expected_fields: + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + 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", + receipt_verdict="UNCERTAIN", + channel="confirmation_pdf", + reason=f"missing_pdf: {p}", + checks=(), + confirmed_count=0, + refuted_count=0, + 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=(), + confirmed_count=0, + 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: + matches = list( + re.finditer( + patterns_cfg[fname], pdf_text, re.IGNORECASE | re.MULTILINE + ) + ) + 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, + ) + 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, + observed, + field_types=field_types, + provenance_map=provenance, + default_provenance=f"pdf:{pdf_sha256[:12]}:missing", + ) + + 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="REFUTED", + channel="confirmation_pdf", + reason=reason, + checks=checks, + confirmed_count=confirmed, + refuted_count=refuted, + abstained_count=abstained, + artifact_sha256=pdf_sha256, + provenance_evidence=prov_evidence, + ) + 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 abstained > 0: + return PortalReadbackResult( + verdict="HALT", + receipt_verdict="UNCERTAIN", + channel="confirmation_pdf", + reason="missing_required_fields", + checks=checks, + confirmed_count=confirmed, + 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, + confirmed_count=confirmed, + 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 new file mode 100644 index 0000000000..85489836fe --- /dev/null +++ b/packages/verify/tests/test_portal_readback.py @@ -0,0 +1,651 @@ +"""Tests for third-party portal independent read-back oracles (no DB/API access).""" + +from __future__ import annotations + +import hashlib +import json +import zlib +from pathlib import Path + +from openadapt_verify.portal_readback import ( + ConfirmationPdfOracle, + FreshReloadSummaryOracle, + ReloadProof, + extract_pdf_text_stdlib, + normalize_field_value, +) + +_SAMPLE_DOM_BYTES = ( + 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"
Bundled Auto
Yes
" + b"
Quote ID
MRN-88041
" + b"
Policy Ref
MRN-88O41
" + b"
Premium
\xe2\x82\xac500
" + b"
" +) +_SAMPLE_DOM_SHA = hashlib.sha256(_SAMPLE_DOM_BYTES).hexdigest() + + +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, + 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") + 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) + + +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 = _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", + } + observed = { + "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", + } + + res = oracle.verify( + expected, observed, proof, summary_dom_bytes=_SAMPLE_DOM_BYTES + ) + + assert res.verdict == "VERIFIED" + assert res.receipt_verdict == "CONFIRMED" + assert res.channel == "fresh_reload_summary" + assert res.reason == "ok" + 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) + 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 ( + _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() + res = oracle.verify( + {"prior_losses": 0}, + {"prior_losses": 0}, + _valid_reload_proof(navigation_type="same_dom"), + ) + assert res.verdict == "HALT" + assert "stale_in_memory_dom_without_reload_proof" in res.reason + + def test_identical_dom_tokens_halt_fail_closed(self) -> None: + oracle = FreshReloadSummaryOracle() + res = oracle.verify( + {"prior_losses": 0}, + {"prior_losses": 0}, + _valid_reload_proof( + submit_dom_token="dom-same", summary_dom_token="dom-same" + ), + ) + assert res.verdict == "HALT" + assert "summary_dom_token matches submit_dom_token" in res.reason + + 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, + 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 + dom_bare = b"
Premium
500.00
" + proof_bare = _valid_reload_proof( + navigation_type="new_session", + summary_dom_sha256=hashlib.sha256(dom_bare).hexdigest(), + ) + res_one_sided = oracle.verify( + {"premium": "€500"}, + {"premium": "500.00"}, + proof_bare, + summary_dom_bytes=dom_bare, + ) + assert res_one_sided.verdict == "HALT" + assert res_one_sided.receipt_verdict == "UNCERTAIN" + assert res_one_sided.abstained_count == 1 + + dom_losses = ( + b"
" + b"
Prior Losses
2
" + b"
Deductible
$1,000.00
" + b"
" + ) + proof_losses = _valid_reload_proof( + navigation_type="new_session", + summary_dom_sha256=hashlib.sha256(dom_losses).hexdigest(), + ) + res = oracle.verify( + {"prior_losses": 0, "deductible": 1000}, + {"prior_losses": 2, "deductible": "$1,000.00"}, + proof_losses, + summary_dom_bytes=dom_losses, + ) + assert res.verdict == "HALT" + assert res.receipt_verdict == "REFUTED" + assert res.reason == "field_mismatch" + assert res.confirmed_count == 1 + assert res.refuted_count == 1 + + def test_missing_required_field_abstains_and_halts(self) -> None: + oracle = FreshReloadSummaryOracle() + res = oracle.verify( + {"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" + assert res.reason == "missing_required_fields" + assert res.abstained_count == 1 + + def test_lookalike_identifier_is_not_blurred(self) -> None: + oracle = FreshReloadSummaryOracle() + res = oracle.verify( + {"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" + + def test_empty_expected_fields_halts(self) -> None: + oracle = FreshReloadSummaryOracle() + 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_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)", + "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) + expected_sha = hashlib.sha256(pdf_bytes).hexdigest() + + 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", + }, + producer="separate_session", + expected_fetch_sha256=expected_sha, + ) + + assert res.verdict == "VERIFIED" + assert res.receipt_verdict == "CONFIRMED" + assert res.channel == "confirmation_pdf" + assert res.confirmed_count == 6 + 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: + 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, + ) + ) + + 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, + }, + producer="system_of_record", + 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.receipt_verdict == "CONFIRMED" + assert res.confirmed_count == 4 + + 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 + + # 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( + ["Prior Losses: 2"], invisible_lines=["Prior Losses: 0"] + ) + ) + res_inv = oracle.verify( + inv_pdf, {"prior_losses": 0}, producer="separate_session" + ) + 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: + store = tmp_path / "store" + store.mkdir() + oracle = ConfirmationPdfOracle() + + # 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_missing = oracle.verify( + store / "nope.pdf", {"insured_name": "Jordan"}, producer="separate_session" + ) + assert res_missing.verdict == "HALT" + + 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" + + 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("€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" + 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) + + +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" + + +def test_fresh_reload_rejects_conflicting_duplicate_label_values() -> None: + """Duplicate labels with conflicting values (e.g. $500 vs $250) must refuse.""" + dom = b"
Premium: $500
Premium: $250
" + 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 == "UNCERTAIN" + assert "conflicting_duplicate_label" in res.reason + + +def test_pdf_float_render_mode_3_0_tr_stays_invisible(tmp_path: Path) -> None: + """Float render mode `3.0 Tr` must set mode 3 (invisible), never matching `0 Tr`.""" + store = tmp_path / "store" + store.mkdir() + stream = b"BT 3.0 Tr (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_float_tr.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"