diff --git a/.cspell.json b/.cspell.json index dc09c20..9488317 100644 --- a/.cspell.json +++ b/.cspell.json @@ -10,6 +10,7 @@ ".vscode/**", ".cspell.json", "**/*.svg", + "common/payments/fixtures/ap2_order_receipts/**", ".gitignore", "package.json" ], diff --git a/.cspell/custom-words.txt b/.cspell/custom-words.txt index 9525e8c..70a6973 100644 --- a/.cspell/custom-words.txt +++ b/.cspell/custom-words.txt @@ -68,6 +68,7 @@ repudiable resourceless schemas sdjwt +SECP Sephora shellcheck Shopee @@ -79,6 +80,7 @@ superfences Target UCP Ulta +unpadded Villagetown Visa vulnz diff --git a/README.md b/README.md index 546ee4b..dff3d38 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,9 @@ The test suite follows a 4-tier modular architecture per UCP RFC #520: - **`common/`**: Cross-cutting protocol capabilities such as payment credentials and extensions (`common/payments/`). These currently use the shopping checkout as their vehicle and are gated on the capabilities they - need. + need. The AP2 Order receipt vectors (`common/payments/fixtures/`) are the + exception: they check fixed receipts with a platform-side verifier and run + without a server. - **`shopping/`**: Retail shopping domain tests organized by functional domain: `checkout/` (including idempotency), `discount/`, `fulfillment/`, `order/` (including order-event webhooks), and `validation/`. diff --git a/common/payments/ap2_order_receipts_test.py b/common/payments/ap2_order_receipts_test.py new file mode 100644 index 0000000..379f84f --- /dev/null +++ b/common/payments/ap2_order_receipts_test.py @@ -0,0 +1,282 @@ +# Copyright 2026 UCP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AP2 Order receipts issued by the server under test verify. + +Order receipts (ap2-mandates.md "Order Receipts", ucp#1109) are optional: +they are required only when both profiles declare `order_receipts` in the +`dev.ucp.common.payment.ap2_mandate` config. These tests skip unless the +business does, and the platform profile they serve declares it too. + +The receipts are checked with the same platform-side verifier as the fixed +vectors in ap2_receipt_vectors_test.py, against the `keys` the business +publishes at `/.well-known/ucp` and the Payment Mandate the test sent. + +Like ap2_test.py, completion sends placeholder mandates; a business that +verifies real AP2 mandates rejects them. +""" + +import json +import logging +from typing import Any + +from absl.testing import absltest +from common.payments import ap2_receipt_verifier as v +from framework.agent_profile_server import ( + DEFAULT_PROFILE_TEMPLATE, + AgentProfileServer, +) +from framework.base_test import FLAGS +from framework.decorators import requires_capability +from framework.discovery import FORMER_NAMES +from shopping.base import ShoppingIntegrationTestBase, get_valid_payment_payload + +_AP2_CAPABILITY = "dev.ucp.common.payment.ap2_mandate" + +# order_receipts_config.events in payment_ap2_mandate.json. +_RECEIPT_EVENTS = [ + "authorization", + "authorization_adjustment", + "capture", + "capture_reversal", + "release", + "refund", +] + + +def _order_receipts_config(profile_raw: dict[str, Any]) -> dict | None: + """Return the business's `order_receipts` config, if it declares one.""" + ucp = profile_raw.get("ucp", profile_raw) + capabilities = ucp.get("capabilities", {}) + if not isinstance(capabilities, dict): + return None + for name in (_AP2_CAPABILITY, *FORMER_NAMES.get(_AP2_CAPABILITY, ())): + entries = capabilities.get(name) or [] + for entry in entries if isinstance(entries, list) else [entries]: + config = (entry or {}).get("config") or {} + if isinstance(config.get("order_receipts"), dict): + return config["order_receipts"] + return None + + +@requires_capability(_AP2_CAPABILITY) +@requires_capability("dev.ucp.shopping.order") +class Ap2OrderReceiptsTest(ShoppingIntegrationTestBase): + """Receipts a business issues on an AP2 Order verify. + + Validated Paths: + - POST /checkout-sessions/{id}/complete + - GET /orders/{id} + """ + + def _verify_required_capabilities(self) -> None: + """Also skip unless the business declares `order_receipts`.""" + super()._verify_required_capabilities() + if self.server_profile is None: + self.skipTest("discovery profile unavailable") + if _order_receipts_config(self.server_profile.raw) is None: + self.skipTest( + f"server does not declare order_receipts in its {_AP2_CAPABILITY} " + "config (ap2-mandates.md, Order Receipts: Negotiation)" + ) + + def _start_agent_server(self) -> None: + """Serve a platform profile that also declares `order_receipts`. + + Receipts are required only when both profiles declare it + (ap2-mandates.md, Order Receipts: Negotiation). + """ + profile = json.loads(DEFAULT_PROFILE_TEMPLATE.read_text(encoding="utf-8")) + profile["ucp"]["capabilities"][_AP2_CAPABILITY] = [ + { + "name": _AP2_CAPABILITY, + "version": "{ucp_version}", + "spec": "https://ucp.dev/{ucp_version}/specification/payment/" + "extensions/ap2-mandates", + "schema": "https://ucp.dev/{ucp_version}/schemas/common/" + "payment_ap2_mandate.json", + "extends": ["dev.ucp.shopping.checkout", "dev.ucp.shopping.order"], + "config": {"order_receipts": {"events": _RECEIPT_EVENTS}}, + } + ] + self.agent_server = AgentProfileServer( + port=FLAGS.mock_agent_port if FLAGS.is_parsed() else 8285, + webhook_port=FLAGS.mock_webhook_port if FLAGS.is_parsed() else 8284, + ucp_version=self.ucp_version, + profile_dict=profile, + ) + self.agent_server.start() + self.addCleanup(self.agent_server.stop) + + @property + def business_profile_uri(self) -> str: + """The profile URI the business's receipts carry as `iss`.""" + return f"{self.base_url}/.well-known/ucp" + + def _place_order(self) -> tuple[dict[str, Any], v.Mandate]: + """Complete an AP2 checkout; return the Order and the mandate sent.""" + checkout_data = self.create_checkout_session() + payment_payload = get_valid_payment_payload() + # Placeholder mandate, as in ap2_test.py. The Payment Mandate travels in + # payment.instruments[*].credential.token, which mandate_ref hashes + # (ap2-mandates.md, Hashes and Chaining). + payment_payload["ap2"] = { + **checkout_data, + "checkout_mandate": "header.payload.signature~kb_signature", + } + token = payment_payload["payment"]["instruments"][0]["credential"]["token"] + complete_data = self.complete_checkout_session( + checkout_data["id"], payment_payload + ) + order_id = complete_data["order"]["id"] + return self._get_order(order_id), v.Mandate( + token, self.business_profile_uri + ) + + def _get_order(self, order_id: str) -> dict[str, Any]: + response = self.client.get( + self.get_order_url(order_id), headers=self.get_headers() + ) + self.assert_response_status(response, 200) + return response.json() + + def _receipts(self, order: dict[str, Any]) -> list[str]: + receipts = (order.get("ap2") or {}).get("receipts") or [] + self.assertIsInstance(receipts, list, "ap2.receipts must be an array") + return receipts + + def _assert_receipts_verify( + self, order: dict[str, Any], mandate: v.Mandate + ) -> v.VerificationResult: + """Verify the Order's receipts and the business requirements on them.""" + keys = self.server_profile.raw.get("keys") or [] + result = v.verify_order_receipts( + order, {self.business_profile_uri: keys}, [mandate] + ) + # receipt_payload: the members the schema requires. + self.assertEqual( + result.malformed, [], "signed receipts that are not Receipt Payloads" + ) + + # Platform Verification 1 and 2 are MUSTs. + self.assertEqual( + result.outcomes, + [], + "receipts failed verification (ap2-mandates.md, Platform " + "Verification 1-2): " + + "; ".join( + f"{f.receipt_index}: {f.code} ({f.detail})" for f in result.outcomes + ), + ) + # Platform Verification 3 and 4 are SHOULDs: reported, not failed. + for finding in result.warnings + result.reconciliation: + logging.warning( + "receipt %d: %s (%s)", + finding.receipt_index, + finding.code, + finding.detail, + ) + + previous: dict[v.ChainKey, dict[str, int]] = {} + for receipt in result.verified: + payload = receipt.payload + where = f"receipt {receipt.index}" + self.assertEqual(payload["order_id"], order["id"], f"{where}: order_id") + # receipt_event.currency: "MUST match the Order currency." + self.assertEqual( + payload["event"]["currency"], order.get("currency"), where + ) + # receipt_event.status: "Only `succeeded` events change the running + # totals." + totals = payload["totals"] + self.assertEqual( + (totals["captured"], totals["refunded"]), + (receipt.derived_totals.captured, receipt.derived_totals.refunded), + f"{where}: captured/refunded do not follow from the chain's " + "succeeded events", + ) + if payload["event"]["status"] != "succeeded": + opening = { + "mandated": totals["mandated"], + "authorized": 0, + "captured": 0, + "refunded": 0, + } + self.assertEqual( + totals, + previous.get(receipt.chain, opening), + f"{where}: a {payload['event']['status']} event changed totals", + ) + previous[receipt.chain] = totals + return result + + def test_issued_receipts_verify(self) -> None: + """Test that the receipts on a new AP2 Order verify. + + Given a business that declares order_receipts, + When an AP2 checkout is completed and the Order is read, + Then every receipt in ap2.receipts verifies against the business's keys + and the Payment Mandate sent, with no sequence gaps and both total + invariants holding. + """ + order, mandate = self._place_order() + if not self._receipts(order): + self.skipTest("the business issued no receipts for the new Order") + self._assert_receipts_verify(order, mandate) + + def test_receipts_extend_after_shipment(self) -> None: + """Test that a later Order update keeps earlier receipts. + + Given an AP2 Order with receipts, + When the order ships and is read again, + Then ap2.receipts still holds every earlier receipt, each chain in seq + order (ap2-mandates.md, Placement and Delivery), and all of them + verify. + """ + order, mandate = self._place_order() + before = self._receipts(order) + headers = self.get_headers() + headers["Simulation-Secret"] = FLAGS.simulation_secret + ship_response = self.client.post( + f"/testing/simulate-shipping/{order['id']}", headers=headers + ) + if ship_response.status_code == 403: + self.skipTest( + "simulation secret rejected (/testing/simulate-shipping -> 403); " + "configure --simulation_secret to match the server under test" + ) + if ship_response.status_code in (404, 405): + self.skipTest( + "server exposes no simulation path " + f"(/testing/simulate-shipping -> {ship_response.status_code}); " + "cannot trigger an order update" + ) + self.assert_response_status(ship_response, 200) + + shipped = self._get_order(order["id"]) + after = self._receipts(shipped) + if not after: + self.skipTest("the business issued no receipts for the Order") + for receipt in before: + self.assertIn(receipt, after, "an earlier receipt was dropped") + self.assertEqual( + [r for r in after if r in before], + before, + "earlier receipts changed order", + ) + self._assert_receipts_verify(shipped, mandate) + + +if __name__ == "__main__": + absltest.main() diff --git a/common/payments/ap2_receipt_fixtures.py b/common/payments/ap2_receipt_fixtures.py new file mode 100644 index 0000000..143b737 --- /dev/null +++ b/common/payments/ap2_receipt_fixtures.py @@ -0,0 +1,1054 @@ +# Copyright 2026 UCP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generate the AP2 Order receipt vectors in fixtures/ap2_order_receipts/. + +Regenerate the fixtures, or check that the committed ones are current: + + uv run python -m common.payments.ap2_receipt_fixtures + uv run python -m common.payments.ap2_receipt_fixtures --check + +The output is byte-for-byte reproducible: + +* Vectors built on the signed Order example in ucp#1109 copy its three + receipts verbatim (`_SPEC_CHAIN`); they verify with the example key from + the PR description (`_SPEC_KEY`). There is no private key for them here. +* Every other receipt is signed with a TEST-ONLY P-256 key derived from a + fixed label (`_test_only_key`), using deterministic ECDSA (RFC 6979), so + the same payload always yields the same signature. + +The TEST-ONLY keys are public by construction. Never use them for anything +but these vectors. +""" + +import argparse +import datetime +import hashlib +import json +from pathlib import Path +import sys +from typing import Any + +from common.payments import ap2_receipt_verifier as v +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, utils + +FIXTURE_DIR = ( + Path(__file__).resolve().parent / "fixtures" / "ap2_order_receipts" +) + +# Order example in ucp#1109 (docs/specification/payment/extensions/ +# ap2-mandates.md, "Placement and Delivery"), at head 1d19291d. +SPEC_SOURCE = ( + "Universal-Commerce-Protocol/ucp#1109 at 1d19291d, ap2-mandates.md, " + "Order example under 'Placement and Delivery'" +) +# cspell:disable +_SPEC_KEY = { + "kty": "EC", + "crv": "P-256", + "kid": "merchant_2025", + "use": "sig", + "alg": "ES256", + "x": "GzEF_HXZbmVOvExfSerMRYki1vTfR1fETwLcYi8MS50", + "y": "iDtJQqA9IVKbVvAQ7tL_G73kkG1GoaHJKSty0pWD0b8", +} +_SPEC_CHAIN = ( + "eyJhbGciOiJFUzI1NiIsImtpZCI6Im1lcmNoYW50XzIwMjUiLCJ0eXAiOiJ1Y3AtYXAyLXJlY2VpcHQrand0In0.eyJjaGVja291dF9pZCI6ImNoa19hYmMxMjMiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3Jpem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" +# `mandate_ref` in the spec chain hashes the credential token of the +# complete_checkout example in the same document. +_SPEC_TOKEN = "examplePaymentMethodToken" + +_TEST_ONLY_SIGNING = ( + "TEST-ONLY P-256 keys derived from fixed labels in " + "common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). " + "Never use them outside these vectors." +) +_SPEC_SIGNING = ( + "Receipts copied byte-for-byte from the signed Order example in " + "ucp#1109; key from the PR description (example only)." +) + +_MERCHANT = "https://merchant.example/.well-known/ucp" +_MARKETPLACE = "https://marketplace.example/.well-known/ucp" +_SELLER_A = "https://seller-a.example/.well-known/ucp" +_SELLER_B = "https://seller-b.example/.well-known/ucp" +_HOTEL = "https://hotel.example/.well-known/ucp" + +# ucp#1109 rule text, quoted without Markdown emphasis. +_RULES = { + "verify_1": ( + "Platform Verification 1: MUST verify each receipt's signature against " + "the `keys` of the business named in `iss`, and MUST treat a receipt " + "whose `iss` is not the business that signed the checkout covered by " + "`mandate_ref` as `receipt_mandate_unknown`." + ), + "verify_2": ( + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, " + "`captured` ≤ `mandated` and `refunded` ≤ `captured` per " + "`(iss, mandate_ref)` chain." + ), + "verify_3": ( + "Platform Verification 3: SHOULD, when `event.seller_id` is present, " + "also check per seller that succeeded captures do not exceed that " + "seller's attributed total and that refunds do not exceed that seller's " + "captures." + ), + "verify_4": ( + "Platform Verification 4: SHOULD reconcile each `refund` receipt that " + "carries `event.ref.adjustment_id` against that Order adjustment. A " + "mismatch is a commercial problem, not a cryptographic one: the receipt " + "remains valid." + ), + "business_3": ( + "Business Requirements 3: MUST NOT capture so that `captured` exceeds " + "`mandated`. Any increase in what the buyer pays beyond " + "`mandated` (a tip, an overage, an order change, or a re-authorization " + "above the original amount) MUST be covered by a new closed Payment " + "Mandate from the platform. Movements that spend against the new " + "mandate form their own chain, keyed by its `mandate_ref`." + ), + "business_6": ( + "Business Requirements 6: MUST keep retired public keys resolvable by " + "`kid` for at least the dispute window of the payment method used." + ), + "split_shipments": ( + "Edge Cases, Split shipments: multiple `capture` receipts against the " + "same `mandate_ref`, with `captured` accumulating." + ), + "marketplace": ( + "Edge Cases, Marketplace as merchant of record: the marketplace issues " + "every receipt and sets `event.seller_id`, so a duplicate capture for " + "one seller is detectable even when the chain's totals pass." + ), + "several_mor": ( + "Edge Cases, Several merchants of record in one Order: each has its own " + "mandate and keys, so each `(iss, mandate_ref)` pair is an independent " + "chain." + ), + "partial_refund": ( + "Edge Cases, Partial refunds under a cancellation policy: the refund " + "receipt proves the money movement and cites the cancellation " + "adjustment through `event.ref.adjustment_id`; whether the amount was " + "commercially correct is checked against that adjustment, not inside " + "the receipt." + ), + "pending": ( + "Edge Cases, Pending movements: a movement may first be receipted as " + "`pending`. A later receipt in the same chain for the same movement " + "carries `status: succeeded`. Totals change only on the `succeeded` " + "receipt." + ), + "late_network_ref": ( + "Edge Cases, Late network references: when a network reference (for " + "example the Acquirer Reference Number of a refund) is assigned after " + "the movement is receipted, it appears on a follow-up receipt for the " + "same `event.ref`. `network_ref` is optional on every status: a refund " + "processed as a reversal of the original authorization may never have " + "one." + ), +} + + +def _test_only_key(label: str) -> ec.EllipticCurvePrivateKey: + """Derive a TEST-ONLY P-256 private key from a fixed label.""" + seed = hashlib.sha256( + b"UCP conformance TEST-ONLY AP2 receipt key: " + label.encode("utf-8") + ).digest() + order = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 + return ec.derive_private_key( + int.from_bytes(seed, "big") % (order - 1) + 1, ec.SECP256R1() + ) + + +class FixtureSigner: + """Signs receipts with a business's TEST-ONLY key.""" + + def __init__(self, iss: str, kid: str) -> None: + """Derive the key for one `kid` of the business `iss`.""" + self.kid = kid + self._key = _test_only_key(f"{iss} {kid}") + + @property + def jwk(self) -> dict[str, str]: + """The public key, as published in the business's `keys`.""" + numbers = self._key.public_key().public_numbers() + return { + "kty": "EC", + "crv": "P-256", + "kid": self.kid, + "use": "sig", + "alg": "ES256", + "x": v.b64url_encode(numbers.x.to_bytes(32, "big")), + "y": v.b64url_encode(numbers.y.to_bytes(32, "big")), + } + + def sign(self, payload: dict[str, Any]) -> str: + """Return the compact JWS receipt for a payload (Receipt Format).""" + header = {"alg": "ES256", "kid": self.kid, "typ": v.RECEIPT_TYP} + signing_input = ( + v.b64url_encode(_jcs(header)) + "." + v.b64url_encode(_jcs(payload)) + ) + der = self._key.sign( + signing_input.encode("ascii"), + ec.ECDSA(hashes.SHA256(), deterministic_signing=True), + ) + r, s = utils.decode_dss_signature(der) + signature = r.to_bytes(32, "big") + s.to_bytes(32, "big") + return signing_input + "." + v.b64url_encode(signature) + + +def _jcs(value: Any) -> bytes: + """Canonicalize JSON per RFC 8785 (JCS). + + For the values used here (objects with ASCII member names, strings, + integers, booleans and null) sorted members and compact separators are + exactly RFC 8785. Anything else is refused rather than encoded wrongly. + """ + + def check(item: Any) -> None: + if isinstance(item, dict): + for key, value in item.items(): + if not key.isascii(): + raise ValueError(f"non-ASCII member name {key!r}") + check(value) + elif isinstance(item, list): + for value in item: + check(value) + elif isinstance(item, float): + raise ValueError("floats are not used in receipts") + + check(value) + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=False + ).encode("utf-8") + + +def _timestamp(value: str) -> int: + """Seconds since the epoch for an RFC 3339 UTC time ending in `Z`.""" + # fromisoformat accepts a trailing `Z` only from Python 3.11. + parsed = datetime.datetime.fromisoformat(value.removesuffix("Z") + "+00:00") + return int(parsed.timestamp()) + + +class _Chain: + """Issues the receipts of one `(iss, mandate_ref)` chain in order. + + Running totals follow from the events: only succeeded events change + them, `authorization` and `release` move `authorized`, and `captured` is + net of capture reversals. + """ + + def __init__( + self, + signer: FixtureSigner, + iss: str, + token: str, + mandated: int, + order_id: str, + checkout_id: str, + currency: str, + ) -> None: + self.signer = signer + self.iss = iss + self.token = token + self.mandate_ref = v.sha256_ref(token) + self.order_id = order_id + self.checkout_id = checkout_id + self.currency = currency + self.totals = { + "mandated": mandated, + "authorized": 0, + "captured": 0, + "refunded": 0, + } + self.seq = 0 + self.prev: str | None = None + + def issue( + self, + event_type: str, + amount: int, + occurred_at: str, + status: str = "succeeded", + signer: FixtureSigner | None = None, + **extra: Any, + ) -> str: + """Sign the next receipt; `extra` adds optional `event` members.""" + if status == "succeeded": + key = { + "authorization": ("authorized", 1), + "release": ("authorized", -1), + "capture": ("captured", 1), + "capture_reversal": ("captured", -1), + "refund": ("refunded", 1), + }[event_type] + self.totals[key[0]] += key[1] * amount + self.seq += 1 + payload = { + "iss": self.iss, + "iat": _timestamp(occurred_at) + 60, + "order_id": self.order_id, + "checkout_id": self.checkout_id, + "mandate_ref": self.mandate_ref, + "seq": self.seq, + "prev": self.prev, + "event": { + "type": event_type, + "status": status, + "amount": amount, + "currency": self.currency, + "occurred_at": occurred_at, + **extra, + }, + "totals": dict(self.totals), + } + compact = (signer or self.signer).sign(payload) + self.prev = v.sha256_ref(compact) + return compact + + +def _line(line_id: str, amount: int, seller_id: str | None = None) -> dict: + line: dict[str, Any] = {"id": line_id} + if seller_id is not None: + line["seller_id"] = seller_id + line["totals"] = [ + {"type": "subtotal", "amount": amount}, + {"type": "total", "amount": amount}, + ] + return line + + +def _order( + order_id: str, + checkout_id: str, + currency: str, + line_items: list[dict], + totals: list[dict], + receipts: list[str], + adjustments: list[dict] | None = None, + **extra: Any, +) -> dict[str, Any]: + """Build the Order members the verifier reads, receipts in `ap2`.""" + return { + "id": order_id, + "checkout_id": checkout_id, + "currency": currency, + **extra, + "line_items": line_items, + "adjustments": adjustments or [], + "totals": totals, + "ap2": {"receipts": receipts}, + } + + +def _usd_totals(subtotal: int, tax: int, *extra: dict) -> list[dict]: + return [ + {"type": "subtotal", "amount": subtotal}, + {"type": "tax", "amount": tax}, + *extra, + { + "type": "total", + "amount": subtotal + tax + sum(e["amount"] for e in extra), + }, + ] + + +def _fixture( + vector_id: str, + title: str, + test_plan: str | None, + rules: list[str], + signing: str, + issuers: dict[str, list[dict]], + mandates: list[tuple[str, str]], + order: dict[str, Any], + outcomes: list[tuple[int, str]] = (), + warnings: list[tuple[int, str]] = (), + reconciliation: list[tuple[int, str]] = (), + notes: str | None = None, +) -> dict[str, Any]: + """Assemble one fixture document.""" + fixture: dict[str, Any] = { + "id": vector_id, + "title": title, + "test_plan_vector": test_plan, + "spec": [_RULES[r] for r in rules], + "signing": signing, + } + if notes: + fixture["notes"] = notes + fixture["inputs"] = { + "issuers": {iss: {"keys": keys} for iss, keys in issuers.items()}, + "mandates": [ + {"credential_token": token, "business": business} + for token, business in mandates + ], + "order": order, + } + decoded = [] + for compact in order["ap2"]["receipts"]: + header, payload = v.decode_receipt(compact) + decoded.append({"header": header, "payload": payload}) + fixture["decoded_receipts"] = decoded + + def findings(items): + return [{"receipt_index": i, "code": code} for i, code in items] + + fixture["expected"] = { + "outcomes": findings(outcomes), + "warnings": findings(warnings), + "reconciliation": findings(reconciliation), + } + return fixture + + +def _tamper_amount(compact: str, amount: int) -> str: + """Re-encode a receipt's payload with a new amount, keeping the rest.""" + header_b64, _, signature_b64 = compact.split(".") + _, payload = v.decode_receipt(compact) + payload["event"]["amount"] = amount + return ".".join([header_b64, v.b64url_encode(_jcs(payload)), signature_b64]) + + +def _simple_chain( + vector: str, signer: FixtureSigner | None = None, currency: str = "USD" +) -> _Chain: + return _Chain( + signer or FixtureSigner(_MERCHANT, "test_only_2026"), + _MERCHANT, + f"test_only_payment_mandate_{vector}", + 5400, + f"order_{vector}", + f"chk_{vector}", + currency, + ) + + +def _merchant_vector(vector: str, chain: _Chain, **kwargs: Any) -> dict: + """Fixture for a single-merchant USD 54.00 order.""" + receipts = kwargs.pop("receipts") + order = _order( + chain.order_id, + chain.checkout_id, + "USD", + kwargs.pop("line_items", [_line("li_1", 5000)]), + kwargs.pop("totals", _usd_totals(5000, 400)), + receipts, + kwargs.pop("adjustments", None), + ) + return _fixture( + vector, + issuers=kwargs.pop("issuers", {_MERCHANT: [chain.signer.jwk]}), + mandates=kwargs.pop("mandates", [(chain.token, chain.iss)]), + order=order, + signing=_TEST_ONLY_SIGNING, + **kwargs, + ) + + +def _spec_order(receipts: list[str]) -> dict[str, Any]: + """Rebuild the ucp#1109 Order example, reduced to what is verified.""" + return _order( + "order_abc123", + "chk_abc123", + "USD", + [_line("li_shoes", 2800), _line("li_jacket", 2200)], + _usd_totals(5000, 400), + receipts, + ) + + +def _v01() -> dict: + chain = _simple_chain("v01") + receipts = [ + chain.issue("authorization", 5400, "2026-11-09T14:53:20Z"), + chain.issue("capture", 5400, "2026-11-10T02:00:00Z"), + ] + return _merchant_vector( + "v01_single_capture", + chain, + title="A single capture equal to the mandate verifies", + test_plan="1", + rules=["verify_1", "verify_2"], + receipts=receipts, + notes=( + "The ucp#1109 chain has two split captures, so it is vector 2; a " + "single capture of the full mandate needs its own signed receipt." + ), + ) + + +def _v02() -> dict: + return _fixture( + "v02_split_captures", + "Two split captures summing to the mandate verify", + "2", + ["verify_1", "verify_2", "split_shipments"], + _SPEC_SIGNING + " Source: " + SPEC_SOURCE + ".", + {_SPEC_BUSINESS: [_SPEC_KEY]}, + [(_SPEC_TOKEN, _SPEC_BUSINESS)], + _spec_order(list(_SPEC_CHAIN)), + ) + + +def _v03() -> dict: + chain = _simple_chain("v03") + receipts = [ + chain.issue("authorization", 5400, "2026-11-09T14:53:20Z"), + chain.issue("capture", 6000, "2026-11-10T02:00:00Z"), + ] + return _merchant_vector( + "v03_capture_exceeds_mandate", + chain, + title="A capture above the mandate, without a new mandate", + test_plan="3", + rules=["verify_2", "business_3"], + receipts=receipts, + outcomes=[(1, v.RECEIPT_EXCEEDS_MANDATE)], + ) + + +def _v04() -> dict: + signer = FixtureSigner(_MERCHANT, "test_only_2026") + original = _Chain( + signer, + _MERCHANT, + "test_only_payment_mandate_v04_original", + 5400, + "order_v04", + "chk_v04", + "USD", + ) + increase = _Chain( + signer, + _MERCHANT, + "test_only_payment_mandate_v04_increase", + 600, + "order_v04", + "chk_v04", + "USD", + ) + receipts = [ + original.issue("authorization", 5400, "2026-11-09T14:53:20Z"), + original.issue("capture", 5400, "2026-11-10T02:00:00Z"), + increase.issue("authorization", 600, "2026-11-10T03:00:00Z"), + increase.issue("capture", 600, "2026-11-10T03:05:00Z"), + ] + return _merchant_vector( + "v04_increase_second_mandate", + original, + title="An increase covered by a second mandate verifies", + test_plan="4", + rules=["verify_2", "business_3"], + receipts=receipts, + totals=_usd_totals( + 5000, 400, {"type": "fee", "amount": 600, "display_text": "Tip"} + ), + mandates=[ + ("test_only_payment_mandate_v04_original", _MERCHANT), + ("test_only_payment_mandate_v04_increase", _MERCHANT), + ], + notes=( + "The USD 6.00 tip is covered by a second closed Payment Mandate, " + "whose movements form their own chain starting at seq 1." + ), + ) + + +def _v05() -> dict: + receipts = [*_SPEC_CHAIN[:2], _tamper_amount(_SPEC_CHAIN[2], 4400)] + return _fixture( + "v05_tampered_amount", + "A tampered amount gives receipt_invalid_signature", + "5", + ["verify_1"], + _SPEC_SIGNING + " Source: " + SPEC_SOURCE + ".", + {_SPEC_BUSINESS: [_SPEC_KEY]}, + [(_SPEC_TOKEN, _SPEC_BUSINESS)], + _spec_order(receipts), + outcomes=[(2, v.RECEIPT_INVALID_SIGNATURE)], + notes=( + "The ucp#1109 chain with event.amount of the third receipt changed " + "from 2400 to 4400 after signing; header and signature are unchanged." + ), + ) + + +def _v06() -> dict: + return _fixture( + "v06_missing_seq", + "A missing seq gives receipt_sequence_gap", + "6", + ["verify_2"], + _SPEC_SIGNING + " Source: " + SPEC_SOURCE + ".", + {_SPEC_BUSINESS: [_SPEC_KEY]}, + [(_SPEC_TOKEN, _SPEC_BUSINESS)], + _spec_order([_SPEC_CHAIN[0], _SPEC_CHAIN[2]]), + outcomes=[(1, v.RECEIPT_SEQUENCE_GAP)], + notes="The ucp#1109 chain with its seq 2 receipt removed.", + ) + + +def _v07() -> dict: + chain = _simple_chain("v07") + receipts = [ + chain.issue("authorization", 5400, "2026-11-09T14:53:20Z"), + chain.issue("capture", 5400, "2026-11-10T02:00:00Z"), + chain.issue("refund", 6000, "2026-11-12T10:00:00Z"), + ] + return _merchant_vector( + "v07_refund_exceeds_capture", + chain, + title="A refund above captured gives receipt_refund_exceeds_capture", + test_plan="7", + rules=["verify_2"], + receipts=receipts, + outcomes=[(2, v.RECEIPT_REFUND_EXCEEDS_CAPTURE)], + ) + + +def _v08_receipts() -> tuple[_Chain, FixtureSigner, list[str]]: + retired = FixtureSigner(_MERCHANT, "test_only_2025") + current = FixtureSigner(_MERCHANT, "test_only_2026") + chain = _simple_chain("v08", signer=current) + receipts = [ + chain.issue("authorization", 5400, "2026-11-09T14:53:20Z", signer=retired), + chain.issue("capture", 5400, "2026-11-10T02:00:00Z"), + ] + return chain, retired, receipts + + +def _v08() -> dict: + chain, retired, receipts = _v08_receipts() + return _merchant_vector( + "v08_rotated_retained_key", + chain, + title="A receipt signed with a rotated, retained key verifies", + test_plan="8", + rules=["verify_1", "business_6"], + receipts=receipts, + issuers={_MERCHANT: [retired.jwk, chain.signer.jwk]}, + notes=( + "seq 1 is signed with test_only_2025, which was retired before seq 2 " + "but is still published in keys." + ), + ) + + +def _v08_not_retained() -> dict: + chain, _, receipts = _v08_receipts() + return _merchant_vector( + "v08_key_not_retained", + chain, + title="A receipt whose retired key is no longer published", + test_plan=None, + rules=["verify_1", "verify_2", "business_6"], + receipts=receipts, + issuers={_MERCHANT: [chain.signer.jwk]}, + outcomes=[(0, v.RECEIPT_INVALID_SIGNATURE), (1, v.RECEIPT_SEQUENCE_GAP)], + notes=( + "Negative counterpart of v08_rotated_retained_key: test_only_2025 is " + "gone from keys, so seq 1 cannot be verified. It is then not part of " + "the chain, and seq 2 is reported as a gap." + ), + ) + + +def _marketplace_vector(vector: str, steps: list[tuple], **kwargs) -> dict: + signer = FixtureSigner(_MARKETPLACE, "test_only_2026") + chain = _Chain( + signer, + _MARKETPLACE, + f"test_only_payment_mandate_{vector}", + 5400, + f"order_{vector}", + f"chk_{vector}", + "USD", + ) + receipts = [chain.issue(*step[:3], **step[3]) for step in steps] + order = _order( + chain.order_id, + chain.checkout_id, + "USD", + [_line("li_a", 2000, "seller_a"), _line("li_b", 3400, "seller_b")], + [ + {"type": "subtotal", "amount": 5400}, + {"type": "total", "amount": 5400}, + ], + receipts, + sellers={ + "seller_a": {"name": "Seller A"}, + "seller_b": {"name": "Seller B"}, + }, + ) + return _fixture( + vector, + issuers={_MARKETPLACE: [signer.jwk]}, + mandates=[(f"test_only_payment_mandate_{vector}", _MARKETPLACE)], + order=order, + signing=_TEST_ONLY_SIGNING, + **kwargs, + ) + + +def _v09() -> dict: + return _marketplace_vector( + "v09_two_sellers", + [ + ("authorization", 5400, "2026-11-09T14:53:20Z", {}), + ("capture", 2000, "2026-11-10T18:04:00Z", {"seller_id": "seller_a"}), + ("capture", 3400, "2026-11-11T18:04:00Z", {"seller_id": "seller_b"}), + ], + title="Marketplace as merchant of record, two sellers: captures verify", + test_plan="9", + rules=["verify_2", "verify_3", "marketplace"], + ) + + +def _v09_duplicate() -> dict: + return _marketplace_vector( + "v09_duplicate_seller_capture", + [ + ("authorization", 5400, "2026-11-09T14:53:20Z", {}), + ("capture", 2000, "2026-11-10T18:04:00Z", {"seller_id": "seller_a"}), + ("capture", 2000, "2026-11-11T18:04:00Z", {"seller_id": "seller_a"}), + ], + title="A duplicate capture for one seller gives a seller-total warning", + test_plan="9", + rules=["verify_2", "verify_3", "marketplace"], + warnings=[(2, v.RECEIPT_EXCEEDS_SELLER_TOTAL)], + notes=( + "Chain totals pass (captured 4000 <= mandated 5400), but seller_a's " + "captures (4000) exceed its attributed total (2000). The per-seller " + "check is a SHOULD, so this is a warning, not a failed outcome." + ), + ) + + +def _v09_seller_refund() -> dict: + return _marketplace_vector( + "v09_seller_refund_exceeds_captures", + [ + ("authorization", 5400, "2026-11-09T14:53:20Z", {}), + ("capture", 2000, "2026-11-10T18:04:00Z", {"seller_id": "seller_a"}), + ("refund", 1000, "2026-11-12T09:00:00Z", {"seller_id": "seller_b"}), + ], + title="A refund above one seller's captures gives a seller-total warning", + test_plan=None, + rules=["verify_2", "verify_3"], + warnings=[(2, v.RECEIPT_EXCEEDS_SELLER_TOTAL)], + notes=( + "Chain totals pass (refunded 1000 <= captured 2000), but seller_b " + "has no captures. Second half of the per-seller SHOULD." + ), + ) + + +def _two_mor_vector(vector: str, with_mismatch: bool, **kwargs) -> dict: + signer_a = FixtureSigner(_SELLER_A, "test_only_2026") + signer_b = FixtureSigner(_SELLER_B, "test_only_2026") + token_a = f"test_only_payment_mandate_{vector}_seller_a" + token_b = f"test_only_payment_mandate_{vector}_seller_b" + order_id, checkout_id = f"order_{vector}", f"chk_{vector}" + chain_a = _Chain( + signer_a, _SELLER_A, token_a, 2000, order_id, checkout_id, "USD" + ) + chain_b = _Chain( + signer_b, _SELLER_B, token_b, 3400, order_id, checkout_id, "USD" + ) + receipts = [ + chain_a.issue("authorization", 2000, "2026-11-09T14:53:20Z"), + chain_a.issue( + "capture", 2000, "2026-11-10T18:04:00Z", seller_id="seller_a" + ), + chain_b.issue("authorization", 3400, "2026-11-09T14:53:20Z"), + chain_b.issue( + "capture", 3400, "2026-11-10T18:04:00Z", seller_id="seller_b" + ), + ] + if with_mismatch: + # Spends chain A's mandate under seller-b's iss, signed with seller-b's + # own key: the signature verifies, the mandate binding does not. + rogue = _Chain( + signer_b, _SELLER_B, token_a, 2000, order_id, checkout_id, "USD" + ) + rogue.totals["authorized"] = 2000 + receipts.append(rogue.issue("capture", 2000, "2026-11-10T18:04:00Z")) + order = _order( + order_id, + checkout_id, + "USD", + [_line("li_a", 2000, "seller_a"), _line("li_b", 3400, "seller_b")], + [ + {"type": "subtotal", "amount": 5400}, + {"type": "total", "amount": 5400}, + ], + receipts, + sellers={ + "seller_a": {"name": "Seller A", "profile": _SELLER_A}, + "seller_b": {"name": "Seller B", "profile": _SELLER_B}, + }, + ) + return _fixture( + vector, + issuers={_SELLER_A: [signer_a.jwk], _SELLER_B: [signer_b.jwk]}, + mandates=[(token_a, _SELLER_A), (token_b, _SELLER_B)], + order=order, + signing=_TEST_ONLY_SIGNING, + **kwargs, + ) + + +def _v10() -> dict: + return _two_mor_vector( + "v10_two_merchants_of_record", + with_mismatch=False, + title="Two merchants of record in one order: both chains verify", + test_plan="10", + rules=["verify_1", "verify_2", "several_mor"], + ) + + +def _v10_mismatch() -> dict: + return _two_mor_vector( + "v10_iss_mismatch", + with_mismatch=True, + title="A receipt whose iss does not match its mandate", + test_plan="10", + rules=["verify_1", "several_mor"], + outcomes=[(4, v.RECEIPT_MANDATE_UNKNOWN)], + notes=( + "Receipt 4 carries seller A's mandate_ref with iss seller-b and is " + "signed with seller-b's key. Both valid chains still verify." + ), + ) + + +def _lodging_vector(vector: str, refund: int, **kwargs) -> dict: + signer = FixtureSigner(_HOTEL, "test_only_2026") + token = f"test_only_payment_mandate_{vector}" + chain = _Chain( + signer, _HOTEL, token, 60000, f"order_{vector}", f"chk_{vector}", "EUR" + ) + receipts = [ + chain.issue("authorization", 60000, "2026-11-01T09:00:00Z"), + chain.issue("capture", 60000, "2026-11-01T09:00:30Z"), + chain.issue( + "refund", + refund, + "2026-11-14T16:00:00Z", + ref={"adjustment_id": "adj_cancel_1"}, + ), + ] + adjustment = { + "id": "adj_cancel_1", + "type": "cancellation", + "occurred_at": "2026-11-14T15:30:00Z", + "status": "completed", + "totals": [{"type": "total", "amount": -45000}], + "description": ( + "Cancelled under the booking's cancellation policy: EUR 150.00 " + "penalty retained, EUR 450.00 refundable." + ), + } + order = _order( + chain.order_id, + chain.checkout_id, + "EUR", + [_line("li_room", 60000)], + [ + {"type": "subtotal", "amount": 60000}, + {"type": "total", "amount": 60000}, + ], + receipts, + adjustments=[adjustment], + ) + return _fixture( + vector, + issuers={_HOTEL: [signer.jwk]}, + mandates=[(token, _HOTEL)], + order=order, + signing=_TEST_ONLY_SIGNING, + **kwargs, + ) + + +def _v11() -> dict: + return _lodging_vector( + "v11_lodging_partial_refund", + 45000, + title="Lodging partial refund matching the cancellation adjustment", + test_plan="11", + rules=["verify_2", "verify_4", "partial_refund"], + ) + + +def _v12() -> dict: + return _lodging_vector( + "v12_lodging_refund_mismatch", + 30000, + title="Lodging refund that disagrees with the cancellation adjustment", + test_plan="12", + rules=["verify_2", "verify_4", "partial_refund"], + reconciliation=[(2, v.RECONCILIATION_ADJUSTMENT_MISMATCH)], + notes=( + "The receipt chain verifies; the refund (EUR 300.00) disagrees with " + "the adjustment it cites (EUR 450.00). Reported as a reconciliation " + "finding, separately from the receipt outcomes." + ), + ) + + +def _pending_refund_vector(vector: str, settled: str, **kwargs) -> dict: + """Refund receipted pending, then succeeded, for the same event.ref.""" + network_ref = kwargs.pop("network_ref", None) + chain = _simple_chain(vector) + ref = {"ref": {"adjustment_id": "adj_refund_1"}} + receipts = [ + chain.issue("authorization", 5400, "2026-11-09T14:53:20Z"), + chain.issue("capture", 5400, "2026-11-10T02:00:00Z"), + chain.issue("refund", 5400, kwargs.pop("requested"), "pending", **ref), + chain.issue( + "refund", + 5400, + settled, + **ref, + **({"network_ref": network_ref} if network_ref else {}), + ), + ] + adjustment = { + "id": "adj_refund_1", + "type": "refund", + "occurred_at": "2026-11-10T04:00:00Z", + "status": "completed", + "totals": [{"type": "total", "amount": -5400}], + } + return _merchant_vector( + vector, + chain, + receipts=receipts, + adjustments=[adjustment], + **kwargs, + ) + + +def _refund_delayed_network_ref() -> dict: + return _pending_refund_vector( + "refund_delayed_network_ref", + "2026-11-17T10:00:00Z", + requested="2026-11-10T04:00:00Z", + network_ref="74000000000000000001063", + title="Refund receipted pending, then succeeded with a late network_ref", + test_plan=None, + rules=["verify_2", "pending", "late_network_ref"], + notes=( + "seq 3 is pending and leaves totals unchanged; seq 4, for the same " + "event.ref, is succeeded, carries network_ref (an ARN assigned days " + "later) and is the only receipt that changes refunded." + ), + ) + + +def _refund_reversal() -> dict: + return _pending_refund_vector( + "refund_reversal_no_network_ref", + "2026-11-10T04:02:00Z", + requested="2026-11-10T04:00:00Z", + title="Refund processed as a reversal: succeeded without network_ref", + test_plan=None, + rules=["verify_2", "pending", "late_network_ref"], + notes=( + "The refund settles as a reversal of the authorization shortly after " + "capture, so no network reference is ever assigned: the succeeded " + "receipt for the same event.ref has no network_ref, and is valid." + ), + ) + + +_BUILDERS = ( + _v01, + _v02, + _v03, + _v04, + _v05, + _v06, + _v07, + _v08, + _v08_not_retained, + _v09, + _v09_duplicate, + _v09_seller_refund, + _v10, + _v10_mismatch, + _v11, + _v12, + _refund_delayed_network_ref, + _refund_reversal, +) + + +def build_fixtures() -> dict[str, str]: + """Return every fixture file name with its exact content.""" + files = {} + for build in _BUILDERS: + fixture = build() + text = json.dumps(fixture, indent=2, ensure_ascii=False) + "\n" + files[f"{fixture['id']}.json"] = text + return files + + +def main(argv: list[str] | None = None) -> int: + """Write the fixtures, or with --check report whether they are current.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--check", + action="store_true", + help="Exit non-zero if a committed fixture differs from the output.", + ) + args = parser.parse_args(argv) + + files = build_fixtures() + stale = sorted( + name + for name, text in files.items() + if not (FIXTURE_DIR / name).is_file() + or (FIXTURE_DIR / name).read_text(encoding="utf-8") != text + ) + extra = sorted( + p.name for p in FIXTURE_DIR.glob("*.json") if p.name not in files + ) + if args.check: + for name in stale: + sys.stderr.write(f"stale: {name}\n") + for name in extra: + sys.stderr.write(f"not generated: {name}\n") + return 1 if stale or extra else 0 + + FIXTURE_DIR.mkdir(parents=True, exist_ok=True) + for name in stale: + (FIXTURE_DIR / name).write_text(files[name], encoding="utf-8") + sys.stdout.write(f"wrote {name}\n") + for name in extra: + sys.stderr.write(f"not generated, left in place: {name}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/common/payments/ap2_receipt_vectors_test.py b/common/payments/ap2_receipt_vectors_test.py new file mode 100644 index 0000000..707763b --- /dev/null +++ b/common/payments/ap2_receipt_vectors_test.py @@ -0,0 +1,315 @@ +# Copyright 2026 UCP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Platform-side vectors for AP2 Order receipts (ucp#1063, ucp#1109). + +Each fixture in fixtures/ap2_order_receipts/ is an Order with its receipts, +the business keys and the Payment Mandates a platform holds, and the exact +findings verification must produce. These tests need no server: they check +the vectors and the verifier in ap2_receipt_verifier.py against each other. +ap2_order_receipts_test.py applies the same verifier to receipts a live +business issues. +""" + +import json +from pathlib import Path +from typing import Any + +from absl.testing import absltest, parameterized +from common.payments import ap2_receipt_fixtures as fixtures +from common.payments import ap2_receipt_verifier as v + +_FIXTURE_PATHS = sorted(fixtures.FIXTURE_DIR.glob("*.json")) + +# `receipt_verification_outcome` in payment_ap2_mandate.json (ucp#1109). +_SPEC_OUTCOMES = { + "receipt_invalid_signature", + "receipt_sequence_gap", + "receipt_exceeds_mandate", + "receipt_refund_exceeds_capture", + "receipt_exceeds_seller_total", + "receipt_mandate_unknown", + "reconciliation_adjustment_mismatch", +} + + +def _load(path: Path) -> dict[str, Any]: + with path.open(encoding="utf-8") as f: + return json.load(f) + + +def _verify(fixture: dict[str, Any]) -> v.VerificationResult: + inputs = fixture["inputs"] + return v.verify_order_receipts( + inputs["order"], + {iss: issuer["keys"] for iss, issuer in inputs["issuers"].items()}, + [ + v.Mandate(m["credential_token"], m["business"]) + for m in inputs["mandates"] + ], + ) + + +def _as_expected(findings: list[v.Finding]) -> list[dict[str, Any]]: + return [{"receipt_index": f.receipt_index, "code": f.code} for f in findings] + + +class Ap2ReceiptVectorsTest(parameterized.TestCase): + """Runs every vector through the platform-side verifier.""" + + def test_fixtures_are_present(self) -> None: + """The fixture directory holds the generated vectors.""" + self.assertNotEmpty( + _FIXTURE_PATHS, f"no fixtures in {fixtures.FIXTURE_DIR}" + ) + + def test_fixtures_match_generator(self) -> None: + """The committed fixtures are exactly what the generator produces. + + Regenerate with `uv run python -m common.payments.ap2_receipt_fixtures`. + """ + generated = fixtures.build_fixtures() + self.assertCountEqual(generated, [p.name for p in _FIXTURE_PATHS]) + for path in _FIXTURE_PATHS: + self.assertEqual( + path.read_text(encoding="utf-8"), + generated[path.name], + f"{path.name} differs from the generator output", + ) + + def test_test_plan_is_covered(self) -> None: + """Vectors 1-12 of the ucp#1063 test plan each have a fixture.""" + covered = {_load(p)["test_plan_vector"] for p in _FIXTURE_PATHS} + self.assertContainsSubset({str(n) for n in range(1, 13)}, covered) + + def test_every_outcome_is_exercised(self) -> None: + """Each `receipt_verification_outcome` value is expected somewhere.""" + seen = set() + for path in _FIXTURE_PATHS: + for group in _load(path)["expected"].values(): + seen.update(finding["code"] for finding in group) + self.assertEqual(seen, _SPEC_OUTCOMES) + + @parameterized.named_parameters((path.stem, path) for path in _FIXTURE_PATHS) + def test_vector(self, path: Path) -> None: + """The verifier reports exactly the fixture's expected findings.""" + fixture = _load(path) + result = _verify(fixture) + expected = fixture["expected"] + self.assertEqual( + _as_expected(result.outcomes), expected["outcomes"], "outcomes" + ) + self.assertEqual( + _as_expected(result.warnings), expected["warnings"], "warnings" + ) + self.assertEqual( + _as_expected(result.reconciliation), + expected["reconciliation"], + "reconciliation", + ) + + @parameterized.named_parameters((path.stem, path) for path in _FIXTURE_PATHS) + def test_decoded_receipts_match(self, path: Path) -> None: + """The decoded copy in each fixture is the receipts' real content.""" + fixture = _load(path) + decoded = [] + for compact in fixture["inputs"]["order"]["ap2"]["receipts"]: + header, payload = v.decode_receipt(compact) + decoded.append({"header": header, "payload": payload}) + self.assertEqual(decoded, fixture["decoded_receipts"]) + + @parameterized.named_parameters( + (path.stem, path) + for path in _FIXTURE_PATHS + if not any(_load(path)["expected"].values()) + ) + def test_totals_change_only_on_succeeded(self, path: Path) -> None: + """In each valid vector the stated totals follow from the events. + + receipt_event.status: "Only `succeeded` events change the running + totals." A receipt that is not succeeded repeats the previous totals + of its chain. + """ + result = _verify(_load(path)) + previous: dict[v.ChainKey, dict[str, int]] = {} + for receipt in result.verified: + totals = receipt.payload["totals"] + self.assertEqual( + (totals["captured"], totals["refunded"]), + (receipt.derived_totals.captured, receipt.derived_totals.refunded), + f"receipt {receipt.index}", + ) + if receipt.payload["event"]["status"] != "succeeded": + self.assertEqual( + totals, previous[receipt.chain], f"receipt {receipt.index}" + ) + previous[receipt.chain] = totals + + @parameterized.named_parameters( + ("delayed_network_ref", "refund_delayed_network_ref", True), + ("reversal_no_network_ref", "refund_reversal_no_network_ref", False), + ) + def test_pending_refund_then_succeeded( + self, vector_id: str, has_network_ref: bool + ) -> None: + """A pending refund is followed by a succeeded one for the same ref. + + Edge Cases, "Pending movements" and "Late network references": + `network_ref` is optional on every status, so the succeeded receipt + carries it only when the network assigned one. + """ + result = _verify(_load(fixtures.FIXTURE_DIR / f"{vector_id}.json")) + self.assertEmpty(result.outcomes) + pending, succeeded = result.verified[-2:] + pending_event = pending.payload["event"] + succeeded_event = succeeded.payload["event"] + self.assertEqual(pending_event["type"], "refund") + self.assertEqual(pending_event["status"], "pending") + self.assertNotIn("network_ref", pending_event) + self.assertEqual(succeeded_event["status"], "succeeded") + self.assertEqual(succeeded_event["ref"], pending_event["ref"]) + self.assertEqual(succeeded.payload["seq"], pending.payload["seq"] + 1) + self.assertEqual(pending.payload["totals"]["refunded"], 0) + self.assertEqual( + succeeded.payload["totals"]["refunded"], succeeded_event["amount"] + ) + self.assertEqual("network_ref" in succeeded_event, has_network_ref) + + +class Ap2ReceiptMutationTest(absltest.TestCase): + """Changes to a valid chain that the verifier must reject. + + Starts from the ucp#1109 chain (v02_split_captures), which verifies. + """ + + def setUp(self) -> None: + """Load the valid ucp#1109 chain.""" + super().setUp() + self.fixture = _load(fixtures.FIXTURE_DIR / "v02_split_captures.json") + self.receipts = self.fixture["inputs"]["order"]["ap2"]["receipts"] + + def _outcomes(self, receipts: list[str]) -> list[tuple[int, str]]: + self.fixture["inputs"]["order"]["ap2"]["receipts"] = receipts + return [(f.receipt_index, f.code) for f in _verify(self.fixture).outcomes] + + def test_unchanged_chain_verifies(self) -> None: + """The starting point has no findings.""" + self.assertEqual(self._outcomes(list(self.receipts)), []) + + def test_flipped_signature_byte(self) -> None: + """A changed signature character invalidates the signature.""" + last = self.receipts[2] + flipped = last[:-5] + ("A" if last[-5] != "A" else "B") + last[-4:] + self.assertEqual( + self._outcomes([*self.receipts[:2], flipped]), + [(2, v.RECEIPT_INVALID_SIGNATURE)], + ) + + def test_flipped_payload_byte(self) -> None: + """A changed payload character invalidates the signature.""" + header, payload, signature = self.receipts[1].split(".") + index = payload.index("6") # inside the encoded payload + payload = payload[:index] + "7" + payload[index + 1 :] + self.assertEqual( + self._outcomes( + [self.receipts[0], f"{header}.{payload}.{signature}", self.receipts[2]] + )[0], + (1, v.RECEIPT_INVALID_SIGNATURE), + ) + + def test_reordered_receipts(self) -> None: + """Receipts out of `seq` order are a sequence gap.""" + self.assertIn( + (1, v.RECEIPT_SEQUENCE_GAP), + self._outcomes([self.receipts[0], self.receipts[2], self.receipts[1]]), + ) + + def test_repeated_receipt(self) -> None: + """A repeated `seq` is a sequence gap.""" + self.assertEqual( + self._outcomes([*self.receipts, self.receipts[2]]), + [(3, v.RECEIPT_SEQUENCE_GAP)], + ) + + def test_unknown_issuer_key(self) -> None: + """A `kid` that does not resolve in the keys of `iss` cannot verify.""" + issuers = self.fixture["inputs"]["issuers"] + for issuer in issuers.values(): + issuer["keys"] = [dict(k, kid="other_kid") for k in issuer["keys"]] + self.assertEqual( + self._outcomes(list(self.receipts))[0], + (0, v.RECEIPT_INVALID_SIGNATURE), + ) + + def test_unknown_mandate(self) -> None: + """A receipt whose `mandate_ref` the platform never sent is unknown.""" + self.fixture["inputs"]["mandates"][0]["credential_token"] = "other" + self.assertEqual( + self._outcomes(list(self.receipts)), + [(i, v.RECEIPT_MANDATE_UNKNOWN) for i in range(3)], + ) + + def test_mandate_covers_another_business(self) -> None: + """A mandate that covers another business makes `iss` mismatch.""" + self.fixture["inputs"]["mandates"][0]["business"] = ( + "https://other.example/.well-known/ucp" + ) + self.assertEqual( + self._outcomes(list(self.receipts)), + [(i, v.RECEIPT_MANDATE_UNKNOWN) for i in range(3)], + ) + + def test_not_a_compact_jws(self) -> None: + """A receipt that is not a compact JWS cannot be verified.""" + self.assertEqual( + self._outcomes([*self.receipts, "not-a-jws"]), + [(3, v.RECEIPT_INVALID_SIGNATURE)], + ) + + def test_signed_receipt_missing_members(self) -> None: + """A validly signed payload without required members is malformed. + + The specification defines no outcome for it. It is recorded apart, and + the other receipts are still verified. + """ + iss = "https://merchant.example/.well-known/ucp" + signer = fixtures.FixtureSigner(iss, "test_only_2026") + receipt = signer.sign({"iss": iss, "seq": "1"}) + self.fixture["inputs"]["issuers"][iss] = {"keys": [signer.jwk]} + self.fixture["inputs"]["order"]["ap2"]["receipts"] = [ + *self.receipts, + receipt, + ] + result = _verify(self.fixture) + self.assertEqual(result.outcomes, []) + self.assertEqual([i for i, _ in result.malformed], [3]) + self.assertRegex(result.malformed[0][1], "mandate_ref.*seq") + self.assertLen(result.verified, 3) + + def test_receipt_that_is_not_a_string(self) -> None: + """A non-string entry in `ap2.receipts` cannot be verified.""" + self.assertEqual( + self._outcomes([*self.receipts, {"not": "a receipt"}]), + [(3, v.RECEIPT_INVALID_SIGNATURE)], + ) + + def test_seller_not_in_sellers_map_is_not_checked(self) -> None: + """An unresolved `seller_id` makes attribution unavailable (ucp#1018).""" + fixture = _load(fixtures.FIXTURE_DIR / "v09_duplicate_seller_capture.json") + del fixture["inputs"]["order"]["sellers"]["seller_a"] + self.assertEqual(_verify(fixture).warnings, []) + + +if __name__ == "__main__": + absltest.main() diff --git a/common/payments/ap2_receipt_verifier.py b/common/payments/ap2_receipt_verifier.py new file mode 100644 index 0000000..f5e3bc4 --- /dev/null +++ b/common/payments/ap2_receipt_verifier.py @@ -0,0 +1,573 @@ +# Copyright 2026 UCP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Platform-side verifier for AP2 Order receipts. + +Implements the checks in the "Order Receipts" section of the AP2 Mandates +extension (docs/specification/payment/extensions/ap2-mandates.md, as proposed +in Universal-Commerce-Protocol/ucp#1109). Section names in the comments below +refer to that document. + +The verifier takes what a platform holds after checkout: + +* the Order, with its receipts in `ap2.receipts`; +* the `keys` of each business profile, keyed by profile URI; +* the Payment Mandates it sent, each with the profile URI of the business + whose checkout the mandate covers. + +It reports three groups of findings, kept apart on purpose: + +* `outcomes`: the MUST checks of "Platform Verification" 1 and 2; +* `warnings`: the per-seller SHOULD of "Platform Verification" 3 + (`receipt_exceeds_seller_total`); +* `reconciliation`: the SHOULD of "Platform Verification" 4 + (`reconciliation_adjustment_mismatch`). It is commercial, not + cryptographic, so a receipt it flags stays valid. + +Only ECDSA is implemented (ES256, ES384, ES512): the extension's algorithm +rule follows AP2 v0.2, which requires it ("Cryptographic Requirements"). + +Where the specification leaves a choice open, this verifier: + +* reports a receipt whose `kid` does not resolve in the `keys` of `iss`, or + whose `iss` has no known keys, as `receipt_invalid_signature` (its + signature "cannot be verified"); +* leaves a receipt that fails the signature or mandate binding check out of + its chain, so the next receipt in that chain is a sequence gap; +* reconciles a refund against the magnitude of the cited adjustment's + `total`, because adjustment totals are signed and receipt amounts are not; +* checks a seller only when it resolves in `sellers` and has attributed + line items; +* evaluates both total invariants on the totals each receipt states, as + Platform Verification 2 is written; `derived_totals` exposes what the + chain's events add up to, but a difference has no outcome; +* records a signed receipt that is not a Receipt Payload in `malformed` + rather than as an outcome, since no outcome covers it. +""" + +import base64 +from collections.abc import Iterable, Mapping +import dataclasses +import hashlib +import json +from typing import Any + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, utils + +# "Receipt Format": the `typ` every receipt header carries. +RECEIPT_TYP = "ucp-ap2-receipt+jwt" + +# `receipt_verification_outcome` in payment_ap2_mandate.json. +RECEIPT_INVALID_SIGNATURE = "receipt_invalid_signature" +RECEIPT_SEQUENCE_GAP = "receipt_sequence_gap" +RECEIPT_EXCEEDS_MANDATE = "receipt_exceeds_mandate" +RECEIPT_REFUND_EXCEEDS_CAPTURE = "receipt_refund_exceeds_capture" +RECEIPT_EXCEEDS_SELLER_TOTAL = "receipt_exceeds_seller_total" +RECEIPT_MANDATE_UNKNOWN = "receipt_mandate_unknown" +RECONCILIATION_ADJUSTMENT_MISMATCH = "reconciliation_adjustment_mismatch" + +# `required` of `receipt_payload` in payment_ap2_mandate.json. +REQUIRED_PAYLOAD_MEMBERS = ( + "iss", + "iat", + "order_id", + "mandate_ref", + "seq", + "prev", + "event", + "totals", +) +# `required` of `receipt_event` and `receipt_totals`. +REQUIRED_EVENT_MEMBERS = ("type", "status", "amount", "currency", "occurred_at") +REQUIRED_TOTALS_MEMBERS = ("mandated", "authorized", "captured", "refunded") + +# JWS `alg` -> (JWK `crv`, hash, byte length of each of r and s). +_ECDSA_ALGORITHMS: dict[str, tuple[str, type[hashes.HashAlgorithm], int]] = { + "ES256": ("P-256", hashes.SHA256, 32), + "ES384": ("P-384", hashes.SHA384, 48), + "ES512": ("P-521", hashes.SHA512, 66), +} +_CURVES: dict[str, ec.EllipticCurve] = { + "P-256": ec.SECP256R1(), + "P-384": ec.SECP384R1(), + "P-521": ec.SECP521R1(), +} + +ChainKey = tuple[str, str] + + +@dataclasses.dataclass(frozen=True) +class Finding: + """One finding about one receipt. + + Attributes: + receipt_index: Position of the receipt in the Order's `ap2.receipts`. + code: A `receipt_verification_outcome` value. + detail: Human-readable explanation. + + """ + + receipt_index: int + code: str + detail: str + + +@dataclasses.dataclass(frozen=True) +class Totals: + """`captured` and `refunded` derived from a chain's succeeded events.""" + + captured: int + refunded: int + + +@dataclasses.dataclass(frozen=True) +class VerifiedReceipt: + """A receipt whose signature and mandate binding both verified.""" + + index: int + compact: str + header: dict[str, Any] + payload: dict[str, Any] + derived_totals: Totals + + @property + def chain(self) -> ChainKey: + """The `(iss, mandate_ref)` chain the receipt belongs to.""" + return (self.payload["iss"], self.payload["mandate_ref"]) + + +@dataclasses.dataclass +class VerificationResult: + """Findings for one Order, grouped as described in the module docstring.""" + + outcomes: list[Finding] = dataclasses.field(default_factory=list) + warnings: list[Finding] = dataclasses.field(default_factory=list) + reconciliation: list[Finding] = dataclasses.field(default_factory=list) + verified: list[VerifiedReceipt] = dataclasses.field(default_factory=list) + # Receipts that verify but are not a Receipt Payload, as (index, detail). + # The specification defines no outcome for them; they join no chain. + malformed: list[tuple[int, str]] = dataclasses.field(default_factory=list) + + +@dataclasses.dataclass(frozen=True) +class Mandate: + """A closed Payment Mandate the platform sent at `complete_checkout`. + + Attributes: + credential_token: The exact string sent in + `payment.instruments[*].credential.token`. + business: Profile URI of the business that signed the checkout the + mandate covers (its `ap2.merchant_authorization`). + + """ + + credential_token: str + business: str + + @property + def mandate_ref(self) -> str: + """The `mandate_ref` a receipt spending against this mandate carries.""" + return sha256_ref(self.credential_token) + + +def b64url_decode(value: str) -> bytes: + """Decode unpadded base64url, rejecting other alphabets.""" + if not value or any( + c not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" + for c in value + ): + raise ValueError("not unpadded base64url") + return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + + +def b64url_encode(data: bytes) -> str: + """Encode bytes as unpadded base64url.""" + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def sha256_ref(artifact: str) -> str: + """Hash an artifact's exact UTF-8 bytes ("Hashes and Chaining"). + + `mandate_ref` and `prev` both use this format: `sha-256:` followed by the + unpadded base64url SHA-256 digest. + """ + digest = hashlib.sha256(artifact.encode("utf-8")).digest() + return "sha-256:" + b64url_encode(digest) + + +def public_key_from_jwk(jwk: Mapping[str, Any]) -> ec.EllipticCurvePublicKey: + """Load an EC public key from a JWK (RFC 7517).""" + if jwk.get("kty") != "EC" or jwk.get("crv") not in _CURVES: + raise ValueError(f"unsupported JWK: kty={jwk.get('kty')}") + numbers = ec.EllipticCurvePublicNumbers( + int.from_bytes(b64url_decode(jwk["x"]), "big"), + int.from_bytes(b64url_decode(jwk["y"]), "big"), + _CURVES[jwk["crv"]], + ) + return numbers.public_key() + + +def decode_receipt(compact: str) -> tuple[dict[str, Any], dict[str, Any]]: + """Split a compact JWS receipt into its decoded header and payload.""" + if not isinstance(compact, str): + raise ValueError("a receipt is a string") + parts = compact.split(".") + if len(parts) != 3: + raise ValueError("a receipt is a compact JWS with three segments") + header = json.loads(b64url_decode(parts[0])) + payload = json.loads(b64url_decode(parts[1])) + if not isinstance(header, dict) or not isinstance(payload, dict): + raise ValueError("JWS header and payload must be JSON objects") + return header, payload + + +def _check_signature( + compact: str, + header: Mapping[str, Any], + issuer_keys: Iterable[Mapping[str, Any]] | None, +) -> str | None: + """Return why the signature cannot be verified, or None if it verifies. + + "Receipt Format": the header carries `alg` per the extension's algorithm + rule, `kid` resolving in the issuing business's `keys`, and `typ`. + "Platform Verification" 1: verify against the `keys` of the business named + in `iss`. + """ + if header.get("typ") != RECEIPT_TYP: + return f"header typ is {header.get('typ')!r}, expected {RECEIPT_TYP!r}" + alg = header.get("alg") + if alg not in _ECDSA_ALGORITHMS: + return f"header alg {alg!r} is not ES256, ES384 or ES512" + if issuer_keys is None: + return "no keys are known for the business named in iss" + kid = header.get("kid") + jwk = next((k for k in issuer_keys if kid and k.get("kid") == kid), None) + if jwk is None: + return f"kid {header.get('kid')!r} does not resolve in the keys of iss" + crv, hash_cls, size = _ECDSA_ALGORITHMS[alg] + if jwk.get("crv") != crv or jwk.get("alg", alg) != alg: + return f"key {jwk.get('kid')!r} cannot verify {alg}" + + signing_input, _, signature_b64 = compact.rpartition(".") + try: + signature = b64url_decode(signature_b64) + if len(signature) != 2 * size: + return "signature has the wrong length for the algorithm" + der = utils.encode_dss_signature( + int.from_bytes(signature[:size], "big"), + int.from_bytes(signature[size:], "big"), + ) + public_key_from_jwk(jwk).verify( + der, signing_input.encode("ascii"), ec.ECDSA(hash_cls()) + ) + except (InvalidSignature, KeyError, TypeError, ValueError): + return "signature does not verify" + return None + + +def _payload_problems(payload: Mapping[str, Any]) -> list[str]: + """List required members a payload lacks or has with the wrong type. + + Checks the members the verifier reads against `receipt_payload`, + `receipt_event` and `receipt_totals`. + """ + event = payload.get("event") + totals = payload.get("totals") + expected: dict[str, tuple[Any, type | tuple[type, ...]]] = { + "iss": (payload.get("iss"), str), + "mandate_ref": (payload.get("mandate_ref"), str), + "seq": (payload.get("seq"), int), + "prev": (payload.get("prev"), (str, type(None))), + "event": (event, dict), + "totals": (totals, dict), + } + if isinstance(event, dict): + for member in REQUIRED_EVENT_MEMBERS: + kind = int if member == "amount" else str + expected[f"event.{member}"] = (event.get(member), kind) + if isinstance(totals, dict): + for member in REQUIRED_TOTALS_MEMBERS: + expected[f"totals.{member}"] = (totals.get(member), int) + problems = [m for m in REQUIRED_PAYLOAD_MEMBERS if m not in payload] + problems += [ + name + for name, (value, kind) in expected.items() + if name.split(".")[0] in payload + and (not isinstance(value, kind) or isinstance(value, bool)) + ] + return problems + + +def _seller_of_line(line_item: Mapping[str, Any], order: Mapping[str, Any]): + """Return the seller of record of an Order line item. + + Seller attribution (ucp#1018): `line_items[].seller_id` overrides the + order-level `seller_id`. + """ + return line_item.get("seller_id", order.get("seller_id")) + + +def _attributed_totals(order: Mapping[str, Any]) -> dict[str, int]: + """Sum each seller's line item `total` amounts.""" + totals: dict[str, int] = {} + for line_item in order.get("line_items", []): + seller = _seller_of_line(line_item, order) + if seller is None: + continue + amount = sum( + t["amount"] + for t in line_item.get("totals", []) + if t.get("type") == "total" + ) + totals[seller] = totals.get(seller, 0) + amount + return totals + + +def _adjustment_amount(adjustment: Mapping[str, Any]) -> int | None: + """Return the magnitude of an adjustment's `total`, if it has one. + + Adjustment totals are signed, negative for money returned to the buyer + (adjustment.json), while a receipt `amount` is always non-negative. + """ + totals = [ + t["amount"] + for t in adjustment.get("totals", []) + if t.get("type") == "total" + ] + return abs(totals[0]) if len(totals) == 1 else None + + +def verify_order_receipts( + order: Mapping[str, Any], + issuer_keys: Mapping[str, Iterable[Mapping[str, Any]]], + mandates: Iterable[Mandate], +) -> VerificationResult: + """Verify every receipt in `order["ap2"]["receipts"]`. + + Args: + order: The Order, carrying its receipts in `ap2.receipts`. + issuer_keys: The `keys` of each known business profile, by profile URI. + mandates: The Payment Mandates the platform sent for this Order. + + Returns: + The findings, grouped into outcomes, warnings and reconciliation. + + """ + result = VerificationResult() + mandates_by_ref = {m.mandate_ref: m for m in mandates} + # Last verified receipt and derived totals of each (iss, mandate_ref) chain. + chain_tail: dict[ChainKey, VerifiedReceipt] = {} + + receipts = (order.get("ap2") or {}).get("receipts", []) + for index, compact in enumerate(receipts): + try: + header, payload = decode_receipt(compact) + except ValueError as exc: + result.outcomes.append( + Finding(index, RECEIPT_INVALID_SIGNATURE, f"not a compact JWS: {exc}") + ) + continue + + # Platform Verification 1: the signature, against the keys of `iss`. + iss = payload.get("iss") + keys = issuer_keys.get(iss) if isinstance(iss, str) else None + reason = _check_signature(compact, header, keys) + if reason is not None: + result.outcomes.append(Finding(index, RECEIPT_INVALID_SIGNATURE, reason)) + continue + problems = _payload_problems(payload) + if problems: + result.malformed.append( + (index, "missing or mistyped members: " + ", ".join(problems)) + ) + continue + + # Platform Verification 1: `iss` must be the business that signed the + # checkout covered by `mandate_ref`; the outcome table adds the case of + # an unknown `mandate_ref`. Business Requirements 2 says the same from + # the business side. + mandate = mandates_by_ref.get(payload["mandate_ref"]) + if mandate is None: + result.outcomes.append( + Finding(index, RECEIPT_MANDATE_UNKNOWN, "mandate_ref is unknown") + ) + continue + if mandate.business != payload["iss"]: + result.outcomes.append( + Finding( + index, + RECEIPT_MANDATE_UNKNOWN, + f"iss {payload['iss']} is not the business the mandate covers " + f"({mandate.business})", + ) + ) + continue + + # Hashes and Chaining / Platform Verification 2: one chain per + # (iss, mandate_ref). `seq` starts at 1 and increases by exactly 1; + # `prev` is the hash of the previous receipt's compact JWS, null at 1. + chain: ChainKey = (payload["iss"], payload["mandate_ref"]) + tail = chain_tail.get(chain) + expected_seq = 1 if tail is None else tail.payload["seq"] + 1 + expected_prev = None if tail is None else sha256_ref(tail.compact) + if payload["seq"] != expected_seq: + result.outcomes.append( + Finding( + index, + RECEIPT_SEQUENCE_GAP, + f"seq {payload['seq']}, expected {expected_seq}", + ) + ) + elif payload["prev"] != expected_prev: + result.outcomes.append( + Finding( + index, + RECEIPT_SEQUENCE_GAP, + f"prev {payload['prev']} does not match {expected_prev}", + ) + ) + + # Platform Verification 2: both total invariants, per chain, on the + # running totals the receipt states. + totals = payload["totals"] + if totals["captured"] > totals["mandated"]: + result.outcomes.append( + Finding( + index, + RECEIPT_EXCEEDS_MANDATE, + f"captured {totals['captured']} > mandated {totals['mandated']}", + ) + ) + if totals["refunded"] > totals["captured"]: + result.outcomes.append( + Finding( + index, + RECEIPT_REFUND_EXCEEDS_CAPTURE, + f"refunded {totals['refunded']} > captured {totals['captured']}", + ) + ) + + # receipt_event.status: only `succeeded` events change the running + # totals (Edge Cases, "Pending movements"). `captured` is net of capture + # reversals (receipt_totals). + previous = Totals(0, 0) if tail is None else tail.derived_totals + event = payload["event"] + captured, refunded = previous.captured, previous.refunded + if event["status"] == "succeeded": + if event["type"] == "capture": + captured += event["amount"] + elif event["type"] == "capture_reversal": + captured -= event["amount"] + elif event["type"] == "refund": + refunded += event["amount"] + verified = VerifiedReceipt( + index, compact, header, payload, Totals(captured, refunded) + ) + chain_tail[chain] = verified + result.verified.append(verified) + + result.warnings.extend(_check_sellers(order, result.verified)) + result.reconciliation.extend(_reconcile(order, result.verified)) + return result + + +def _check_sellers( + order: Mapping[str, Any], verified: Iterable[VerifiedReceipt] +) -> list[Finding]: + """Platform Verification 3 (SHOULD), reported as warnings. + + When `event.seller_id` is present: succeeded captures must not exceed that + seller's attributed total, and refunds must not exceed that seller's + captures. A `seller_id` that does not resolve in the Order's `sellers` map + is not checked: ucp#1018 says the platform "MUST treat seller attribution + for that scope as unavailable". Neither is a seller with no attributed + line items, which has no attributed total to compare with. + """ + sellers = order.get("sellers") or {} + attributed = { + seller: total + for seller, total in _attributed_totals(order).items() + if seller in sellers + } + captured: dict[str, int] = {} + refunded: dict[str, int] = {} + findings = [] + for receipt in verified: + event = receipt.payload["event"] + seller = event.get("seller_id") + if seller is None or seller not in attributed: + continue + if event["status"] != "succeeded": + continue + if event["type"] == "capture": + captured[seller] = captured.get(seller, 0) + event["amount"] + elif event["type"] == "capture_reversal": + captured[seller] = captured.get(seller, 0) - event["amount"] + elif event["type"] == "refund": + refunded[seller] = refunded.get(seller, 0) + event["amount"] + else: + continue + if captured.get(seller, 0) > attributed[seller]: + findings.append( + Finding( + receipt.index, + RECEIPT_EXCEEDS_SELLER_TOTAL, + f"captures for {seller} ({captured[seller]}) exceed its " + f"attributed total ({attributed[seller]})", + ) + ) + if refunded.get(seller, 0) > captured.get(seller, 0): + findings.append( + Finding( + receipt.index, + RECEIPT_EXCEEDS_SELLER_TOTAL, + f"refunds for {seller} ({refunded[seller]}) exceed its captures " + f"({captured.get(seller, 0)})", + ) + ) + return findings + + +def _reconcile( + order: Mapping[str, Any], verified: Iterable[VerifiedReceipt] +) -> list[Finding]: + """Platform Verification 4 (SHOULD): refunds against Order adjustments. + + Each `refund` receipt that carries `event.ref.adjustment_id` is compared + with that adjustment. A mismatch leaves the receipt valid. + """ + adjustments = {a["id"]: a for a in order.get("adjustments", [])} + findings = [] + for receipt in verified: + event = receipt.payload["event"] + adjustment_id = (event.get("ref") or {}).get("adjustment_id") + if event["type"] != "refund" or adjustment_id is None: + continue + adjustment = adjustments.get(adjustment_id) + expected = None if adjustment is None else _adjustment_amount(adjustment) + if expected is None: + # Not reconcilable: no such adjustment, or no single `total`. + continue + if event["amount"] != expected: + findings.append( + Finding( + receipt.index, + RECONCILIATION_ADJUSTMENT_MISMATCH, + f"refund of {event['amount']} cites adjustment {adjustment_id}, " + f"whose total is {expected}", + ) + ) + return findings diff --git a/common/payments/fixtures/ap2_order_receipts/refund_delayed_network_ref.json b/common/payments/fixtures/ap2_order_receipts/refund_delayed_network_ref.json new file mode 100644 index 0000000..7fd13d4 --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/refund_delayed_network_ref.json @@ -0,0 +1,221 @@ +{ + "id": "refund_delayed_network_ref", + "title": "Refund receipted pending, then succeeded with a late network_ref", + "test_plan_vector": null, + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Edge Cases, Pending movements: a movement may first be receipted as `pending`. A later receipt in the same chain for the same movement carries `status: succeeded`. Totals change only on the `succeeded` receipt.", + "Edge Cases, Late network references: when a network reference (for example the Acquirer Reference Number of a refund) is assigned after the movement is receipted, it appears on a follow-up receipt for the same `event.ref`. `network_ref` is optional on every status: a refund processed as a reversal of the original authorization may never have one." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "seq 3 is pending and leaves totals unchanged; seq 4, for the same event.ref, is succeeded, carries network_ref (an ARN assigned days later) and is the only receipt that changes refunded.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_refund_delayed_network_ref", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_refund_delayed_network_ref", + "checkout_id": "chk_refund_delayed_network_ref", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [ + { + "id": "adj_refund_1", + "type": "refund", + "occurred_at": "2026-11-10T04:00:00Z", + "status": "completed", + "totals": [ + { + "type": "total", + "amount": -5400 + } + ] + } + ], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa19yZWZ1bmRfZGVsYXllZF9uZXR3b3JrX3JlZiIsImV2ZW50Ijp7ImFtb3VudCI6NTQwMCwiY3VycmVuY3kiOiJVU0QiLCJvY2N1cnJlZF9hdCI6IjIwMjYtMTEtMDlUMTQ6NTM6MjBaIiwic3RhdHVzIjoic3VjY2VlZGVkIiwidHlwZSI6ImF1dGhvcml6YXRpb24ifSwiaWF0IjoxNzk0MjM2MDYwLCJpc3MiOiJodHRwczovL21lcmNoYW50LmV4YW1wbGUvLndlbGwta25vd24vdWNwIiwibWFuZGF0ZV9yZWYiOiJzaGEtMjU2OmNIN3M0cXUwSThEMklYMTFZamxOT3ktWlBhX19CNUlZd2J1T3JjWnNJVWciLCJvcmRlcl9pZCI6Im9yZGVyX3JlZnVuZF9kZWxheWVkX25ldHdvcmtfcmVmIiwicHJldiI6bnVsbCwic2VxIjoxLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.Y5zAwO0s6qvCHvFcBuTaqBu8iMrkULjd17Z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iOiJyZWZ1bmQifSwiaWF0IjoxNzk0OTA5NjYwLCJpc3MiOiJodHRwczovL21lcmNoYW50LmV4YW1wbGUvLndlbGwta25vd24vdWNwIiwibWFuZGF0ZV9yZWYiOiJzaGEtMjU2OmNIN3M0cXUwSThEMklYMTFZamxOT3ktWlBhX19CNUlZd2J1T3JjWnNJVWciLCJvcmRlcl9pZCI6Im9yZGVyX3JlZnVuZF9kZWxheWVkX25ldHdvcmtfcmVmIiwicHJldiI6InNoYS0yNTY6VC1OdVZ5cG9GeUQ2ZS1ycHV6M1pEU1F4bnlvcm1fT3FRbmk0eHByTHpLYyIsInNlcSI6NCwidG90YWxzIjp7ImF1dGhvcml6ZWQiOjU0MDAsImNhcHR1cmVkIjo1NDAwLCJtYW5kYXRlZCI6NTQwMCwicmVmdW5kZWQiOjU0MDB9fQ.2dn3atBLCbmtqtJEjU5cukS2opBmnDDjzlWge4wvYAK9jPpqvduEHN_Jr_LJt-jynm9wOQ-HBWzenhx3awXbOQ" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_delayed_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:cH7s4qu0I8D2IX11YjlNOy-ZPa__B5IYwbuOrcZsIUg", + "order_id": "order_refund_delayed_network_ref", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_delayed_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:cH7s4qu0I8D2IX11YjlNOy-ZPa__B5IYwbuOrcZsIUg", + "order_id": "order_refund_delayed_network_ref", + "prev": "sha-256:qwbwtKaCqq2EyAP4HsWyakNFdcyR2BFYqF9EYbvTLAk", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_delayed_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T04:00:00Z", + "ref": { + "adjustment_id": "adj_refund_1" + }, + "status": "pending", + "type": "refund" + }, + "iat": 1794283260, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:cH7s4qu0I8D2IX11YjlNOy-ZPa__B5IYwbuOrcZsIUg", + "order_id": "order_refund_delayed_network_ref", + "prev": "sha-256:Nyihhp_Wf8nfWnDbwBXPYDO0pGKo_HI4iUMSutiV6dw", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_delayed_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "network_ref": "74000000000000000001063", + "occurred_at": "2026-11-17T10:00:00Z", + "ref": { + "adjustment_id": "adj_refund_1" + }, + "status": "succeeded", + "type": "refund" + }, + "iat": 1794909660, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:cH7s4qu0I8D2IX11YjlNOy-ZPa__B5IYwbuOrcZsIUg", + "order_id": "order_refund_delayed_network_ref", + "prev": "sha-256:T-NuVypoFyD6e-rpuz3ZDSQxnyorm_OqQni4xprLzKc", + "seq": 4, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 5400 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/refund_reversal_no_network_ref.json b/common/payments/fixtures/ap2_order_receipts/refund_reversal_no_network_ref.json new file mode 100644 index 0000000..b5d10dd --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/refund_reversal_no_network_ref.json @@ -0,0 +1,220 @@ +{ + "id": "refund_reversal_no_network_ref", + "title": "Refund processed as a reversal: succeeded without network_ref", + "test_plan_vector": null, + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Edge Cases, Pending movements: a movement may first be receipted as `pending`. A later receipt in the same chain for the same movement carries `status: succeeded`. Totals change only on the `succeeded` receipt.", + "Edge Cases, Late network references: when a network reference (for example the Acquirer Reference Number of a refund) is assigned after the movement is receipted, it appears on a follow-up receipt for the same `event.ref`. `network_ref` is optional on every status: a refund processed as a reversal of the original authorization may never have one." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "The refund settles as a reversal of the authorization shortly after capture, so no network reference is ever assigned: the succeeded receipt for the same event.ref has no network_ref, and is valid.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_refund_reversal_no_network_ref", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_refund_reversal_no_network_ref", + "checkout_id": "chk_refund_reversal_no_network_ref", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [ + { + "id": "adj_refund_1", + "type": "refund", + "occurred_at": "2026-11-10T04:00:00Z", + "status": "completed", + "totals": [ + { + "type": "total", + "amount": -5400 + } + ] + } + ], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa19yZWZ1bmRfcmV2ZXJzYWxfbm9fbmV0d29ya19yZWYiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc5NDIzNjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjpMcEtIUEFSM3NWZ1VQdVZzTWV1MERnZ0o5X1g2bHBEdW13Wmt3WkxPenFnIiwib3JkZXJfaWQiOiJvcmRlcl9yZWZ1bmRfcmV2ZXJzYWxfbm9fbmV0d29ya19yZWYiLCJwcmV2IjpudWxsLCJzZXEiOjEsInRvdGFscyI6eyJhdXRob3JpemVkIjo1NDAwLCJjYXB0dXJlZCI6MCwibWFuZGF0ZWQiOjU0MDAsInJlZnVuZGVkIjowfX0.3mSXh1KP6CWLfDfOCvZbWJqusrRJeC_jU87vaikiAm3BiM9JsriMZVqZn1ILNUtUc3F6Atz1SzQTQlTeCL-Y0g", + "eyJhbGciOiJFUzI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YW1wbGUvLndlbGwta25vd24vdWNwIiwibWFuZGF0ZV9yZWYiOiJzaGEtMjU2OkxwS0hQQVIzc1ZnVVB1VnNNZXUwRGdnSjlfWDZscER1bXdaa3daTE96cWciLCJvcmRlcl9pZCI6Im9yZGVyX3JlZnVuZF9yZXZlcnNhbF9ub19uZXR3b3JrX3JlZiIsInByZXYiOiJzaGEtMjU2Ol9CT3JjXzVPaFVYdHB3OUM1Rmp1Z051XzF0UUJOU0NpRVRzR1EtUzNfUDgiLCJzZXEiOjQsInRvdGFscyI6eyJhdXRob3JpemVkIjo1NDAwLCJjYXB0dXJlZCI6NTQwMCwibWFuZGF0ZWQiOjU0MDAsInJlZnVuZGVkIjo1NDAwfX0.JcgtqCWCaq5PvgncNvexnUBV5ObH9xzSg-fwQF6zLuFrSdbF9apKkbM_goH_YEBjhhJajsje0Yj7707kLDtBfw" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_reversal_no_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:LpKHPAR3sVgUPuVsMeu0DggJ9_X6lpDumwZkwZLOzqg", + "order_id": "order_refund_reversal_no_network_ref", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_reversal_no_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:LpKHPAR3sVgUPuVsMeu0DggJ9_X6lpDumwZkwZLOzqg", + "order_id": "order_refund_reversal_no_network_ref", + "prev": "sha-256:ytVGIt4C-cL36jwDCOF6QmBkVfWc5yn-8dv0p-dQJ_A", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_reversal_no_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T04:00:00Z", + "ref": { + "adjustment_id": "adj_refund_1" + }, + "status": "pending", + "type": "refund" + }, + "iat": 1794283260, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:LpKHPAR3sVgUPuVsMeu0DggJ9_X6lpDumwZkwZLOzqg", + "order_id": "order_refund_reversal_no_network_ref", + "prev": "sha-256:pEXS16abtBPeVQ29q-5lhWeHof9vK4dt9QqxGticRbI", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_refund_reversal_no_network_ref", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T04:02:00Z", + "ref": { + "adjustment_id": "adj_refund_1" + }, + "status": "succeeded", + "type": "refund" + }, + "iat": 1794283380, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:LpKHPAR3sVgUPuVsMeu0DggJ9_X6lpDumwZkwZLOzqg", + "order_id": "order_refund_reversal_no_network_ref", + "prev": "sha-256:_BOrc_5OhUXtpw9C5FjugNu_1tQBNSCiETsGQ-S3_P8", + "seq": 4, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 5400 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v01_single_capture.json b/common/payments/fixtures/ap2_order_receipts/v01_single_capture.json new file mode 100644 index 0000000..826109b --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v01_single_capture.json @@ -0,0 +1,140 @@ +{ + "id": "v01_single_capture", + "title": "A single capture equal to the mandate verifies", + "test_plan_vector": "1", + "spec": [ + "Platform Verification 1: MUST verify each receipt's signature against the `keys` of the business named in `iss`, and MUST treat a receipt whose `iss` is not the business that signed the checkout covered by `mandate_ref` as `receipt_mandate_unknown`.", + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "The ucp#1109 chain has two split captures, so it is vector 2; a single capture of the full mandate needs its own signed receipt.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v01", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v01", + "checkout_id": "chk_v01", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWF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Y4Ri1TdktvIiwib3JkZXJfaWQiOiJvcmRlcl92MDEiLCJwcmV2Ijoic2hhLTI1NjprcEM2NC00YVVfMWNXMTFRdWNVVm9HakVSZWhfRmJLVXhfMUNtcWhjLUpNIiwic2VxIjoyLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjU0MDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.AUvO-ONe1uOTn_q8DX3Cg3YDVpMGybPKKjoh2yIdFYzz2rPShXS_ORw7eT-CywEzGqfEo2QDqZCJDyl9vJcOvg" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v01", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:DGlGEk22J-HJ2hBvZufrXUQuYrq5g_KuI-7V8F-SvKo", + "order_id": "order_v01", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v01", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:DGlGEk22J-HJ2hBvZufrXUQuYrq5g_KuI-7V8F-SvKo", + "order_id": "order_v01", + "prev": "sha-256:kpC64-4aU_1cW11QucUVoGjEReh_FbKUx_1Cmqhc-JM", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v02_split_captures.json b/common/payments/fixtures/ap2_order_receipts/v02_split_captures.json new file mode 100644 index 0000000..e464814 --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v02_split_captures.json @@ -0,0 +1,189 @@ +{ + "id": "v02_split_captures", + "title": "Two split captures summing to the mandate verify", + "test_plan_vector": "2", + "spec": [ + "Platform Verification 1: MUST verify each receipt's signature against the `keys` of the business named in `iss`, and MUST treat a receipt whose `iss` is not the business that signed the checkout covered by `mandate_ref` as `receipt_mandate_unknown`.", + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Edge Cases, Split shipments: multiple `capture` receipts against the same `mandate_ref`, with `captured` accumulating." + ], + "signing": "Receipts copied byte-for-byte from the signed Order example in ucp#1109; key from the PR description (example only). Source: Universal-Commerce-Protocol/ucp#1109 at 1d19291d, ap2-mandates.md, Order example under 'Placement and Delivery'.", + "inputs": { + "issuers": { + "https://business.example.com/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "merchant_2025", + "use": "sig", + "alg": "ES256", + "x": "GzEF_HXZbmVOvExfSerMRYki1vTfR1fETwLcYi8MS50", + "y": "iDtJQqA9IVKbVvAQ7tL_G73kkG1GoaHJKSty0pWD0b8" + } + ] + } + }, + "mandates": [ + { + "credential_token": "examplePaymentMethodToken", + "business": "https://business.example.com/.well-known/ucp" + } + ], + "order": { + "id": "order_abc123", + "checkout_id": "chk_abc123", + "currency": "USD", + "line_items": [ + { + "id": "li_shoes", + "totals": [ + { + "type": "subtotal", + "amount": 2800 + }, + { + "type": "total", + "amount": 2800 + } + ] + }, + { + "id": "li_jacket", + "totals": [ + { + "type": "subtotal", + "amount": 2200 + }, + { + "type": "total", + "amount": 2200 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6Im1lcmNoYW50XzIwMjUiLCJ0eXAiOiJ1Y3AtYXAyLXJlY2VpcHQrand0In0.eyJjaGVja291dF9pZCI6ImNoa19hYmMxMjMiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc2MjcwMDAwMCwiaXNzIjoiaHR0cHM6Ly9idXNpbmVzcy5leGFtcGxlLmNvbS8ud2VsbC1rbm93bi91Y3AiLCJtYW5kYXRlX3JlZiI6InNoYS0yNTY6emkweERrMTZfR0p3X1FFS0lIYVVia1VGU3RrREo2V2phS2xmMzFzWWZPayIsIm9yZGVyX2lkIjoib3JkZXJfYWJjMTIzIiwicHJldiI6bnVsbCwic2VxIjoxLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.yqOks6JCSk1SGQjykZw6WiNzk0-PC0S3cwMWXxbuH3KGCvTAFFpkT9HuJPS-krPUsWyLhVPNO2Ftz9SuEaoHpQ", + "eyJhbGciOiJFUzI1NiIsImtpZCI6Im1lcmNoYW50XzIwMjUiLCJ0eXAiOiJ1Y3AtYXAyLXJlY2VpcHQrand0In0.eyJjaGVja291dF9pZCI6ImNoa19hYmMxMjMiLCJldmVudCI6eyJhbW91bnQiOjMwMDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTEwVDAyOjAwOjAwWiIsInJlZiI6eyJwcm9jZXNzaW5nX2VudHJ5X2lkIjoiZW50XzIifSwic3RhdHVzIjoic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mMxMjMiLCJwcmV2Ijoic2hhLTI1NjotTC1ZV3lkLVcxNmItR1ExM3l2bXZ4UTFmOThyMTltSzlZc3FEMlF4QkQ4Iiwic2VxIjozLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjU0MDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.aGDMlvYL7ZjzXiv6HVKJg-sbdNLIOWSr_nNa_-mUrDSjSVcFv56nB8q2FFR0fAU5OGgrkLnwNmxV18b-SK6TPA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1762700000, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 3000, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "ref": { + "processing_entry_id": "ent_2" + }, + "status": "succeeded", + "type": "capture" + }, + "iat": 1762740000, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": "sha-256:zDe6xHjsAm38YFD4qeWDqJhcMiss3bjJ6BqDQVMCJtQ", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 3000, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 2400, + "currency": "USD", + "occurred_at": "2026-11-12T02:00:00Z", + "ref": { + "processing_entry_id": "ent_3" + }, + "status": "succeeded", + "type": "capture" + }, + "iat": 1762912800, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": "sha-256:-L-YWyd-W16b-GQ13yvmvxQ1f98r19mK9YsqD2QxBD8", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v03_capture_exceeds_mandate.json b/common/payments/fixtures/ap2_order_receipts/v03_capture_exceeds_mandate.json new file mode 100644 index 0000000..01e645d --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v03_capture_exceeds_mandate.json @@ -0,0 +1,144 @@ +{ + "id": "v03_capture_exceeds_mandate", + "title": "A capture above the mandate, without a new mandate", + "test_plan_vector": "3", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Business Requirements 3: MUST NOT capture so that `captured` exceeds `mandated`. Any increase in what the buyer pays beyond `mandated` (a tip, an overage, an order change, or a re-authorization above the original amount) MUST be covered by a new closed Payment Mandate from the platform. Movements that spend against the new mandate form their own chain, keyed by its `mandate_ref`." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v03", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v03", + "checkout_id": "chk_v03", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDMiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc5NDIzNjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1Njp5cExsZm1wUWpQVEVhX0dXN01PNVZhVlhCS3dHTFJuR01iS3RsN0E0bFZBIiwib3JkZXJfaWQiOiJvcmRlcl92MDMiLCJwcmV2IjpudWxsLCJzZXEiOjEsInRvdGFscyI6eyJhdXRob3JpemVkIjo1NDAwLCJjYXB0dXJlZCI6MCwibWFuZGF0ZWQiOjU0MDAsInJlZnVuZGVkIjowfX0.AwuforQYyZR1FTefApNIMX38NFXEusM4sEqQVxsPwsX80zf6cAkjaWsRyVTJKGX2RDmCkugHWAQ_0ErIRJB0ZQ", + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDMiLCJldmVudCI6eyJhbW91bnQiOjYwMDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTEwVDAyOjAwOjAwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJjYXB0dXJlIn0sImlhdCI6MTc5NDI3NjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1Njp5cExsZm1wUWpQVEVhX0dXN01PNVZhVlhCS3dHTFJuR01iS3RsN0E0bFZBIiwib3JkZXJfaWQiOiJvcmRlcl92MDMiLCJwcmV2Ijoic2hhLTI1NjpQRW11cDJKSWQxV19zRzlBR3Y4YVFPYUlROXpHbldPT1VMZWhrMzhOQ25JIiwic2VxIjoyLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjYwMDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.Kzs5wRAudJow8MJkVZtlIzeLHrWfTiGomSiCtzTJX-GJyYczBAWw9e7HGMASk0stHr9ipPQwmuUYhLdSMcIAmA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v03", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:ypLlfmpQjPTEa_GW7MO5VaVXBKwGLRnGMbKtl7A4lVA", + "order_id": "order_v03", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v03", + "event": { + "amount": 6000, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:ypLlfmpQjPTEa_GW7MO5VaVXBKwGLRnGMbKtl7A4lVA", + "order_id": "order_v03", + "prev": "sha-256:PEmup2JId1W_sG9AGv8aQOaIQ9zGnWOOULehk38NCnI", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 6000, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [ + { + "receipt_index": 1, + "code": "receipt_exceeds_mandate" + } + ], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v04_increase_second_mandate.json b/common/payments/fixtures/ap2_order_receipts/v04_increase_second_mandate.json new file mode 100644 index 0000000..bfa6863 --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v04_increase_second_mandate.json @@ -0,0 +1,209 @@ +{ + "id": "v04_increase_second_mandate", + "title": "An increase covered by a second mandate verifies", + "test_plan_vector": "4", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Business Requirements 3: MUST NOT capture so that `captured` exceeds `mandated`. Any increase in what the buyer pays beyond `mandated` (a tip, an overage, an order change, or a re-authorization above the original amount) MUST be covered by a new closed Payment Mandate from the platform. Movements that spend against the new mandate form their own chain, keyed by its `mandate_ref`." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "The USD 6.00 tip is covered by a second closed Payment Mandate, whose movements form their own chain starting at seq 1.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v04_original", + "business": "https://merchant.example/.well-known/ucp" + }, + { + "credential_token": "test_only_payment_mandate_v04_increase", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v04", + "checkout_id": "chk_v04", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "fee", + "amount": 600, + "display_text": "Tip" + }, + { + "type": "total", + "amount": 6000 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDQiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc5NDIzNjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjpycmVwQ1pOaUk3ZmZtSVp5b2tfSHQtVWVVb1poZUxCb21FQmtqWTBzVkVVIiwib3JkZX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QnJ2eUNJTHgzdFkiLCJvcmRlcl9pZCI6Im9yZGVyX3YwNCIsInByZXYiOiJzaGEtMjU2OmZfOVFlbEZMbFI2N25uRU9Pc2lXaWppNWdqS1JlLV9PZ1c4Z3NpYXpMbTQiLCJzZXEiOjIsInRvdGFscyI6eyJhdXRob3JpemVkIjo2MDAsImNhcHR1cmVkIjo2MDAsIm1hbmRhdGVkIjo2MDAsInJlZnVuZGVkIjowfX0.8Z_LJhELPtoCmlHpYtYuzDxy5Rq5DfffOZw0Eno2h3N9SJ-IxO5PnUHcoY2k_9-DPBJn0vtHbn6y8HHlx1xirA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v04", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:rrepCZNiI7ffmIZyok_Ht-UeUoZheLBomEBkjY0sVEU", + "order_id": "order_v04", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v04", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:rrepCZNiI7ffmIZyok_Ht-UeUoZheLBomEBkjY0sVEU", + "order_id": "order_v04", + "prev": "sha-256:A49z6UiTYG_8IsKApvmv0vzyEJh516dhoEX6slejFD0", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v04", + "event": { + "amount": 600, + "currency": "USD", + "occurred_at": "2026-11-10T03:00:00Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794279660, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:nZXqTdq9siancE9G8lsfl66tUvfmiXhMBrvyCILx3tY", + "order_id": "order_v04", + "prev": null, + "seq": 1, + "totals": { + "authorized": 600, + "captured": 0, + "mandated": 600, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v04", + "event": { + "amount": 600, + "currency": "USD", + "occurred_at": "2026-11-10T03:05:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794279960, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:nZXqTdq9siancE9G8lsfl66tUvfmiXhMBrvyCILx3tY", + "order_id": "order_v04", + "prev": "sha-256:f_9QelFLlR67nnEOOsiWiji5gjKRe-_OgW8gsiazLm4", + "seq": 2, + "totals": { + "authorized": 600, + "captured": 600, + "mandated": 600, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v05_tampered_amount.json b/common/payments/fixtures/ap2_order_receipts/v05_tampered_amount.json new file mode 100644 index 0000000..5ba837a --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v05_tampered_amount.json @@ -0,0 +1,193 @@ +{ + "id": "v05_tampered_amount", + "title": "A tampered amount gives receipt_invalid_signature", + "test_plan_vector": "5", + "spec": [ + "Platform Verification 1: MUST verify each receipt's signature against the `keys` of the business named in `iss`, and MUST treat a receipt whose `iss` is not the business that signed the checkout covered by `mandate_ref` as `receipt_mandate_unknown`." + ], + "signing": "Receipts copied byte-for-byte from the signed Order example in ucp#1109; key from the PR description (example only). Source: Universal-Commerce-Protocol/ucp#1109 at 1d19291d, ap2-mandates.md, Order example under 'Placement and Delivery'.", + "notes": "The ucp#1109 chain with event.amount of the third receipt changed from 2400 to 4400 after signing; header and signature are unchanged.", + "inputs": { + "issuers": { + "https://business.example.com/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "merchant_2025", + "use": "sig", + "alg": "ES256", + "x": "GzEF_HXZbmVOvExfSerMRYki1vTfR1fETwLcYi8MS50", + "y": "iDtJQqA9IVKbVvAQ7tL_G73kkG1GoaHJKSty0pWD0b8" + } + ] + } + }, + "mandates": [ + { + "credential_token": "examplePaymentMethodToken", + "business": "https://business.example.com/.well-known/ucp" + } + ], + "order": { + "id": "order_abc123", + "checkout_id": "chk_abc123", + "currency": "USD", + "line_items": [ + { + "id": "li_shoes", + "totals": [ + { + "type": "subtotal", + "amount": 2800 + }, + { + "type": "total", + "amount": 2800 + } + ] + }, + { + "id": "li_jacket", + "totals": [ + { + "type": "subtotal", + "amount": 2200 + }, + { + "type": "total", + "amount": 2200 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6Im1lcmNoYW50XzIwMjUiLCJ0eXAiOiJ1Y3AtYXAyLXJlY2VpcHQrand0In0.eyJjaGVja291dF9pZCI6ImNoa19hYmMxMjMiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc2MjcwMDAwMCwiaXNzIjoiaHR0cHM6Ly9idXNpbmVzcy5leGFtcGxlLmNvbS8ud2VsbC1rbm93bi91Y3AiLCJtYW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H19.ZyT9V_cSIvPgIChIM9cF4xrc5_ROhG7J5E8LxCc95HfMIecZ4zRMfsj5638RrVDrcDybCHUFq3qXWftbRssvYg", + "eyJhbGciOiJFUzI1NiIsImtpZCI6Im1lcmNoYW50XzIwMjUiLCJ0eXAiOiJ1Y3AtYXAyLXJlY2VpcHQrand0In0.eyJjaGVja291dF9pZCI6ImNoa19hYmMxMjMiLCJldmVudCI6eyJhbW91bnQiOjQ0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTEyVDAyOjAwOjAwWiIsInJlZiI6eyJwcm9jZXNzaW5nX2VudHJ5X2lkIjoiZW50XzMifSwic3RhdHVzIjoic3VjY2VlZGVkIiwidHlwZSI6ImNhcHR1cmUifSwiaWF0IjoxNzYyOTEyODAwLCJpc3MiOiJodHRwczovL2J1c2luZXNzLmV4YW1wbGUuY29tLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1Njp6aTB4RGsxNl9HSndfUUVLSUhhVWJrVUZTdGtESjZXamFLbGYzMXNZZk9rIiwib3JkZXJfaWQiOiJvcmRlcl9hYmMxMjMiLCJwcmV2Ijoic2hhLTI1NjotTC1ZV3lkLVcxNmItR1ExM3l2bXZ4UTFmOThyMTltSzlZc3FEMlF4QkQ4Iiwic2VxIjozLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjU0MDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.aGDMlvYL7ZjzXiv6HVKJg-sbdNLIOWSr_nNa_-mUrDSjSVcFv56nB8q2FFR0fAU5OGgrkLnwNmxV18b-SK6TPA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1762700000, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 3000, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "ref": { + "processing_entry_id": "ent_2" + }, + "status": "succeeded", + "type": "capture" + }, + "iat": 1762740000, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": "sha-256:zDe6xHjsAm38YFD4qeWDqJhcMiss3bjJ6BqDQVMCJtQ", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 3000, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 4400, + "currency": "USD", + "occurred_at": "2026-11-12T02:00:00Z", + "ref": { + "processing_entry_id": "ent_3" + }, + "status": "succeeded", + "type": "capture" + }, + "iat": 1762912800, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": "sha-256:-L-YWyd-W16b-GQ13yvmvxQ1f98r19mK9YsqD2QxBD8", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [ + { + "receipt_index": 2, + "code": "receipt_invalid_signature" + } + ], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v06_missing_seq.json b/common/payments/fixtures/ap2_order_receipts/v06_missing_seq.json new file mode 100644 index 0000000..135846f --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v06_missing_seq.json @@ -0,0 +1,160 @@ +{ + "id": "v06_missing_seq", + "title": "A missing seq gives receipt_sequence_gap", + "test_plan_vector": "6", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain." + ], + "signing": "Receipts copied byte-for-byte from the signed Order example in ucp#1109; key from the PR description (example only). Source: Universal-Commerce-Protocol/ucp#1109 at 1d19291d, ap2-mandates.md, Order example under 'Placement and Delivery'.", + "notes": "The ucp#1109 chain with its seq 2 receipt removed.", + "inputs": { + "issuers": { + "https://business.example.com/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "merchant_2025", + "use": "sig", + "alg": "ES256", + "x": "GzEF_HXZbmVOvExfSerMRYki1vTfR1fETwLcYi8MS50", + "y": "iDtJQqA9IVKbVvAQ7tL_G73kkG1GoaHJKSty0pWD0b8" + } + ] + } + }, + "mandates": [ + { + "credential_token": "examplePaymentMethodToken", + "business": "https://business.example.com/.well-known/ucp" + } + ], + "order": { + "id": "order_abc123", + "checkout_id": "chk_abc123", + "currency": "USD", + "line_items": [ + { + "id": "li_shoes", + "totals": [ + { + "type": "subtotal", + "amount": 2800 + }, + { + "type": "total", + "amount": 2800 + } + ] + }, + { + "id": "li_jacket", + "totals": [ + { + "type": "subtotal", + "amount": 2200 + }, + { + "type": "total", + "amount": 2200 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6Im1lcmNoYW50XzIwMjUiLCJ0e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VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1Njp6aTB4RGsxNl9HSndfUUVLSUhhVWJrVUZTdGtESjZXamFLbGYzMXNZZk9rIiwib3JkZXJfaWQiOiJvcmRlcl9hYmMxMjMiLCJwcmV2Ijoic2hhLTI1NjotTC1ZV3lkLVcxNmItR1ExM3l2bXZ4UTFmOThyMTltSzlZc3FEMlF4QkQ4Iiwic2VxIjozLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjU0MDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.aGDMlvYL7ZjzXiv6HVKJg-sbdNLIOWSr_nNa_-mUrDSjSVcFv56nB8q2FFR0fAU5OGgrkLnwNmxV18b-SK6TPA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1762700000, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "merchant_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_abc123", + "event": { + "amount": 2400, + "currency": "USD", + "occurred_at": "2026-11-12T02:00:00Z", + "ref": { + "processing_entry_id": "ent_3" + }, + "status": "succeeded", + "type": "capture" + }, + "iat": 1762912800, + "iss": "https://business.example.com/.well-known/ucp", + "mandate_ref": "sha-256:zi0xDk16_GJw_QEKIHaUbkUFStkDJ6WjaKlf31sYfOk", + "order_id": "order_abc123", + "prev": "sha-256:-L-YWyd-W16b-GQ13yvmvxQ1f98r19mK9YsqD2QxBD8", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [ + { + "receipt_index": 1, + "code": "receipt_sequence_gap" + } + ], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v07_refund_exceeds_capture.json b/common/payments/fixtures/ap2_order_receipts/v07_refund_exceeds_capture.json new file mode 100644 index 0000000..ebe43ff --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v07_refund_exceeds_capture.json @@ -0,0 +1,173 @@ +{ + "id": "v07_refund_exceeds_capture", + "title": "A refund above captured gives receipt_refund_exceeds_capture", + "test_plan_vector": "7", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v07", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v07", + "checkout_id": "chk_v07", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "rece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QXGvRq7pKxtgGX7ZPunxT5HAYJqoqEOiWaHfRx2tmpI5b57U5ru9qsG-rfA-8Ht1CBw0BUbpGMxJGmYoXuw" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v07", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:ZvgcRQ4YxRVX_bsJfbQCpj-jamofV-bbeu6Mv2OlGow", + "order_id": "order_v07", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v07", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:ZvgcRQ4YxRVX_bsJfbQCpj-jamofV-bbeu6Mv2OlGow", + "order_id": "order_v07", + "prev": "sha-256:Ux_jxU246WFuQ0ATuhD6F2YS-i0iplJ4gFXODFm4NxA", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v07", + "event": { + "amount": 6000, + "currency": "USD", + "occurred_at": "2026-11-12T10:00:00Z", + "status": "succeeded", + "type": "refund" + }, + "iat": 1794477660, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:ZvgcRQ4YxRVX_bsJfbQCpj-jamofV-bbeu6Mv2OlGow", + "order_id": "order_v07", + "prev": "sha-256:41ykHBdaQGb86y7KUENbrDCVGC_-Wtw2QvAet3wTHTU", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 6000 + } + } + } + ], + "expected": { + "outcomes": [ + { + "receipt_index": 2, + "code": "receipt_refund_exceeds_capture" + } + ], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v08_key_not_retained.json b/common/payments/fixtures/ap2_order_receipts/v08_key_not_retained.json new file mode 100644 index 0000000..955826c --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v08_key_not_retained.json @@ -0,0 +1,150 @@ +{ + "id": "v08_key_not_retained", + "title": "A receipt whose retired key is no longer published", + "test_plan_vector": null, + "spec": [ + "Platform Verification 1: MUST verify each receipt's signature against the `keys` of the business named in `iss`, and MUST treat a receipt whose `iss` is not the business that signed the checkout covered by `mandate_ref` as `receipt_mandate_unknown`.", + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Business Requirements 6: MUST keep retired public keys resolvable by `kid` for at least the dispute window of the payment method used." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "Negative counterpart of v08_rotated_retained_key: test_only_2025 is gone from keys, so seq 1 cannot be verified. It is then not part of the chain, and seq 2 is reported as a gap.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v08", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v08", + "checkout_id": "chk_v08", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI1IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDgiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc5NDIzNjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjpwMlZsbUFQVmtjT1Q4eDI1X1RMczE2SkZfSWs0QmJfdU1MOE9wQ1c4WG9NIiwib3JkZXJfaWQiOiJvcmRlcl92MDgiLCJwcmV2IjpudWxsLCJzZXEiOjEsInRvdGFscyI6eyJhdXRob3JpemVkIjo1NDAwLCJjYXB0dXJlZCI6MCwibWFuZGF0ZWQiOjU0MDAsInJlZnVuZGVkIjowfX0.X8uYVaU1KLewcIrXtYaqsk1t_e9A-eO3CtiEhaS5cO8Ao5KLbie6Eq2WiNHj-fc56IwKKo_sz9tkfO4WEIOlJw", + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDgiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTEwVDAyOjAwOjAwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJjYXB0dXJlIn0sImlhdCI6MTc5NDI3NjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjpwMlZsbUFQVmtjT1Q4eDI1X1RMczE2SkZfSWs0QmJfdU1MOE9wQ1c4WG9NIiwib3JkZXJfaWQiOiJvcmRlcl92MDgiLCJwcmV2Ijoic2hhLTI1NjotX0tNMmMtWTJlbVF4RmU4bVExMEk3TEJWRGxQUU1ENF9NSGhnYzhFM1RNIiwic2VxIjoyLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjU0MDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.X7iGoYaia9oQCQ9MlhQe0mobVe_XDlslC8qwqpbqlqAYWaOI-7Wbjgo0FW8gqqhLVAHE6PzCV9yfIdTq2IwQbw" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v08", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:p2VlmAPVkcOT8x25_TLs16JF_Ik4Bb_uML8OpCW8XoM", + "order_id": "order_v08", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v08", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:p2VlmAPVkcOT8x25_TLs16JF_Ik4Bb_uML8OpCW8XoM", + "order_id": "order_v08", + "prev": "sha-256:-_KM2c-Y2emQxFe8mQ10I7LBVDlPQMD4_MHhgc8E3TM", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [ + { + "receipt_index": 0, + "code": "receipt_invalid_signature" + }, + { + "receipt_index": 1, + "code": "receipt_sequence_gap" + } + ], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v08_rotated_retained_key.json b/common/payments/fixtures/ap2_order_receipts/v08_rotated_retained_key.json new file mode 100644 index 0000000..327d3dc --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v08_rotated_retained_key.json @@ -0,0 +1,149 @@ +{ + "id": "v08_rotated_retained_key", + "title": "A receipt signed with a rotated, retained key verifies", + "test_plan_vector": "8", + "spec": [ + "Platform Verification 1: MUST verify each receipt's signature against the `keys` of the business named in `iss`, and MUST treat a receipt whose `iss` is not the business that signed the checkout covered by `mandate_ref` as `receipt_mandate_unknown`.", + "Business Requirements 6: MUST keep retired public keys resolvable by `kid` for at least the dispute window of the payment method used." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "seq 1 is signed with test_only_2025, which was retired before seq 2 but is still published in keys.", + "inputs": { + "issuers": { + "https://merchant.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2025", + "use": "sig", + "alg": "ES256", + "x": "8qaVbVg3ELtnqCucPvnQsHCKq38EoteCtAlYUM4Uxv0", + "y": "Dwr26klqGwVz0RLSy6TnR5_d6PxlBobngP3EB0yV-aw" + }, + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "gyT0sIDrvE1CD7JvEmEoOasWx_dmXhJVi-dOqj4V-Po", + "y": "BprggvW48ulKwczERsKtS3NdLc7YdYIfx1nuics9hFA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v08", + "business": "https://merchant.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v08", + "checkout_id": "chk_v08", + "currency": "USD", + "line_items": [ + { + "id": "li_1", + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "total", + "amount": 5000 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5000 + }, + { + "type": "tax", + "amount": 400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI1IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDgiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc5NDIzNjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjpwMlZsbUFQVmtjT1Q4eDI1X1RMczE2SkZfSWs0QmJfdU1MOE9wQ1c4WG9NIiwib3JkZXJfaWQiOiJvcmRlcl92MDgiLCJwcmV2IjpudWxsLCJzZXEiOjEsInRvdGFscyI6eyJhdXRob3JpemVkIjo1NDAwLCJjYXB0dXJlZCI6MCwibWFuZGF0ZWQiOjU0MDAsInJlZnVuZGVkIjowfX0.X8uYVaU1KLewcIrXtYaqsk1t_e9A-eO3CtiEhaS5cO8Ao5KLbie6Eq2WiNHj-fc56IwKKo_sz9tkfO4WEIOlJw", + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDgiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTEwVDAyOjAwOjAwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJjYXB0dXJlIn0sImlhdCI6MTc5NDI3NjA2MCwiaXNzIjoiaHR0cHM6Ly9tZXJjaGFudC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjpwMlZsbUFQVmtjT1Q4eDI1X1RMczE2SkZfSWs0QmJfdU1MOE9wQ1c4WG9NIiwib3JkZXJfaWQiOiJvcmRlcl92MDgiLCJwcmV2Ijoic2hhLTI1NjotX0tNMmMtWTJlbVF4RmU4bVExMEk3TEJWRGxQUU1ENF9NSGhnYzhFM1RNIiwic2VxIjoyLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjU0MDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MH19.X7iGoYaia9oQCQ9MlhQe0mobVe_XDlslC8qwqpbqlqAYWaOI-7Wbjgo0FW8gqqhLVAHE6PzCV9yfIdTq2IwQbw" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2025", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v08", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:p2VlmAPVkcOT8x25_TLs16JF_Ik4Bb_uML8OpCW8XoM", + "order_id": "order_v08", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v08", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-10T02:00:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794276060, + "iss": "https://merchant.example/.well-known/ucp", + "mandate_ref": "sha-256:p2VlmAPVkcOT8x25_TLs16JF_Ik4Bb_uML8OpCW8XoM", + "order_id": "order_v08", + "prev": "sha-256:-_KM2c-Y2emQxFe8mQ10I7LBVDlPQMD4_MHhgc8E3TM", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v09_duplicate_seller_capture.json b/common/payments/fixtures/ap2_order_receipts/v09_duplicate_seller_capture.json new file mode 100644 index 0000000..69fa210 --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v09_duplicate_seller_capture.json @@ -0,0 +1,197 @@ +{ + "id": "v09_duplicate_seller_capture", + "title": "A duplicate capture for one seller gives a seller-total warning", + "test_plan_vector": "9", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Platform Verification 3: SHOULD, when `event.seller_id` is present, also check per seller that succeeded captures do not exceed that seller's attributed total and that refunds do not exceed that seller's captures.", + "Edge Cases, Marketplace as merchant of record: the marketplace issues every receipt and sets `event.seller_id`, so a duplicate capture for one seller is detectable even when the chain's totals pass." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "Chain totals pass (captured 4000 <= mandated 5400), but seller_a's captures (4000) exceed its attributed total (2000). The per-seller check is a SHOULD, so this is a warning, not a failed outcome.", + "inputs": { + "issuers": { + "https://marketplace.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "TaUGm9_vHgJoFIFsaKoHwP66ej_e1zhs63od2xv2V84", + "y": "1hBQgzroCLRPAITCUXAHhjnD2SpZS0sMgPrVwtvYyr4" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v09_duplicate_seller_capture", + "business": "https://marketplace.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v09_duplicate_seller_capture", + "checkout_id": "chk_v09_duplicate_seller_capture", + "currency": "USD", + "sellers": { + "seller_a": { + "name": "Seller A" + }, + "seller_b": { + "name": "Seller B" + } + }, + "line_items": [ + { + "id": "li_a", + "seller_id": "seller_a", + "totals": [ + { + "type": "subtotal", + "amount": 2000 + }, + { + "type": "total", + "amount": 2000 + } + ] + }, + { + "id": "li_b", + "seller_id": "seller_b", + "totals": [ + { + "type": "subtotal", + "amount": 3400 + }, + { + "type": "total", + "amount": 3400 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDlfZHVwbGljYXRlX3NlbGxlcl9jYXB0dXJlIiwiZXZlbnQiOnsiYW1vdW50Ijo1NDAwLCJjdXJyZW5jeSI6IlVTRCIsIm9jY3VycmVkX2F0IjoiMjAyNi0xMS0wOVQxNDo1MzoyMFoiLCJzdGF0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ZWQiOjB9fQ.boTYRt6deb9VK527wbPgMKE5dR6FaEO8J-oKdOAUhOdzCQ1MTyGOyClbptor0ZepXiUnFJfChbI0SBvDmgtSHA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_duplicate_seller_capture", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:73OrgTif8NKMJBTApDVyyqgwkRVMtF9E-RhFqrqtlro", + "order_id": "order_v09_duplicate_seller_capture", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_duplicate_seller_capture", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "seller_id": "seller_a", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:73OrgTif8NKMJBTApDVyyqgwkRVMtF9E-RhFqrqtlro", + "order_id": "order_v09_duplicate_seller_capture", + "prev": "sha-256:MU3KLP5IPEzz1rPalU5chQvGsNP5wrFHUP36TPBMAoE", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 2000, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_duplicate_seller_capture", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-11T18:04:00Z", + "seller_id": "seller_a", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794420300, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:73OrgTif8NKMJBTApDVyyqgwkRVMtF9E-RhFqrqtlro", + "order_id": "order_v09_duplicate_seller_capture", + "prev": "sha-256:67AaqOIgx95LBFRyX6n7D6P336jK-jIWypUB0ABqcHo", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 4000, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [ + { + "receipt_index": 2, + "code": "receipt_exceeds_seller_total" + } + ], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v09_seller_refund_exceeds_captures.json b/common/payments/fixtures/ap2_order_receipts/v09_seller_refund_exceeds_captures.json new file mode 100644 index 0000000..84f93de --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v09_seller_refund_exceeds_captures.json @@ -0,0 +1,196 @@ +{ + "id": "v09_seller_refund_exceeds_captures", + "title": "A refund above one seller's captures gives a seller-total warning", + "test_plan_vector": null, + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Platform Verification 3: SHOULD, when `event.seller_id` is present, also check per seller that succeeded captures do not exceed that seller's attributed total and that refunds do not exceed that seller's captures." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "Chain totals pass (refunded 1000 <= captured 2000), but seller_b has no captures. Second half of the per-seller SHOULD.", + "inputs": { + "issuers": { + "https://marketplace.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "TaUGm9_vHgJoFIFsaKoHwP66ej_e1zhs63od2xv2V84", + "y": "1hBQgzroCLRPAITCUXAHhjnD2SpZS0sMgPrVwtvYyr4" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v09_seller_refund_exceeds_captures", + "business": "https://marketplace.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v09_seller_refund_exceeds_captures", + "checkout_id": "chk_v09_seller_refund_exceeds_captures", + "currency": "USD", + "sellers": { + "seller_a": { + "name": "Seller A" + }, + "seller_b": { + "name": "Seller B" + } + }, + "line_items": [ + { + "id": "li_a", + "seller_id": "seller_a", + "totals": [ + { + "type": "subtotal", + "amount": 2000 + }, + { + "type": "total", + "amount": 2000 + } + ] + }, + { + "id": "li_b", + "seller_id": "seller_b", + "totals": [ + { + "type": "subtotal", + "amount": 3400 + }, + { + "type": "total", + "amount": 3400 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDlfc2VsbGVyX3JlZnVuZF9leGNlZWRzX2NhcHR1cmVzIiwiZXZlbnQiOnsiYW1vdW50Ijo1NDAwLCJjdXJyZW5jeSI6IlVTRCIsIm9jY3VycmVkX2F0IjoiMjAyNi0xMS0wOVQxNDo1MzoyMFoiLCJzdGF0dXMiOiJzdWNjZWVkZWQiLCJ0eXBlIjoiYXV0aG9yaXphdGlvbiJ9LCJpYXQiOjE3OTQyMzYwNjAsImlzcyI6Imh0dHBzOi8vbWFya2V0cGxhY2UuZXhhbXBsZS8ud2VsbC1rbm93bi91Y3AiLCJtYW5kYXRlX3JlZiI6InNoYS0yNTY6TEdKSzdpY1VsZ05Lc29ISF9YS3FVSzY0b0VBUEZfZDJVMkZPclFUdUotSSIsIm9yZGVyX2lkIjoib3JkZXJfdjA5X3NlbGxlcl9yZWZ1bmRfZXhjZWVkc19jYXB0dXJlcyIsInByZXYiOm51bGwsInNlcSI6MSwidG90YWxzIjp7ImF1dGhvc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ZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDlfc2VsbGVyX3JlZnVuZF9leGNlZWRzX2NhcHR1cmVzIiwiZXZlbnQiOnsiYW1vdW50IjoxMDAwLCJjdXJyZW5jeSI6IlVTRCIsIm9jY3VycmVkX2F0IjoiMjAyNi0xMS0xMlQwOTowMDowMFoiLCJzZWxsZXJfaWQiOiJzZWxsZXJfYiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJyZWZ1bmQifSwiaWF0IjoxNzk0NDc0MDYwLCJpc3MiOiJodHRwczovL21hcmtldHBsYWNlLmV4YW1wbGUvLndlbGwta25vd24vdWNwIiwibWFuZGF0ZV9yZWYiOiJzaGEtMjU2OkxHSks3aWNVbGdOS3NvSEhfWEtxVUs2NG9FQVBGX2QyVTJGT3JRVHVKLUkiLCJvcmRlcl9pZCI6Im9yZGVyX3YwOV9zZWxsZXJfcmVmdW5kX2V4Y2VlZHNfY2FwdHVyZXMiLCJwcmV2Ijoic2hhLTI1NjpvM1RwSmVYYk93bFlEdHVsVG42ZEJxWUg3UVFBaHA4ZFc0UC0xcUh3NDJNIiwic2VxIjozLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NTQwMCwiY2FwdHVyZWQiOjIwMDAsIm1hbmRhdGVkIjo1NDAwLCJyZWZ1bmRlZCI6MTAwMH19.7Sgui0aV_UJDpk91kVzYBT-mCgKcBfHI2kkSDBr13np1CaYFFP5-oxwStP1XgB3BrHgT7nMlFEhU_syL2plb8Q" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_seller_refund_exceeds_captures", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:LGJK7icUlgNKsoHH_XKqUK64oEAPF_d2U2FOrQTuJ-I", + "order_id": "order_v09_seller_refund_exceeds_captures", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_seller_refund_exceeds_captures", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "seller_id": "seller_a", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:LGJK7icUlgNKsoHH_XKqUK64oEAPF_d2U2FOrQTuJ-I", + "order_id": "order_v09_seller_refund_exceeds_captures", + "prev": "sha-256:aMz6nOAleUlR5Fias0o4YN8U7HysjEAhLjYdhVwU-8U", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 2000, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_seller_refund_exceeds_captures", + "event": { + "amount": 1000, + "currency": "USD", + "occurred_at": "2026-11-12T09:00:00Z", + "seller_id": "seller_b", + "status": "succeeded", + "type": "refund" + }, + "iat": 1794474060, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:LGJK7icUlgNKsoHH_XKqUK64oEAPF_d2U2FOrQTuJ-I", + "order_id": "order_v09_seller_refund_exceeds_captures", + "prev": "sha-256:o3TpJeXbOwlYDtulTn6dBqYH7QQAhp8dW4P-1qHw42M", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 2000, + "mandated": 5400, + "refunded": 1000 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [ + { + "receipt_index": 2, + "code": "receipt_exceeds_seller_total" + } + ], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v09_two_sellers.json b/common/payments/fixtures/ap2_order_receipts/v09_two_sellers.json new file mode 100644 index 0000000..cd3ea48 --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v09_two_sellers.json @@ -0,0 +1,191 @@ +{ + "id": "v09_two_sellers", + "title": "Marketplace as merchant of record, two sellers: captures verify", + "test_plan_vector": "9", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Platform Verification 3: SHOULD, when `event.seller_id` is present, also check per seller that succeeded captures do not exceed that seller's attributed total and that refunds do not exceed that seller's captures.", + "Edge Cases, Marketplace as merchant of record: the marketplace issues every receipt and sets `event.seller_id`, so a duplicate capture for one seller is detectable even when the chain's totals pass." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "inputs": { + "issuers": { + "https://marketplace.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "TaUGm9_vHgJoFIFsaKoHwP66ej_e1zhs63od2xv2V84", + "y": "1hBQgzroCLRPAITCUXAHhjnD2SpZS0sMgPrVwtvYyr4" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v09_two_sellers", + "business": "https://marketplace.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v09_two_sellers", + "checkout_id": "chk_v09_two_sellers", + "currency": "USD", + "sellers": { + "seller_a": { + "name": "Seller A" + }, + "seller_b": { + "name": "Seller B" + } + }, + "line_items": [ + { + "id": "li_a", + "seller_id": "seller_a", + "totals": [ + { + "type": "subtotal", + "amount": 2000 + }, + { + "type": "total", + "amount": 2000 + } + ] + }, + { + "id": "li_b", + "seller_id": "seller_b", + "totals": [ + { + "type": "subtotal", + "amount": 3400 + }, + { + "type": "total", + "amount": 3400 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDlfdHdvX3NlbGxlcnMiLCJldmVudCI6eyJhbW91bnQiOjU0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc5NDIzNjA2MCwiaXNzIjoiaHR0cHM6Ly9tYXJrZXRwbGFjZS5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjpCY3k3N3JxUnZTSlFkQkVrNnhaVXlITnRJSTR2bW1VcWozQmU0cFJ3djVBIiwib3JkZXJfaWQiOiJvcmRlcl92MDlfdHdvX3NlbGxlcnMiLCJwcmV2IjpudWxsLCJzZXEiOjEsInRvdGFscyI6eyJhdXRob3JpemVkIjo1NDAwLCJjYXB0dXJlZCI6MCwibWFuZGF0ZWQiOjU0MDAsInJlZnVuZGVkIjowfX0.qGCU-h94oH8Gl3N6tSaOw4lQO3jrEtuUKzP9Jk5qwQZnvlKLDWhZgTvp9qJpQim6TW28B4JaK2U7yH21lEgKNA", + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MDlfdHdvX3NlbGxlcnMiLCJldmVudCI6eyJhbW91bnQiOjIwMDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWR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WRCRWs2eFpVeUhOdElJNHZtbVVxajNCZTRwUnd2NUEiLCJvcmRlcl9pZCI6Im9yZGVyX3YwOV90d29fc2VsbGVycyIsInByZXYiOiJzaGEtMjU2OmJqN1hkdlNqVnhHOTRfRjBxdDZRaDRDQVVLUW1KalU1Rjhmb0pWTzdiTDgiLCJzZXEiOjMsInRvdGFscyI6eyJhdXRob3JpemVkIjo1NDAwLCJjYXB0dXJlZCI6NTQwMCwibWFuZGF0ZWQiOjU0MDAsInJlZnVuZGVkIjowfX0.lZaG5n-fC-nKU9Mf_Md_7t2y0UfmG1BuPrMjTMwLG1iNRyYzH-iVgYlC48bCWOvbdy5mii__lvkDe0y4whS7AA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_two_sellers", + "event": { + "amount": 5400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:Bcy77rqRvSJQdBEk6xZUyHNtII4vmmUqj3Be4pRwv5A", + "order_id": "order_v09_two_sellers", + "prev": null, + "seq": 1, + "totals": { + "authorized": 5400, + "captured": 0, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_two_sellers", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "seller_id": "seller_a", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:Bcy77rqRvSJQdBEk6xZUyHNtII4vmmUqj3Be4pRwv5A", + "order_id": "order_v09_two_sellers", + "prev": "sha-256:6fWwk0G8oVFtb-Ph9OWlh8gF0lNScz0hNR9Y4s8CBik", + "seq": 2, + "totals": { + "authorized": 5400, + "captured": 2000, + "mandated": 5400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v09_two_sellers", + "event": { + "amount": 3400, + "currency": "USD", + "occurred_at": "2026-11-11T18:04:00Z", + "seller_id": "seller_b", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794420300, + "iss": "https://marketplace.example/.well-known/ucp", + "mandate_ref": "sha-256:Bcy77rqRvSJQdBEk6xZUyHNtII4vmmUqj3Be4pRwv5A", + "order_id": "order_v09_two_sellers", + "prev": "sha-256:bj7XdvSjVxG94_F0qt6Qh4CAUKQmJjU5F8foJVO7bL8", + "seq": 3, + "totals": { + "authorized": 5400, + "captured": 5400, + "mandated": 5400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v10_iss_mismatch.json b/common/payments/fixtures/ap2_order_receipts/v10_iss_mismatch.json new file mode 100644 index 0000000..ce7b0ed --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v10_iss_mismatch.json @@ -0,0 +1,275 @@ +{ + "id": "v10_iss_mismatch", + "title": "A receipt whose iss does not match its mandate", + "test_plan_vector": "10", + "spec": [ + "Platform Verification 1: MUST verify each receipt's signature against the `keys` of the business named in `iss`, and MUST treat a receipt whose `iss` is not the business that signed the checkout covered by `mandate_ref` as `receipt_mandate_unknown`.", + "Edge Cases, Several merchants of record in one Order: each has its own mandate and keys, so each `(iss, mandate_ref)` pair is an independent chain." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "Receipt 4 carries seller A's mandate_ref with iss seller-b and is signed with seller-b's key. Both valid chains still verify.", + "inputs": { + "issuers": { + "https://seller-a.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "VKICPtz5xDPI-XMiFoRnI3HPtiVP00giqky-gi4e7Ls", + "y": "hnCDK0ntvGeJGSzDgud6IxCN-Zwntg73ofncIEQd4p4" + } + ] + }, + "https://seller-b.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "WtGteYCbnI31nfLnpr0PWZ7jeN6r_79-ETXrpMmr4DA", + "y": "ra8GzmWu3D2bQ0D9AGtuEHQKbXYd2tJU_Wn8TLCOxYA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v10_iss_mismatch_seller_a", + "business": "https://seller-a.example/.well-known/ucp" + }, + { + "credential_token": "test_only_payment_mandate_v10_iss_mismatch_seller_b", + "business": "https://seller-b.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v10_iss_mismatch", + "checkout_id": "chk_v10_iss_mismatch", + "currency": "USD", + "sellers": { + "seller_a": { + "name": "Seller A", + "profile": "https://seller-a.example/.well-known/ucp" + }, + "seller_b": { + "name": "Seller B", + "profile": "https://seller-b.example/.well-known/ucp" + } + }, + "line_items": [ + { + "id": "li_a", + "seller_id": "seller_a", + "totals": [ + { + "type": "subtotal", + "amount": 2000 + }, + { + "type": "total", + "amount": 2000 + } + ] + }, + { + "id": "li_b", + "seller_id": "seller_b", + "totals": [ + { + "type": "subtotal", + "amount": 3400 + }, + { + "type": "total", + "amount": 3400 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MTBfaXNzX21pc21hdGNoIiwiZXZl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jAyNi0xMS0xMFQxODowNDowMFoiLCJzdGF0dXMiOiJzdWNjZWVkZWQiLCJ0eXBlIjoiY2FwdHVyZSJ9LCJpYXQiOjE3OTQzMzM5MDAsImlzcyI6Imh0dHBzOi8vc2VsbGVyLWIuZXhhbXBsZS8ud2VsbC1rbm93bi91Y3AiLCJtYW5kYXRlX3JlZiI6InNoYS0yNTY6TWJkNG00OVVoTmxlTm8tN192UWtqSlpXS0V6b0pQLUFmOUNsZFZiWVpqSSIsIm9yZGVyX2lkIjoib3JkZXJfdjEwX2lzc19taXNtYXRjaCIsInByZXYiOm51bGwsInNlcSI6MSwidG90YWxzIjp7ImF1dGhvcml6ZWQiOjIwMDAsImNhcHR1cmVkIjoyMDAwLCJtYW5kYXRlZCI6MjAwMCwicmVmdW5kZWQiOjB9fQ.E-wPT8fBVxeWjTXXZL74Gj4EzyPMnscH7GIGUdVtxg9_KQ9-iSg5gt5ofW8keA2Bim_9bhkV41wgRy61aKCsKw" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_iss_mismatch", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://seller-a.example/.well-known/ucp", + "mandate_ref": "sha-256:Mbd4m49UhNleNo-7_vQkjJZWKEzoJP-Af9CldVbYZjI", + "order_id": "order_v10_iss_mismatch", + "prev": null, + "seq": 1, + "totals": { + "authorized": 2000, + "captured": 0, + "mandated": 2000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_iss_mismatch", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "seller_id": "seller_a", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://seller-a.example/.well-known/ucp", + "mandate_ref": "sha-256:Mbd4m49UhNleNo-7_vQkjJZWKEzoJP-Af9CldVbYZjI", + "order_id": "order_v10_iss_mismatch", + "prev": "sha-256:fUf5Vx8QZ2a8mXVQJMcy1d78qR5FYBCoy7CvuGl_rag", + "seq": 2, + "totals": { + "authorized": 2000, + "captured": 2000, + "mandated": 2000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_iss_mismatch", + "event": { + "amount": 3400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://seller-b.example/.well-known/ucp", + "mandate_ref": "sha-256:9ciflTYNdNF-DTQHZkO447n0wtt9P3M3iJCEkmt5WSM", + "order_id": "order_v10_iss_mismatch", + "prev": null, + "seq": 1, + "totals": { + "authorized": 3400, + "captured": 0, + "mandated": 3400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_iss_mismatch", + "event": { + "amount": 3400, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "seller_id": "seller_b", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://seller-b.example/.well-known/ucp", + "mandate_ref": "sha-256:9ciflTYNdNF-DTQHZkO447n0wtt9P3M3iJCEkmt5WSM", + "order_id": "order_v10_iss_mismatch", + "prev": "sha-256:qStD-xlncxzbW-kT7tyvXl4Etqr79Gaw6bzkJBR42DM", + "seq": 2, + "totals": { + "authorized": 3400, + "captured": 3400, + "mandated": 3400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_iss_mismatch", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://seller-b.example/.well-known/ucp", + "mandate_ref": "sha-256:Mbd4m49UhNleNo-7_vQkjJZWKEzoJP-Af9CldVbYZjI", + "order_id": "order_v10_iss_mismatch", + "prev": null, + "seq": 1, + "totals": { + "authorized": 2000, + "captured": 2000, + "mandated": 2000, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [ + { + "receipt_index": 4, + "code": "receipt_mandate_unknown" + } + ], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v10_two_merchants_of_record.json b/common/payments/fixtures/ap2_order_receipts/v10_two_merchants_of_record.json new file mode 100644 index 0000000..6f38058 --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v10_two_merchants_of_record.json @@ -0,0 +1,240 @@ +{ + "id": "v10_two_merchants_of_record", + "title": "Two merchants of record in one order: both chains verify", + "test_plan_vector": "10", + "spec": [ + "Platform Verification 1: MUST verify each receipt's signature against the `keys` of the business named in `iss`, and MUST treat a receipt whose `iss` is not the business that signed the checkout covered by `mandate_ref` as `receipt_mandate_unknown`.", + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Edge Cases, Several merchants of record in one Order: each has its own mandate and keys, so each `(iss, mandate_ref)` pair is an independent chain." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "inputs": { + "issuers": { + "https://seller-a.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "VKICPtz5xDPI-XMiFoRnI3HPtiVP00giqky-gi4e7Ls", + "y": "hnCDK0ntvGeJGSzDgud6IxCN-Zwntg73ofncIEQd4p4" + } + ] + }, + "https://seller-b.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "WtGteYCbnI31nfLnpr0PWZ7jeN6r_79-ETXrpMmr4DA", + "y": "ra8GzmWu3D2bQ0D9AGtuEHQKbXYd2tJU_Wn8TLCOxYA" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v10_two_merchants_of_record_seller_a", + "business": "https://seller-a.example/.well-known/ucp" + }, + { + "credential_token": "test_only_payment_mandate_v10_two_merchants_of_record_seller_b", + "business": "https://seller-b.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v10_two_merchants_of_record", + "checkout_id": "chk_v10_two_merchants_of_record", + "currency": "USD", + "sellers": { + "seller_a": { + "name": "Seller A", + "profile": "https://seller-a.example/.well-known/ucp" + }, + "seller_b": { + "name": "Seller B", + "profile": "https://seller-b.example/.well-known/ucp" + } + }, + "line_items": [ + { + "id": "li_a", + "seller_id": "seller_a", + "totals": [ + { + "type": "subtotal", + "amount": 2000 + }, + { + "type": "total", + "amount": 2000 + } + ] + }, + { + "id": "li_b", + "seller_id": "seller_b", + "totals": [ + { + "type": "subtotal", + "amount": 3400 + }, + { + "type": "total", + "amount": 3400 + } + ] + } + ], + "adjustments": [], + "totals": [ + { + "type": "subtotal", + "amount": 5400 + }, + { + "type": "total", + "amount": 5400 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MTBfdHdvX21lcmNoYW50c19vZl9yZWNvcmQiLCJldmVudCI6eyJhbW91bnQiOjIwMDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTA5VDE0OjUzOjIwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOi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1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MTBfdHdvX21lcmNoYW50c19vZl9yZWNvcmQiLCJldmVudCI6eyJhbW91bnQiOjM0MDAsImN1cnJlbmN5IjoiVVNEIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTEwVDE4OjA0OjAwWiIsInNlbGxlcl9pZCI6InNlbGxlcl9iIiwic3RhdHVzIjoic3VjY2VlZGVkIiwidHlwZSI6ImNhcHR1cmUifSwiaWF0IjoxNzk0MzMzOTAwLCJpc3MiOiJodHRwczovL3NlbGxlci1iLmV4YW1wbGUvLndlbGwta25vd24vdWNwIiwibWFuZGF0ZV9yZWYiOiJzaGEtMjU2OjJrd3kxbTk0T3VRRlVfYVFBZ0pGcThyZTc1VURYVGJDWTdrN0kwMVNHUmsiLCJvcmRlcl9pZCI6Im9yZGVyX3YxMF90d29fbWVyY2hhbnRzX29mX3JlY29yZCIsInByZXYiOiJzaGEtMjU2OlROcU1lWHdVS0ZBRDJ3NVBLdmVVRmxnQ1ljTmlhcmd1Rlp1SFBuYjNoaHciLCJzZXEiOjIsInRvdGFscyI6eyJhdXRob3JpemVkIjozNDAwLCJjYXB0dXJlZCI6MzQwMCwibWFuZGF0ZWQiOjM0MDAsInJlZnVuZGVkIjowfX0.YBIb9cNysDa85F8wzPYhkaL34xYI_XuPSjhBwP9KkXgDvAgYm_h63KmcKPD3lOV2SJPtLvWn-ej0bmgLZm6Z3A" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_two_merchants_of_record", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://seller-a.example/.well-known/ucp", + "mandate_ref": "sha-256:mPv7e-SorM_R4ozQ3otB3SwLrcG1pFlmB73bSig_Xd4", + "order_id": "order_v10_two_merchants_of_record", + "prev": null, + "seq": 1, + "totals": { + "authorized": 2000, + "captured": 0, + "mandated": 2000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_two_merchants_of_record", + "event": { + "amount": 2000, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "seller_id": "seller_a", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://seller-a.example/.well-known/ucp", + "mandate_ref": "sha-256:mPv7e-SorM_R4ozQ3otB3SwLrcG1pFlmB73bSig_Xd4", + "order_id": "order_v10_two_merchants_of_record", + "prev": "sha-256:rvykycEE6-0VTlKrACTDo0FK9jeeZeValA42etLCqec", + "seq": 2, + "totals": { + "authorized": 2000, + "captured": 2000, + "mandated": 2000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_two_merchants_of_record", + "event": { + "amount": 3400, + "currency": "USD", + "occurred_at": "2026-11-09T14:53:20Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1794236060, + "iss": "https://seller-b.example/.well-known/ucp", + "mandate_ref": "sha-256:2kwy1m94OuQFU_aQAgJFq8re75UDXTbCY7k7I01SGRk", + "order_id": "order_v10_two_merchants_of_record", + "prev": null, + "seq": 1, + "totals": { + "authorized": 3400, + "captured": 0, + "mandated": 3400, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v10_two_merchants_of_record", + "event": { + "amount": 3400, + "currency": "USD", + "occurred_at": "2026-11-10T18:04:00Z", + "seller_id": "seller_b", + "status": "succeeded", + "type": "capture" + }, + "iat": 1794333900, + "iss": "https://seller-b.example/.well-known/ucp", + "mandate_ref": "sha-256:2kwy1m94OuQFU_aQAgJFq8re75UDXTbCY7k7I01SGRk", + "order_id": "order_v10_two_merchants_of_record", + "prev": "sha-256:TNqMeXwUKFAD2w5PKveUFlgCYcNiarguFZuHPnb3hhw", + "seq": 2, + "totals": { + "authorized": 3400, + "captured": 3400, + "mandated": 3400, + "refunded": 0 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v11_lodging_partial_refund.json b/common/payments/fixtures/ap2_order_receipts/v11_lodging_partial_refund.json new file mode 100644 index 0000000..19431ec --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v11_lodging_partial_refund.json @@ -0,0 +1,183 @@ +{ + "id": "v11_lodging_partial_refund", + "title": "Lodging partial refund matching the cancellation adjustment", + "test_plan_vector": "11", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Platform Verification 4: SHOULD reconcile each `refund` receipt that carries `event.ref.adjustment_id` against that Order adjustment. A mismatch is a commercial problem, not a cryptographic one: the receipt remains valid.", + "Edge Cases, Partial refunds under a cancellation policy: the refund receipt proves the money movement and cites the cancellation adjustment through `event.ref.adjustment_id`; whether the amount was commercially correct is checked against that adjustment, not inside the receipt." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "inputs": { + "issuers": { + "https://hotel.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "rlpdUvhzJJYYp5_j8rmnVNxmtuY3JjGqmPmzfvJSSFU", + "y": "D4aPYVBPScGh-hyuwkUFBNk1IOqKALJXZfGo7jqfHOI" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v11_lodging_partial_refund", + "business": "https://hotel.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v11_lodging_partial_refund", + "checkout_id": "chk_v11_lodging_partial_refund", + "currency": "EUR", + "line_items": [ + { + "id": "li_room", + "totals": [ + { + "type": "subtotal", + "amount": 60000 + }, + { + "type": "total", + "amount": 60000 + } + ] + } + ], + "adjustments": [ + { + "id": "adj_cancel_1", + "type": "cancellation", + "occurred_at": "2026-11-14T15:30:00Z", + "status": "completed", + "totals": [ + { + "type": "total", + "amount": -45000 + } + ], + "description": "Cancelled under the booking's cancellation policy: EUR 150.00 penalty retained, EUR 450.00 refundable." + } + ], + "totals": [ + { + "type": "subtotal", + "amount": 60000 + }, + { + "type": "total", + "amount": 60000 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MTFfbG9kZ2luZ19wYXJ0aWFsX3JlZnVuZCIsImV2ZW50Ijp7ImFtb3VudCI6NjAwMDAsImN1cnJlbmN5IjoiRVVSIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTAxVDA5OjAwOjAwWiIsInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJhdXRob3JpemF0aW9uIn0sImlhdCI6MTc5MzUyMzY2MCwiaXNzIjoiaHR0cHM6Ly9ob3RlbC5leGFtcGxlLy53ZWxsLWtub3duL3VjcCIsIm1hbmRhdGVfcmVmIjoic2hhLTI1NjozZzdwNUJ6bWM4ZldncTB6bndnV0psSnZWd0VuNGRZQzNRWlRaU01KN0pBIiwib3JkZXJfaWQiOiJvcmRlcl92MTFfbG9kZ2luZ19wYXJ0aWFsX3JlZnVuZCIsInByZXYiOm51bGwsInNlcSI6MSwidG90YWxzIjp7ImF1dGhvcml6ZWQiOjYwMDAwLCJjYXB0dXJlZCI6MCwibWFuZGF0ZWQiOjYwMDAwLCJyZWZ1bmRlZCI6MH19.OyFqMZ71lmthWvwr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CI6NDUwMDAsImN1cnJlbmN5IjoiRVVSIiwib2NjdXJyZWRfYXQiOiIyMDI2LTExLTE0VDE2OjAwOjAwWiIsInJlZiI6eyJhZGp1c3RtZW50X2lkIjoiYWRqX2NhbmNlbF8xIn0sInN0YXR1cyI6InN1Y2NlZWRlZCIsInR5cGUiOiJyZWZ1bmQifSwiaWF0IjoxNzk0NjcyMDYwLCJpc3MiOiJodHRwczovL2hvdGVsLmV4YW1wbGUvLndlbGwta25vd24vdWNwIiwibWFuZGF0ZV9yZWYiOiJzaGEtMjU2OjNnN3A1QnptYzhmV2dxMHpud2dXSmxKdlZ3RW40ZFlDM1FaVFpTTUo3SkEiLCJvcmRlcl9pZCI6Im9yZGVyX3YxMV9sb2RnaW5nX3BhcnRpYWxfcmVmdW5kIiwicHJldiI6InNoYS0yNTY6TWxFamFYY1ZGXzR5Q1p6V3hORzFxZUFib1Z3LXBReDI2SzVtYmZRSlYxZyIsInNlcSI6MywidG90YWxzIjp7ImF1dGhvcml6ZWQiOjYwMDAwLCJjYXB0dXJlZCI6NjAwMDAsIm1hbmRhdGVkIjo2MDAwMCwicmVmdW5kZWQiOjQ1MDAwfX0.E1ti_SxoZcPFqIh4AX4u_FFqj3l5fbBtk8MgDWW9NGI5kPUuD4bTs7XExsl98sTn9MMUhcilIzzUA3UeUW_YbA" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v11_lodging_partial_refund", + "event": { + "amount": 60000, + "currency": "EUR", + "occurred_at": "2026-11-01T09:00:00Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1793523660, + "iss": "https://hotel.example/.well-known/ucp", + "mandate_ref": "sha-256:3g7p5Bzmc8fWgq0znwgWJlJvVwEn4dYC3QZTZSMJ7JA", + "order_id": "order_v11_lodging_partial_refund", + "prev": null, + "seq": 1, + "totals": { + "authorized": 60000, + "captured": 0, + "mandated": 60000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v11_lodging_partial_refund", + "event": { + "amount": 60000, + "currency": "EUR", + "occurred_at": "2026-11-01T09:00:30Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1793523690, + "iss": "https://hotel.example/.well-known/ucp", + "mandate_ref": "sha-256:3g7p5Bzmc8fWgq0znwgWJlJvVwEn4dYC3QZTZSMJ7JA", + "order_id": "order_v11_lodging_partial_refund", + "prev": "sha-256:AHyh1NqFs_zsRbuaY5gDalP4rtsSfLR0b3MEte0xKy4", + "seq": 2, + "totals": { + "authorized": 60000, + "captured": 60000, + "mandated": 60000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v11_lodging_partial_refund", + "event": { + "amount": 45000, + "currency": "EUR", + "occurred_at": "2026-11-14T16:00:00Z", + "ref": { + "adjustment_id": "adj_cancel_1" + }, + "status": "succeeded", + "type": "refund" + }, + "iat": 1794672060, + "iss": "https://hotel.example/.well-known/ucp", + "mandate_ref": "sha-256:3g7p5Bzmc8fWgq0znwgWJlJvVwEn4dYC3QZTZSMJ7JA", + "order_id": "order_v11_lodging_partial_refund", + "prev": "sha-256:MlEjaXcVF_4yCZzWxNG1qeAboVw-pQx26K5mbfQJV1g", + "seq": 3, + "totals": { + "authorized": 60000, + "captured": 60000, + "mandated": 60000, + "refunded": 45000 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [] + } +} diff --git a/common/payments/fixtures/ap2_order_receipts/v12_lodging_refund_mismatch.json b/common/payments/fixtures/ap2_order_receipts/v12_lodging_refund_mismatch.json new file mode 100644 index 0000000..cf74552 --- /dev/null +++ b/common/payments/fixtures/ap2_order_receipts/v12_lodging_refund_mismatch.json @@ -0,0 +1,189 @@ +{ + "id": "v12_lodging_refund_mismatch", + "title": "Lodging refund that disagrees with the cancellation adjustment", + "test_plan_vector": "12", + "spec": [ + "Platform Verification 2: MUST evaluate `seq` and `prev` continuity, `captured` ≤ `mandated` and `refunded` ≤ `captured` per `(iss, mandate_ref)` chain.", + "Platform Verification 4: SHOULD reconcile each `refund` receipt that carries `event.ref.adjustment_id` against that Order adjustment. A mismatch is a commercial problem, not a cryptographic one: the receipt remains valid.", + "Edge Cases, Partial refunds under a cancellation policy: the refund receipt proves the money movement and cites the cancellation adjustment through `event.ref.adjustment_id`; whether the amount was commercially correct is checked against that adjustment, not inside the receipt." + ], + "signing": "TEST-ONLY P-256 keys derived from fixed labels in common/payments/ap2_receipt_fixtures.py; deterministic ECDSA (RFC 6979). Never use them outside these vectors.", + "notes": "The receipt chain verifies; the refund (EUR 300.00) disagrees with the adjustment it cites (EUR 450.00). Reported as a reconciliation finding, separately from the receipt outcomes.", + "inputs": { + "issuers": { + "https://hotel.example/.well-known/ucp": { + "keys": [ + { + "kty": "EC", + "crv": "P-256", + "kid": "test_only_2026", + "use": "sig", + "alg": "ES256", + "x": "rlpdUvhzJJYYp5_j8rmnVNxmtuY3JjGqmPmzfvJSSFU", + "y": "D4aPYVBPScGh-hyuwkUFBNk1IOqKALJXZfGo7jqfHOI" + } + ] + } + }, + "mandates": [ + { + "credential_token": "test_only_payment_mandate_v12_lodging_refund_mismatch", + "business": "https://hotel.example/.well-known/ucp" + } + ], + "order": { + "id": "order_v12_lodging_refund_mismatch", + "checkout_id": "chk_v12_lodging_refund_mismatch", + "currency": "EUR", + "line_items": [ + { + "id": "li_room", + "totals": [ + { + "type": "subtotal", + "amount": 60000 + }, + { + "type": "total", + "amount": 60000 + } + ] + } + ], + "adjustments": [ + { + "id": "adj_cancel_1", + "type": "cancellation", + "occurred_at": "2026-11-14T15:30:00Z", + "status": "completed", + "totals": [ + { + "type": "total", + "amount": -45000 + } + ], + "description": "Cancelled under the booking's cancellation policy: EUR 150.00 penalty retained, EUR 450.00 refundable." + } + ], + "totals": [ + { + "type": "subtotal", + "amount": 60000 + }, + { + "type": "total", + "amount": 60000 + } + ], + "ap2": { + "receipts": [ + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MTJfbG9kZ2luZ19yZWZ1bmRfbWlzbWF0Y2giLCJldmVudCI6eyJhbW91bnQiOjYwMDAwLCJjdXJyZW5jeSI6IkVVUiIsIm9jY3VycmVkX2F0IjoiMjAyNi0xMS0wMVQwOTowMDowMFoiLCJzdGF0dXMiOiJzdWNjZWVkZWQiLCJ0eXBlIjoiYXV0aG9yaXphdGlvbiJ9LCJpYXQiOjE3OTM1MjM2NjAsImlzcyI6Imh0dHBzOi8vaG90ZWwuZXhhbXBsZS8ud2VsbC1rbm93bi91Y3AiLCJtYW5kYXRlX3JlZiI6InNoYS0yNTY6NF9lWVl5ck5PQXR6a21haVhNU2JnZTFRVGJQR1lxM05ETEJtUFB6U21NYyIsIm9yZGVyX2lkIjoib3JkZXJfdjEyX2xvZGdpbmdfcmVmdW5kX21pc21hdGNoIiwicHJldiI6bnVsbCwic2VxIjoxLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NjAwMDAsImNhcHR1cmVkIjowLCJtYW5kYXRlZCI6NjAwMDAsInJlZnVuZGVkIjowfX0.q04DCLikkO14s5o4WErv4UxKnmOjj2XAVgzn9lFviLx5Brg5W6QKJUPD_9RVomWAk9hcn_Pb-lCP-DMiZ1DK-A", + "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3Rfb25seV8yMDI2IiwidHlwIjoidWNwLWFwMi1yZWNlaXB0K2p3dCJ9.eyJjaGVja291dF9pZCI6ImNoa192MTJfbG9kZ2luZ19yZWZ1bmRfbWlzbWF0Y2giLCJldmVudCI6eyJhbW91bnQiOjYwMDAwLCJjdXJyZW5jeSI6IkVVUiIsIm9jY3VycmVk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cmVmIjoic2hhLTI1Njo0X2VZWXlyTk9BdHprbWFpWE1TYmdlMVFUYlBHWXEzTkRMQm1QUHpTbU1jIiwib3JkZXJfaWQiOiJvcmRlcl92MTJfbG9kZ2luZ19yZWZ1bmRfbWlzbWF0Y2giLCJwcmV2Ijoic2hhLTI1NjpPR3pqM0toZ21MWGlTenc5Ny1JRW0zUlZJZnJBRlJBZkY0QTlsRzUtbl8wIiwic2VxIjozLCJ0b3RhbHMiOnsiYXV0aG9yaXplZCI6NjAwMDAsImNhcHR1cmVkIjo2MDAwMCwibWFuZGF0ZWQiOjYwMDAwLCJyZWZ1bmRlZCI6MzAwMDB9fQ.j3-narnqg5n7-LyEzzvsokY9TiCvYeZELNKt8nMU8Ihb9YK4UNrV89z80u2C_6v-tZR5zcVIOJvu0kGj0JD-sw" + ] + } + } + }, + "decoded_receipts": [ + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v12_lodging_refund_mismatch", + "event": { + "amount": 60000, + "currency": "EUR", + "occurred_at": "2026-11-01T09:00:00Z", + "status": "succeeded", + "type": "authorization" + }, + "iat": 1793523660, + "iss": "https://hotel.example/.well-known/ucp", + "mandate_ref": "sha-256:4_eYYyrNOAtzkmaiXMSbge1QTbPGYq3NDLBmPPzSmMc", + "order_id": "order_v12_lodging_refund_mismatch", + "prev": null, + "seq": 1, + "totals": { + "authorized": 60000, + "captured": 0, + "mandated": 60000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v12_lodging_refund_mismatch", + "event": { + "amount": 60000, + "currency": "EUR", + "occurred_at": "2026-11-01T09:00:30Z", + "status": "succeeded", + "type": "capture" + }, + "iat": 1793523690, + "iss": "https://hotel.example/.well-known/ucp", + "mandate_ref": "sha-256:4_eYYyrNOAtzkmaiXMSbge1QTbPGYq3NDLBmPPzSmMc", + "order_id": "order_v12_lodging_refund_mismatch", + "prev": "sha-256:4knsdL6dKTZoxtxSpZQ6A99Y8dZRAoPGs87rfmvT1Mc", + "seq": 2, + "totals": { + "authorized": 60000, + "captured": 60000, + "mandated": 60000, + "refunded": 0 + } + } + }, + { + "header": { + "alg": "ES256", + "kid": "test_only_2026", + "typ": "ucp-ap2-receipt+jwt" + }, + "payload": { + "checkout_id": "chk_v12_lodging_refund_mismatch", + "event": { + "amount": 30000, + "currency": "EUR", + "occurred_at": "2026-11-14T16:00:00Z", + "ref": { + "adjustment_id": "adj_cancel_1" + }, + "status": "succeeded", + "type": "refund" + }, + "iat": 1794672060, + "iss": "https://hotel.example/.well-known/ucp", + "mandate_ref": "sha-256:4_eYYyrNOAtzkmaiXMSbge1QTbPGYq3NDLBmPPzSmMc", + "order_id": "order_v12_lodging_refund_mismatch", + "prev": "sha-256:OGzj3KhgmLXiSzw97-IEm3RVIfrAFRAfF4A9lG5-n_0", + "seq": 3, + "totals": { + "authorized": 60000, + "captured": 60000, + "mandated": 60000, + "refunded": 30000 + } + } + } + ], + "expected": { + "outcomes": [], + "warnings": [], + "reconciliation": [ + { + "receipt_index": 2, + "code": "reconciliation_adjustment_mismatch" + } + ] + } +} diff --git a/pyproject.toml b/pyproject.toml index 56fe0ee..eaa3593 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,7 @@ authors = [ ] dependencies = [ "absl-py>=1.0.0", + "cryptography>=44.0.0", "httpx>=0.26.0", "pydantic>=2.12.0", "ucp-sdk==0.4.6", diff --git a/runner.py b/runner.py index eda96d6..06b2d09 100644 --- a/runner.py +++ b/runner.py @@ -35,6 +35,8 @@ "common": [ "common.payments.card_credential_test", "common.payments.ap2_test", + "common.payments.ap2_receipt_vectors_test", + "common.payments.ap2_order_receipts_test", "common.payments.token_binding_test", ], "shopping": [