diff --git a/openadapt/receipt_verify.py b/openadapt/receipt_verify.py index a97d9cc265..1c2c52d725 100644 --- a/openadapt/receipt_verify.py +++ b/openadapt/receipt_verify.py @@ -41,6 +41,12 @@ def _registry(keys: Optional[Path]) -> list[Any]: def _describe(result: Any, say: Say, indent: str = " ") -> None: for line in result.signer_lines: say(f"{indent}{line}") + if result.ok: + # Separate lines: they never merge with or upgrade the signer line. + for line in getattr(result, "confirmation_lines", ()): + say(f"{indent}{line}") + if getattr(result, "approval_line", ""): + say(f"{indent}{result.approval_line}") if not result.ok: if result.detail: say(f"{indent}({result.detail})") diff --git a/packages/flow/docs/RECEIPTS.md b/packages/flow/docs/RECEIPTS.md index 69a498094b..1119dec2d7 100644 --- a/packages/flow/docs/RECEIPTS.md +++ b/packages/flow/docs/RECEIPTS.md @@ -36,6 +36,29 @@ URLs or page text.** Evidence files, screenshots included, appear only by SHA-256 digest. A verifier refuses a receipt or card that carries an image, a base64 blob, a URL or long text (`embedded_content`). +A receipt may also carry **counterparty confirmations**: evidence read from +another party's system about a handoff, such as a referral a portal later +shows as recorded. Each confirmation states the kind of system, how it was +read (a portal read-back, an API, or an acknowledgment message), its state +(`sent`, `acknowledged`, `recorded_as_intended` or `recorded_differently`) and +its own strength. Who the other party is, when it was observed, which fields +it showed and any reason are salted commitments, never shown on a public card. +The verifier prints each one on its own line, for example "Confirmed in the +other party's system at 2026-11-20T23:41:07Z". That line never merges with or +upgrades the signer line: "Signed by this computer" still means only that this +computer signed the statement. + +A receipt handed to another party can also be **bound to the bytes it hands +over**: a `payload` subject names the SHA-256 and media type of the MCP tool +result, HTTP body or file. The receiver checks the bytes it got against it. +And it says **how its writes were approved**, from Flow's item approval +binding ([APPROVAL_AND_VERIFICATION.md](APPROVAL_AND_VERIFICATION.md)): the +approval mode (`each_item`, `problems_only` or `not_gated`) and the kind of +approver (a person or an agent delegate) are visible; who approved, the +scope and the time are commitments. A receipt with no approval block says +"No approval recorded", so a receipt never implies authority it doesn't +record. + ## Who signed it Each signature names a key id. The verifier's pinned key registry maps that diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index e431f764e9..fd889594fa 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -101,6 +101,53 @@ def _line(index: int, result: Mapping[str, Any]) -> dict[str, Any]: } +def _approval( + report: Mapping[str, Any], +) -> tuple[Optional[dict[str, Any]], dict[str, Optional[str]]]: + """``predicate.approval`` from the report's item-approval block, and its values. + + The source is Flow's approval binding (``report.approval``, + ``openadapt.approval-mode-item/v1``): its mode, and each approved + ``ItemApprovalRef``. The approver's id is committed, never shown. + """ + block = report.get("approval") + if not isinstance(block, Mapping): + return None, {} + mode = block.get("mode") + if mode not in ("each_item", "problems_only", "not_gated"): + return None, {} + approved = [ + a + for a in block.get("approvals") or [] + if isinstance(a, Mapping) and a.get("decision") == "approved" + ] + # The item's final decision decides: earlier "approved" answers never + # make a declined, waiting or unanswered item read as approved. + if mode == "not_gated" or block.get("decision") != "approved" or not approved: + return {"mode": mode, "approver_kind": "none", "commitments": {}}, {} + # The weakest approver counts: one delegate's answer among people's makes + # the whole run "approved by an agent delegate", never "by a person". + kind = ( + "person" if all(a.get("decided_by") == "human" for a in approved) else "agent" + ) + ids = sorted( + str( + a.get("approver_id") + or (a.get("approver") or {}).get("id") + or a.get("approver_kind") + or "unknown" + ) + for a in approved + ) + scope = sorted(str(a.get("request_sha256", "")) for a in approved) + values: dict[str, Optional[str]] = { + "approval.principal": f"{kind}:pr-" + + hashlib.sha256("\n".join(ids).encode("utf-8")).hexdigest()[:16], + "approval.scope": hashlib.sha256("\n".join(scope).encode("utf-8")).hexdigest(), + } + return {"mode": mode, "approver_kind": kind, "commitments": {}}, values + + def build_statement( report: Mapping[str, Any], report_sha256: str, @@ -137,6 +184,15 @@ def build_statement( bundle = bundle if isinstance(bundle, str) and _SHA256.fullmatch(bundle) else None version = bundle or report_sha256 subject = [{"name": "report.json", "digest": {"sha256": report_sha256}}] + try: + subject.append( + { + "name": "report.canonical", + "digest": {"sha256": r.report_canonical_sha256(report)}, + } + ) + except ValueError: # a report JSON can't express canonically: file digest only + pass if bundle: subject.append({"name": "bundle", "digest": {"sha256": bundle}}) name = report.get("workflow_name") @@ -152,9 +208,14 @@ def build_statement( run_id = report.get("run_id") if isinstance(run_id, str) and r.DISCLOSURE_FIELDS["run_id"].fullmatch(run_id): values["run_id"] = run_id - commitments, openings = r.make_openings(values, salt=salt) + approval, approval_values = _approval(report) + commitments, openings = r.make_openings({**values, **approval_values}, salt=salt) + if approval is not None: + approval["commitments"] = { + path.split(".", 1)[1]: commitments.pop(path) for path in approval_values + } checks = _checks(report) - statement = { + statement: dict[str, Any] = { "_type": r.STATEMENT_TYPE, "subject": subject, "predicateType": r.PREDICATE_TYPE, @@ -187,6 +248,8 @@ def build_statement( }, }, } + if approval is not None: + statement["predicate"]["approval"] = approval return statement, openings @@ -411,12 +474,20 @@ def verify_run_receipt( result = r.verify_receipt(envelope, registry, openings=openings) if not result.ok or result.statement is None: return result - subjects = {s["name"]: s["digest"]["sha256"] for s in result.statement["subject"]} - # ``attach-seal`` keeps the signed bytes as report.pre-seal.json. + # ``attach-seal`` keeps the signed bytes as report.pre-seal.json. The + # file digest is checked against ``report.json`` and the canonical digest + # against ``report.canonical``, never one against the other. for name in ("report.json", "report.pre-seal.json"): path = run_dir / name - if path.is_file() and ( - hashlib.sha256(path.read_bytes()).hexdigest() == subjects.get("report.json") + if not path.is_file(): + continue + data = path.read_bytes() + try: + canonical = r.report_canonical_sha256(loads_strict(data.decode("utf-8"))) + except (UnicodeDecodeError, ValueError): + canonical = None + if r.report_subject_match( + result.statement, file_bytes=data, canonical_sha256=canonical ): if name != "report.json" and (run_dir / "report.json").is_file(): # Say which bytes it covers: never a silent pass for a diff --git a/packages/types/openadapt_types/receipt.py b/packages/types/openadapt_types/receipt.py index 9728d29295..c35c738e4c 100644 --- a/packages/types/openadapt_types/receipt.py +++ b/packages/types/openadapt_types/receipt.py @@ -95,7 +95,25 @@ "field_values", "postconditions", ] -SubjectName = Literal["report.json", "bundle", "evidence"] +#: ``report.json``: SHA-256 of the report file's exact bytes on disk. +#: ``report.canonical``: SHA-256 of the report's RFC 8785 (JCS) canonical +#: JSON, the digest OpenAdapt Cloud's managed callback sends. They are +#: different digests of the same report and never stand in for each other. +SubjectName = Literal[ + "report.json", "report.canonical", "bundle", "evidence", "payload" +] +#: The media type of a handed-off payload (the ``payload`` subject only). +PayloadMediaType = Literal[ + "application/json", + "application/cbor", + "text/plain", + "text/csv", + "application/pdf", + "application/octet-stream", +] +ApprovalMode = Literal["each_item", "problems_only", "not_gated"] +#: Who answered, as Flow's item approval records it (decided_by). +ApproverKind = Literal["person", "agent", "none"] Role = Literal[ "this_computer", "customer_key", "openadapt_cloud", "public_log", "demo" @@ -115,6 +133,8 @@ "opening_mismatch", "disclosure_not_allowed", "inconsistent", + "payload_mismatch", + "payload_not_bound", "verifier_unavailable", ] @@ -147,6 +167,24 @@ class Digest(_Closed): class Subject(_Closed): name: SubjectName digest: Digest + #: Only on ``payload``: the bytes handed to another party (an MCP tool + #: result, an HTTP body or a file), by digest and media type. + media_type: Optional[PayloadMediaType] = None + + +_APPROVAL_KEY = re.compile(r"principal|scope|approved_at") + + +class Approval(_Closed): + """Who approved the run's writes, from Flow's item approval binding. + + The principal, the scope and the time are salted commitments; a public + card shows only the mode and the approver kind. + """ + + mode: ApprovalMode + approver_kind: ApproverKind + commitments: dict[StrictStr, StrictStr] = Field(max_length=3) class Program(_Closed): @@ -192,6 +230,68 @@ class Disclosure(_Closed): commitments: dict[StrictStr, StrictStr] = Field(max_length=16) +SystemKind = Literal[ + "ehr", "payer_portal", "bank", "erp", "crm", "government_portal", "email", "other" +] +ReadMethod = Literal["portal_read_back", "api", "acknowledgment_message"] +ConfirmationState = Literal[ + "sent", "acknowledged", "recorded_as_intended", "recorded_differently" +] +ConfirmationStrength = Literal["read_back", "acknowledgment", "none"] +#: Read methods that look at the other party's own system of record. +INDEPENDENT_READS: Final = ("portal_read_back", "api") +_CONFIRMATION_KEY = re.compile(r"counterparty|observed_at|reason|field\.[0-9]{1,2}") +ConfirmationReason = Literal[ + "rejected_by_counterparty", + "conflicting_report", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", +] +#: Which reasons each state may carry (no reason is always allowed). The +#: reason is committed, so it shows only where the private openings are read. +REASONS_FOR_STATE: Final[Mapping[str, frozenset[str]]] = { + "sent": frozenset( + { + "rejected_by_counterparty", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", + } + ), + "acknowledged": frozenset({"ambiguous_key", "not_found", "no_answer_by_deadline"}), + "recorded_as_intended": frozenset({"conflicting_report"}), + "recorded_differently": frozenset({"conflicting_report"}), +} + + +class Confirmation(_Closed): + """Evidence read from another party's system about one handoff. + + Everything that could identify the other party, the time or the fields + is a salted commitment; the openings stay in the private sidecar. + """ + + kind: Literal["counterparty_confirmation"] + for_step: Optional[Count] = Field(default=None, ge=0, le=10_000) + system_kind: SystemKind + read_method: ReadMethod + state: ConfirmationState + strength: ConfirmationStrength + differing_count: Count = Field(ge=0, le=64) + commitments: dict[StrictStr, StrictStr] = Field(min_length=2, max_length=34) + + +class Follows(_Closed): + """The receipt a follow-up record updates: the SHA-256 of the original + receipt's DSSE payload bytes, and this update's place in the chain.""" + + receipt: Digest + sequence: Count = Field(ge=1, le=MAX_LINES) + + class RunPredicateV1(_Closed): program: Program started_hour: StrictStr = Field(pattern=_HOUR) @@ -202,24 +302,95 @@ class RunPredicateV1(_Closed): checks: Checks model_calls: Count = Field(ge=0, le=MAX_COUNT) disclosure: Disclosure + #: Counterparty confirmations; omitted from the payload when empty, so a + #: receipt without one is byte-identical to one made before they existed. + confirmations: list[Confirmation] = Field(default_factory=list, max_length=64) + #: The approval binding; omitted when the run recorded none. + approval: Optional[Approval] = None + #: Set only on a follow-up record: a later, separately signed statement + #: that repeats the original receipt's predicate and carries only the + #: counterparty confirmations that changed since. Omitted otherwise, so a + #: receipt is byte-identical to one made before follow-ups existed. + follows: Optional[Follows] = None class RunStatementV1(_Closed): type_: Literal["https://in-toto.io/Statement/v1"] = Field(alias="_type") - subject: list[Subject] = Field(min_length=1, max_length=3) + subject: list[Subject] = Field(min_length=1, max_length=4) predicateType: Literal["https://openadapt.ai/record/run/v1"] predicate: RunPredicateV1 def wire(self) -> dict[str, Any]: - return self.model_dump(mode="json", by_alias=True) + out = self.model_dump(mode="json", by_alias=True) + if not out["predicate"]["confirmations"]: + del out["predicate"]["confirmations"] + if out["predicate"]["approval"] is None: + del out["predicate"]["approval"] + if out["predicate"]["follows"] is None: + del out["predicate"]["follows"] + for subject in out["subject"]: + if subject["media_type"] is None: + del subject["media_type"] + return out + + +def _check_confirmation(c: Confirmation, steps: set[int]) -> Optional[str]: + if c.for_step is not None and c.for_step not in steps: + return "a confirmation names a step with no line" + if c.state == "sent" and c.strength != "none": + return "a sent handoff has no confirmation strength" + if c.state == "acknowledged" and c.strength != "acknowledgment": + return "an acknowledgment has acknowledgment strength" + if c.state.startswith("recorded_") and ( + c.read_method not in INDEPENDENT_READS or c.strength != "read_back" + ): + return "only a portal or API read-back can say how the record was recorded" + if (c.state == "recorded_differently") != (c.differing_count > 0): + return "differing_count disagrees with the state" + if not {"counterparty", "observed_at"} <= set(c.commitments): + return "a confirmation commits to its counterparty and observed_at" + for key, value in c.commitments.items(): + if not _CONFIRMATION_KEY.fullmatch(key) or not re.fullmatch( + _SHA256_HEX[1:-1], value + ): + return f"confirmation commitment {key!r} is not a known field" + fields = sum(1 for key in c.commitments if key.startswith("field.")) + if c.differing_count > fields: + return "more differing fields than observed fields" + return None + + +def _check_approval(a: Approval) -> Optional[str]: + for key, value in a.commitments.items(): + if not _APPROVAL_KEY.fullmatch(key) or not re.fullmatch(_SHA256_HEX[1:-1], value): + return f"approval commitment {key!r} is not a known field" + if a.mode == "not_gated" and a.approver_kind != "none": + return "a not_gated run names no approver" + if a.approver_kind == "none": + if a.commitments: + return "an approval with no approver commits to nothing" + elif not {"principal", "scope"} <= set(a.commitments): + return "an approval names its approver's principal and scope" + return None def _check_consistent(statement: RunStatementV1) -> Optional[str]: """A closed statement that contradicts itself is refused, never repaired.""" p = statement.predicate + if p.follows is not None and not p.confirmations: + return "a follow-up record carries at least one confirmation" names = [s.name for s in statement.subject] - if len(set(names)) != len(names) or "report.json" not in names: + if len(set(names)) != len(names) or not {"report.json", "report.canonical"} & set( + names + ): return "subject names repeat, or the report is missing" + for subject in statement.subject: + if (subject.name == "payload") != (subject.media_type is not None): + return "only the payload subject has a media type, and it always has one" + if p.approval is not None: + problem = _check_approval(p.approval) + if problem: + return problem for path, value in p.disclosure.commitments.items(): if path not in DISCLOSURE_FIELDS or not re.fullmatch(_SHA256_HEX[1:-1], value): return f"disclosure path {path!r} is not a known field" @@ -247,6 +418,10 @@ def _check_consistent(statement: RunStatementV1) -> Optional[str]: steps = [line.step for line in p.lines] if steps != sorted(set(steps)): return "lines are not in step order, or repeat a step" + for c in p.confirmations: + problem = _check_confirmation(c, set(steps)) + if problem: + return problem return None @@ -321,7 +496,46 @@ def make_openings( return commitments, openings +_APPROVAL_PATH = re.compile(r"approval\.(principal|scope|approved_at)") +_APPROVAL_VALUES: Final[Mapping[str, re.Pattern[str]]] = { + "principal": re.compile(r"(person|agent):pr-[a-f0-9]{16}"), + "scope": re.compile(r"[a-f0-9]{64}"), + "approved_at": _ISO_SECONDS, +} +_CONFIRMATION_PATH = re.compile( + r"confirmations\.([0-9]{1,2})\.(counterparty|observed_at|reason|field\.[0-9]{1,2})" +) +_CONFIRMATION_VALUES: Final[Mapping[str, re.Pattern[str]]] = { + "counterparty": re.compile( + r"(ehr|payer_portal|bank|erp|crm|government_portal|email|other):cp-[a-f0-9]{16}" + ), + "observed_at": _ISO_SECONDS, + "reason": re.compile( + r"rejected_by_counterparty|conflicting_report|ambiguous_key" + r"|receiver_unreachable|not_found|no_answer_by_deadline" + ), + "field": re.compile(r"[a-z][a-z0-9_]{0,31}:[a-f0-9]{64}(:differs)?"), +} + + +def confirmation_path(index: int, key: str) -> str: + return f"confirmations.{index}.{key}" + + def _value_problem(path: str, value: Any) -> Optional[str]: + approval = _APPROVAL_PATH.fullmatch(path) + if approval: + if not (isinstance(value, str) and _APPROVAL_VALUES[approval.group(1)].fullmatch(value)): + return f"{path!r} does not match its field's pattern" + return None + found = _CONFIRMATION_PATH.fullmatch(path) + if found: + if not isinstance(value, str): + return f"{path!r} is not a string" + kind = found.group(2).split(".")[0] + if not _CONFIRMATION_VALUES[kind].fullmatch(value): + return f"{path!r} does not match its field's pattern" + return None pattern = DISCLOSURE_FIELDS.get(path) if pattern is None: return f"{path!r} is not a disclosure field" @@ -379,6 +593,94 @@ def _statement_embedded(statement: Mapping[str, Any]) -> Optional[str]: return find_embedded_content(rest) +# -- RFC 8785 (JCS) canonical JSON ----------------------------------------------- + + +def _jcs_number(value: Any) -> str: + if isinstance(value, bool): + raise ValueError("not a number") + if isinstance(value, int): + if abs(value) > 2**53 - 1: + raise ValueError("an integer outside the IEEE 754 safe range") + return str(value) + if value != value or value in (float("inf"), float("-inf")): + raise ValueError("NaN and infinity have no JSON form") + if value == 0: + return "0" + sign = "-" if value < 0 else "" + digits, _, exp = repr(abs(value)).replace("e+", "e").partition("e") + whole, _, frac = digits.partition(".") + mantissa = (whole + frac).lstrip("0") + shift = int(exp) if exp else 0 + if whole == "0": + point = shift - (len(frac) - len(frac.lstrip("0"))) + else: + point = len(whole) + shift + mantissa = mantissa.rstrip("0") or "0" + k, n = len(mantissa), point + if k <= n <= 21: + out = mantissa + "0" * (n - k) + elif 0 < n <= 21: + out = mantissa[:n] + "." + mantissa[n:] + elif -6 < n <= 0: + out = "0." + "0" * (-n) + mantissa + else: + e = n - 1 + head = mantissa[0] + ("." + mantissa[1:] if k > 1 else "") + out = f"{head}e{'+' if e >= 0 else '-'}{abs(e)}" + return sign + out + + +def jcs(value: Any) -> str: + """RFC 8785 canonical JSON: sorted keys (UTF-16 order), ES number form.""" + if value is None or isinstance(value, bool): + return json.dumps(value) + if isinstance(value, (int, float)): + return _jcs_number(value) + if isinstance(value, str): + return json.dumps(value, ensure_ascii=False) + if isinstance(value, (list, tuple)): + return "[" + ",".join(jcs(item) for item in value) + "]" + if isinstance(value, Mapping): + keys = sorted(value, key=lambda k: str(k).encode("utf-16-be")) + return ( + "{" + + ",".join(f"{json.dumps(str(k), ensure_ascii=False)}:{jcs(value[k])}" for k in keys) + + "}" + ) + raise ValueError(f"{type(value).__name__} has no JSON form") + + +def report_canonical_sha256(report: Any) -> str: + """The ``report.canonical`` digest of a parsed report.""" + return hashlib.sha256(jcs(report).encode("utf-8")).hexdigest() + + +def report_subject_match( + statement: Mapping[str, Any], + *, + file_bytes: Optional[bytes] = None, + canonical_sha256: Optional[str] = None, +) -> Optional[str]: + """Which report subject matches: ``report.json`` (file bytes) or ``report.canonical``. + + Each digest is compared only with its own subject; ``None`` when neither + matches. + """ + subjects = { + s.get("name"): s.get("digest", {}).get("sha256") + for s in statement.get("subject", []) + if isinstance(s, Mapping) + } + if file_bytes is not None and subjects.get("report.json") == hashlib.sha256( + file_bytes + ).hexdigest(): + return "report.json" + if canonical_sha256 is not None and subjects.get("report.canonical") == canonical_sha256: + return "report.canonical" + return None + + # -- envelope ------------------------------------------------------------------ @@ -575,6 +877,17 @@ class ReceiptVerification: disclosed: Mapping[str, str] = field(default_factory=dict) #: True when a full private openings file was checked. private: bool = False + #: One line per counterparty confirmation. Never merged with, and never + #: upgrading, ``signer_lines``. + confirmation_lines: tuple[str, ...] = () + #: Per confirmation: read from the other party's own system (portal or + #: API). Decided only from the read method; the signer's role comes + #: from the pinned registry. + independent: tuple[bool, ...] = () + #: "No approval recorded", or how the run's writes were approved. + approval_line: str = "" + #: True when ``payload`` bytes were given and match the payload subject. + payload_bound: Optional[bool] = None _REFUSAL_LINES: Final[Mapping[str, str]] = { @@ -589,6 +902,8 @@ class ReceiptVerification: "opening_mismatch": "Not verified: a disclosed value doesn't match the receipt", "disclosure_not_allowed": "Not verified: the card reveals a field it may not", "inconsistent": "Not verified: the receipt contradicts itself", + "payload_mismatch": "Not verified: these bytes aren't the payload the receipt signed", + "payload_not_bound": "Not verified: the receipt isn't bound to a payload", "malformed": "Not verified: malformed receipt", "verifier_unavailable": "Not verified: install cryptography to check signatures", } @@ -631,12 +946,16 @@ def verify_receipt( registry: Sequence[RoleKey], *, openings: Optional[Mapping[str, Any]] = None, + received: Optional[bytes] = None, ) -> ReceiptVerification: """Verify a receipt (a DSSE envelope) or a public card against pinned keys. ``document`` is the envelope (``receipt.json``) or a card (``openadapt.receipt-card/v1``). ``openings`` is the private sidecar for - an envelope; its values are checked against the commitments. A card's + an envelope; its values are checked against the commitments. + ``received`` is the bytes a receiver got in a handoff; the receipt must + name them as its ``payload`` subject (``payload_not_bound`` or + ``payload_mismatch`` otherwise). A card's openings must be on its disclosure version's allow-list. Fails closed: an unknown key, role or schema, any bad signature, a demo @@ -731,7 +1050,13 @@ def verify_receipt( problem = _check_consistent(statement) if problem: return _refuse("inconsistent", problem) - commitments = statement.predicate.disclosure.commitments + commitments = dict(statement.predicate.disclosure.commitments) + for index, c in enumerate(statement.predicate.confirmations): + for key, value in c.commitments.items(): + commitments[confirmation_path(index, key)] = value + if statement.predicate.approval is not None: + for key, value in statement.predicate.approval.commitments.items(): + commitments[f"approval.{key}"] = value disclosed: dict[str, str] = {} private = False if card_openings is not None: @@ -755,6 +1080,12 @@ def verify_receipt( return result disclosed = result private = True + for index, c in enumerate(statement.predicate.confirmations): + reason = disclosed.get(confirmation_path(index, "reason")) + if reason is not None and reason not in REASONS_FOR_STATE[c.state]: + return _refuse( + "inconsistent", f"a {c.state} confirmation can't have reason {reason}" + ) ordered = sorted( checks, key=lambda c: _ROLE_ORDER.index(c.role) if c.role in _ROLE_ORDER else -1, @@ -763,8 +1094,24 @@ def verify_receipt( for c in ordered: if c.line not in lines: lines.append(c.line) + payload_bound: Optional[bool] = None + if received is not None: + bound = next((x for x in statement.subject if x.name == "payload"), None) + if bound is None: + return _refuse("payload_not_bound", "the receipt names no payload") + if bound.digest.sha256 != hashlib.sha256(received).hexdigest(): + return _refuse("payload_mismatch", "the bytes received aren't the payload signed") + payload_bound = True + confirmations = statement.predicate.confirmations return ReceiptVerification( True, + approval_line=approval_line(statement.predicate.approval), + payload_bound=payload_bound, + confirmation_lines=tuple( + confirmation_line(c, disclosed.get(confirmation_path(i, "observed_at"))) + for i, c in enumerate(confirmations) + ), + independent=tuple(c.read_method in INDEPENDENT_READS for c in confirmations), signers=tuple(ordered), signer_lines=tuple(lines), demo=demo, @@ -775,6 +1122,177 @@ def verify_receipt( ) +def approval_line(a: Optional[Approval]) -> str: + """The verifier's approval line, as every verifier prints it.""" + if a is None: + return "No approval recorded" + if a.mode == "not_gated": + return "Not gated: no approval was required for these writes" + if a.approver_kind == "none": + mode = "each item" if a.mode == "each_item" else "items that fail a check" + return f"Approval required for {mode}; no item was approved" + who = "a person" if a.approver_kind == "person" else "an agent delegate" + how = "each item" if a.mode == "each_item" else "items that failed a check" + return f"Approved by {who}: {how}" + + +def confirmation_line(c: Confirmation, observed_at: Optional[str] = None) -> str: + """The verifier's line for one confirmation, as every verifier prints it.""" + at = f" at {observed_at}" if observed_at else "" + if c.state == "recorded_as_intended": + return f"Confirmed in the other party's system{at}" + if c.state == "recorded_differently": + noun = "field differs" if c.differing_count == 1 else "fields differ" + return ( + f"Recorded differently in the other party's system{at}: " + f"{c.differing_count} {noun}" + ) + if c.state == "acknowledged": + return f"Acknowledged by the other party{at}" + return f"Sent to the other party{at}, not confirmed" + + +# -- follow-up records ------------------------------------------------------------ + +#: Predicate fields a follow-up copies from its original, unchanged. +FOLLOW_UP_COPIED: Final = ( + "program", + "started_hour", + "outcome", + "reason_code", + "steps", + "lines", + "checks", + "model_calls", + "disclosure", + "approval", +) +#: Why a chain of follow-ups is refused (beyond a refusal of one record). +ChainRefusal = Literal[ + "original_refused", + "original_is_follow_up", + "update_refused", + "not_a_follow_up", + "wrong_original", + "out_of_sequence", + "changed_original", + "mixed_demo", + "different_signer", +] + + +def payload_sha256(envelope: Mapping[str, Any]) -> str: + """SHA-256 of an envelope's DSSE payload bytes: what ``follows`` names.""" + return hashlib.sha256( + base64.b64decode(str(envelope["payload"]), validate=True) + ).hexdigest() + + +@dataclass(frozen=True) +class ChainVerification: + ok: bool + reason: Optional[ChainRefusal] = None + detail: str = "" + original: Optional[ReceiptVerification] = None + updates: tuple[ReceiptVerification, ...] = () + #: The original's confirmation lines, then ``Update N: `` for each + #: follow-up's lines, in order. Never merged with the signer lines. + lines: tuple[str, ...] = () + + +def follow_up_statement( + original: Mapping[str, Any], sequence: int, confirmations: Sequence[Any] +) -> dict[str, Any]: + """A follow-up statement: ``original``'s statement (a dict from its + payload) with only the changed ``confirmations`` and ``follows`` set. + ``original`` is the original receipt's envelope.""" + payload = loads_strict(base64.b64decode(str(original["payload"]), validate=True)) + predicate = {k: v for k, v in payload["predicate"].items() if k in FOLLOW_UP_COPIED} + predicate["confirmations"] = list(confirmations) + predicate["follows"] = { + "receipt": {"sha256": payload_sha256(original)}, + "sequence": sequence, + } + return {**payload, "predicate": predicate} + + +def verify_chain( + original: Mapping[str, Any], + updates: Sequence[Mapping[str, Any]], + registry: Sequence[RoleKey], + *, + openings: Optional[Mapping[str, Any]] = None, + update_openings: Sequence[Optional[Mapping[str, Any]]] = (), +) -> ChainVerification: + """Verify a receipt and its follow-up records, in order. + + Each follow-up must verify on its own, be signed only by keys that + signed the original, name the original's payload digest in ``follows``, + count 1, 2, 3 in ``sequence``, and copy every other predicate field and + the subjects unchanged. Any failure refuses + the whole chain. A valid chain shows the original's confirmation lines + and then each update's, labelled ``Update N``. + """ + first = verify_receipt(original, registry, openings=openings) + if not first.ok or first.statement is None: + return ChainVerification(False, "original_refused", first.detail, first) + base = first.statement + if "follows" in base["predicate"]: + return ChainVerification( + False, "original_is_follow_up", "the first record is a follow-up", first + ) + digest = payload_sha256(original) + original_keys = {signer.key_id for signer in first.signers} + lines = list(first.confirmation_lines) + checked: list[ReceiptVerification] = [] + for index, update in enumerate(updates): + opened = update_openings[index] if index < len(update_openings) else None + result = verify_receipt(update, registry, openings=opened) + checked.append(result) + if not result.ok or result.statement is None: + return ChainVerification( + False, + "update_refused", + f"update {index + 1}: {result.reason}", + first, + tuple(checked), + ) + if result.demo != first.demo: + # A demo-key update can't extend a real chain, or the reverse. + return ChainVerification( + False, "mixed_demo", f"update {index + 1}", first, tuple(checked) + ) + update_keys = {signer.key_id for signer in result.signers} + if not update_keys or not update_keys <= original_keys: + # Another key in the registry can't speak for the original's signer. + return ChainVerification( + False, "different_signer", f"update {index + 1}", first, tuple(checked) + ) + predicate = result.statement["predicate"] + follows = predicate.get("follows") + if not isinstance(follows, Mapping): + return ChainVerification( + False, "not_a_follow_up", f"update {index + 1}", first, tuple(checked) + ) + if follows["receipt"]["sha256"] != digest: + return ChainVerification( + False, "wrong_original", f"update {index + 1}", first, tuple(checked) + ) + if follows["sequence"] != index + 1: + return ChainVerification( + False, "out_of_sequence", f"update {index + 1}", first, tuple(checked) + ) + same = result.statement["subject"] == base["subject"] and all( + predicate.get(k) == base["predicate"].get(k) for k in FOLLOW_UP_COPIED + ) + if not same: + return ChainVerification( + False, "changed_original", f"update {index + 1}", first, tuple(checked) + ) + lines += [f"Update {index + 1}: {line}" for line in result.confirmation_lines] + return ChainVerification(True, None, "", first, tuple(checked), tuple(lines)) + + def _check_openings( openings: Any, commitments: Mapping[str, str], @@ -846,6 +1364,19 @@ def program_id(name: Any, version_sha256: str) -> str: "add_signature", "canonical_json", "commitment", + "Approval", + "ChainVerification", + "FOLLOW_UP_COPIED", + "follow_up_statement", + "payload_sha256", + "verify_chain", + "jcs", + "report_canonical_sha256", + "report_subject_match", + "approval_line", + "Confirmation", + "confirmation_line", + "confirmation_path", "find_embedded_content", "is_receipt_card", "is_receipt_envelope", diff --git a/packages/types/tests/test_receipt_follow_up.py b/packages/types/tests/test_receipt_follow_up.py new file mode 100644 index 0000000000..4f9734e7af --- /dev/null +++ b/packages/types/tests/test_receipt_follow_up.py @@ -0,0 +1,119 @@ +"""Follow-up records: a later signed update to a receipt's counterparty lines.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +pytest.importorskip("cryptography") + +from openadapt_types import receipt as r # noqa: E402 + +_GEN = Path(__file__).parent / "vectors" / "record-run-v1" / "generate.py" +_spec = importlib.util.spec_from_file_location("receipt_vector_generate", _GEN) +gen = importlib.util.module_from_spec(_spec) +assert _spec.loader is not None +_spec.loader.exec_module(gen) + + +def _registry(): + return r.parse_registry(gen.REGISTRY) + + +def _sign(statement): + return r.sign_statement(statement, [gen.signer("this_computer")]) + + +def _original(): + statement, openings = gen._confirmed("sent") + return _sign(statement), openings + + +def _update(original, sequence, state): + updated, _ = gen._confirmed(state) + return _sign( + r.follow_up_statement(original, sequence, updated["predicate"]["confirmations"]) + ) + + +def test_a_chain_verifies_and_labels_each_update(): + original, openings = _original() + one = _update(original, 1, "acknowledged") + two = _update(original, 2, "recorded_as_intended") + chain = r.verify_chain( + original, + [one, two], + _registry(), + openings=r.private_openings(original, openings), + ) + assert chain.ok, chain + assert chain.lines == ( + "Sent to the other party at 2026-11-20T23:41:07Z, not confirmed", + "Update 1: Acknowledged by the other party", + "Update 2: Confirmed in the other party's system", + ) + + +def test_a_receipt_without_follows_is_byte_identical(): + statement, _ = gen._confirmed("sent") + assert ( + "follows" not in r.RunStatementV1.model_validate(statement).wire()["predicate"] + ) + + +@pytest.mark.parametrize( + "build,reason", + [ + (lambda o: [_update(o, 2, "acknowledged")], "out_of_sequence"), + (lambda o: [_sign(gen._confirmed("acknowledged")[0])], "not_a_follow_up"), + ], +) +def test_broken_chains_are_refused(build, reason): + original, _ = _original() + chain = r.verify_chain(original, build(original), _registry()) + assert (chain.ok, chain.reason) == (False, reason) + + +def test_a_follow_up_naming_another_receipt_or_changing_it_is_refused(): + original, _ = _original() + update = _update(original, 1, "acknowledged") + stmt = r.follow_up_statement( + original, 1, gen._confirmed("acknowledged")[0]["predicate"]["confirmations"] + ) + stmt["predicate"]["follows"]["receipt"]["sha256"] = "0" * 64 + assert ( + r.verify_chain(original, [_sign(stmt)], _registry()).reason == "wrong_original" + ) + changed = r.follow_up_statement( + original, 1, gen._confirmed("acknowledged")[0]["predicate"]["confirmations"] + ) + changed["predicate"]["model_calls"] = 9 + assert ( + r.verify_chain(original, [_sign(changed)], _registry()).reason + == "changed_original" + ) + assert r.verify_chain(update, [], _registry()).reason == "original_is_follow_up" + + +def test_a_follow_up_signed_by_another_registered_key_is_refused(): + original, _ = _original() + updated, _ = gen._confirmed("acknowledged") + statement = r.follow_up_statement( + original, 1, updated["predicate"]["confirmations"] + ) + by_other = r.sign_statement(statement, [gen.signer("customer_key")]) + assert r.verify_receipt(by_other, _registry()).ok + chain = r.verify_chain(original, [by_other], _registry()) + assert (chain.ok, chain.reason) == (False, "different_signer") + both = r.sign_statement( + statement, [gen.signer("this_computer"), gen.signer("customer_key")] + ) + assert r.verify_chain(original, [both], _registry()).reason == "different_signer" + + +def test_an_empty_follow_up_cannot_be_signed(): + original, _ = _original() + with pytest.raises(ValueError, match="at least one confirmation"): + _sign(r.follow_up_statement(original, 1, [])) diff --git a/packages/types/tests/test_receipt_vectors.py b/packages/types/tests/test_receipt_vectors.py index 2a5a880042..b2b2f93b13 100644 --- a/packages/types/tests/test_receipt_vectors.py +++ b/packages/types/tests/test_receipt_vectors.py @@ -2,6 +2,7 @@ from __future__ import annotations +import base64 import json from pathlib import Path @@ -12,7 +13,13 @@ from openadapt_types import receipt as r # noqa: E402 VECTORS = Path(__file__).parent / "vectors" / "record-run-v1" -NAMES = sorted(p.stem for p in VECTORS.glob("*.json") if not p.name.startswith("registry")) +NAMES = sorted( + p.stem + for p in VECTORS.glob("*.json") + if not p.name.startswith("registry") + and p.stem != "jcs" + and not p.stem.startswith("chain-") +) def _registry(): @@ -29,6 +36,18 @@ def test_the_vector_set_is_complete(): "cloud-countersign", "embedded-image-in-card", "embedded-image-in-record", + "confirmation-recorded-as-intended", + "confirmation-recorded-differently", + "confirmation-acknowledged", + "confirmation-sent", + "confirmation-tampered", + "confirmation-public-redaction", + "confirmation-reason-no-answer", + "payload-bound", + "payload-mismatch", + "payload-missing", + "approval-public-card", + "approval-none", ): assert required in NAMES @@ -36,7 +55,13 @@ def test_the_vector_set_is_complete(): @pytest.mark.parametrize("name", NAMES) def test_vector(name): vector = json.loads((VECTORS / f"{name}.json").read_text()) - result = r.verify_receipt(vector["document"], _registry(), openings=vector.get("openings")) + received = vector.get("received") + result = r.verify_receipt( + vector["document"], + _registry(), + openings=vector.get("openings"), + received=base64.b64decode(received) if received is not None else None, + ) expected = vector["expected"] assert result.ok is expected["ok"], result.detail assert result.reason == expected["reason"] @@ -45,6 +70,13 @@ def test_vector(name): assert result.outcome == expected["outcome"] assert result.demo is expected["demo"] assert dict(result.disclosed) == expected["disclosed"] + assert list(result.confirmation_lines) == expected.get("confirmation_lines", []) + assert list(result.independent) == expected.get("independent", []) + # A confirmation line never joins or upgrades the signer lines. + assert not set(result.confirmation_lines) & set(result.signer_lines) + if "approval_line" in expected: + assert result.approval_line == expected["approval_line"] + assert result.payload_bound == expected.get("payload_bound") else: assert result.outcome is None @@ -99,3 +131,79 @@ def test_allow_list_fields_are_disclosure_fields(): assert set(allowed) <= set(r.DISCLOSURE_FIELDS) for source in allowed.values(): assert source.split(":")[0] in ("public-card/v1", "public-evidence-receipt/v1") + + +def test_a_statement_without_confirmations_is_byte_identical(): + vector = json.loads((VECTORS / "valid.json").read_text()) + import base64 + + payload = base64.b64decode(vector["document"]["payload"]) + assert b"confirmations" not in payload + assert r.statement_payload(json.loads(payload)) == payload + + +@pytest.mark.parametrize( + "change", + [ + {"state": "recorded_as_intended", "read_method": "acknowledgment_message"}, + {"state": "sent", "strength": "read_back"}, + {"state": "recorded_differently", "differing_count": 0}, + {"for_step": 3}, + ], +) +def test_inconsistent_confirmations_are_refused(change): + vector = json.loads((VECTORS / "confirmation-recorded-as-intended.json").read_text()) + import base64 + + statement = json.loads(base64.b64decode(vector["document"]["payload"])) + statement["predicate"]["confirmations"][0].update(change) + with pytest.raises(ValueError): + r.statement_payload(statement) + + +def test_jcs_cases(): + cases = json.loads((VECTORS / "jcs.json").read_text())["cases"] + assert len(cases) >= 10 + for case in cases: + assert r.jcs(case["input"]) == case["canonical"] + # UTF-16 key order, not code point order. + assert r.jcs({"\uffff": 1, "\U0001f600": 2}) == '{"\U0001f600":2,"\uffff":1}' + + +def test_report_digests_never_stand_in_for_each_other(): + import hashlib + + vector = json.loads((VECTORS / "report-canonical.json").read_text()) + statement = json.loads(base64.b64decode(vector["document"]["payload"])) + file_bytes = base64.b64decode(vector["report_file"]) + canonical = r.report_canonical_sha256(vector["report"]) + assert canonical == vector["expected"]["report_canonical_sha256"] + assert r.jcs(vector["report"]) == vector["expected"]["report_canonical"] + assert r.report_subject_match(statement, file_bytes=file_bytes) == "report.json" + assert r.report_subject_match(statement, canonical_sha256=canonical) == "report.canonical" + # Neither digest is accepted in the other's place. + file_digest = hashlib.sha256(file_bytes).hexdigest() + assert r.report_subject_match(statement, canonical_sha256=file_digest) is None + assert ( + r.report_subject_match(statement, file_bytes=r.jcs(vector["report"]).encode()) + is None + ) + + +CHAINS = sorted(p.stem for p in VECTORS.glob("chain-*.json")) + + +def test_the_chain_vectors_are_there(): + assert {"chain-valid", "chain-wrong-original", "chain-out-of-sequence", + "chain-tampered", "chain-empty", "chain-different-signer"} <= set(CHAINS) + + +@pytest.mark.parametrize("name", CHAINS) +def test_chain_vector(name): + vector = json.loads((VECTORS / f"{name}.json").read_text()) + chain = vector["chain"] + result = r.verify_chain(chain["original"], chain["updates"], _registry()) + expected = vector["expected"] + assert result.ok is expected["ok"], result.detail + assert result.reason == expected["reason"] + assert list(result.lines) == expected["lines"] diff --git a/packages/types/tests/vectors/record-run-v1/README.md b/packages/types/tests/vectors/record-run-v1/README.md index 26b3f2b13d..814ab377b2 100644 --- a/packages/types/tests/vectors/record-run-v1/README.md +++ b/packages/types/tests/vectors/record-run-v1/README.md @@ -55,6 +55,75 @@ not secrets. A refusal shows one "Not verified: ..." line; an unknown key shows "Not verified: unknown signer". 7. **Outcome.** Copied from the statement, never upgraded. +8. **Counterparty confirmations.** `predicate.confirmations[]` is optional and + omitted when empty. Each item is closed: `kind` (`counterparty_confirmation`), + `for_step` (null or the step of a line), `system_kind`, `read_method` + (`portal_read_back`, `api`, `acknowledgment_message`), `state` (`sent`, + `acknowledged`, `recorded_as_intended`, `recorded_differently`), `strength` + (`read_back`, `acknowledgment`, `none`), `differing_count` and `commitments` + (keys `counterparty`, `observed_at`, optional `reason`, `field.`). Rules: + `sent` has strength `none`; `acknowledged` has `acknowledgment`; both + `recorded_*` states need a portal or API read and `read_back`; + `differing_count` is at least 1 exactly for `recorded_differently`. Openings + use paths `confirmations..`, live only in the private sidecar, and + are never on the public allow-list. Values: counterparty + `:cp-<16 hex>`; `observed_at` ISO seconds with Z; a field + `:` with `:differs` when it differs; `reason` one of + `rejected_by_counterparty`, `conflicting_report`, `ambiguous_key`, + `receiver_unreachable`, `not_found`, `no_answer_by_deadline`. When the reason + is opened it must suit the state: `sent` takes any but `conflicting_report`; + `acknowledged` takes `ambiguous_key`, `not_found` or + `no_answer_by_deadline`; both `recorded_*` states take only + `conflicting_report` (otherwise `inconsistent`). + Each confirmation prints its own line in `confirmation_lines`, never in + `signer_lines`: "Confirmed in the other party's system[ at