Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion conformance/inflow-specs.lock.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"repository": "inflowpayai/inflow-specs",
"revision": "c1b49718056739f43e92c34790ae8b58c1d3a382"
"revision": "20c518990672db7d29020ba22056a4c372d356c4"
}
10 changes: 9 additions & 1 deletion scripts/verify_distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ async def check():
MPP_CONSUMER = """
from importlib import util
from inflowpay.mpp import encode, decode, to_pympp_challenge, from_pympp_challenge
from inflowpay.mpp import get_inflow_transaction_id
transaction_id = '22222222-2222-4222-8222-222222222222'
receipt = dict(status='success', inflowTransactionId=transaction_id)
assert get_inflow_transaction_id(receipt) == transaction_id
from inflowpay.mpp.buyer import BuyerMethod, payment_transport
from inflowpay.mpp.seller import Seller
from inflowpay import ClientOptions
Expand Down Expand Up @@ -121,10 +125,14 @@ async def check_seller():
from importlib import util
from inflowpay.x402 import (
PaymentRequirements, declare_payment_identifier, generate_payment_id,
payment_identifier_entry,
payment_identifier_entry, get_inflow_transaction_id, SettleResponse, INFLOW_TRANSACTION,
)
from x402.schemas import PaymentRequirements as UpstreamRequirements
assert PaymentRequirements is UpstreamRequirements
transaction_id = '22222222-2222-4222-8222-222222222222'
settlement = SettleResponse(success=True, transaction='reference', network='inflow:1',
extensions={INFLOW_TRANSACTION: {'info': {'transactionId': transaction_id}}})
assert get_inflow_transaction_id(settlement) == transaction_id
entry = payment_identifier_entry(declare_payment_identifier(), generate_payment_id())
assert entry is not None and entry['info']['required'] is False
from inflowpay.x402.buyer import Buyer
Expand Down
3 changes: 2 additions & 1 deletion src/inflowpay/mpp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""InFlow MPP wire codecs. Decoding does not authenticate or settle a payment."""

from ._pympp import from_pympp_challenge, to_pympp_challenge
from ._pympp import from_pympp_challenge, get_inflow_transaction_id, to_pympp_challenge
from ._requests import validate_payload, validate_request
from ._wire import (
JsonValue,
Expand All @@ -26,6 +26,7 @@
"decode_receipt",
"encode",
"from_pympp_challenge",
"get_inflow_transaction_id",
"parse_challenge_header",
"parse_challenge_headers",
"render_challenge_header",
Expand Down
22 changes: 21 additions & 1 deletion src/inflowpay/mpp/_pympp.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import re
from copy import deepcopy
from dataclasses import dataclass, field, fields, replace

from mpp import Challenge, ChallengeEcho
from mpp import Challenge, ChallengeEcho, Receipt

from ._wire import (
MppCodecError,
Expand All @@ -14,6 +15,25 @@
)


def get_inflow_transaction_id(receipt: Receipt | WireObject) -> str | None:
"""Read the seller's Transaction UUID from a receipt or its decoded wire object."""
wire = (
object_value(decode(receipt.to_payment_receipt()))
if isinstance(receipt, Receipt)
else receipt
)
if wire.get("status") != "success":
return None
value = wire.get("inflowTransactionId")
if (
isinstance(value, str)
and len(value) == 36
and re.fullmatch(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", value, re.I)
):
return value
return None


@dataclass(frozen=True)
class _WireChallenge(Challenge):
_wire: WireObject = field(default_factory=dict, repr=False, compare=False)
Expand Down
3 changes: 3 additions & 0 deletions src/inflowpay/mpp/seller.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from .._runtime import Client
from ..options import ClientOptions
from ._pympp import get_inflow_transaction_id
from ._requests import validate_payload, validate_request
from ._wire import (
MppCodecError,
Expand Down Expand Up @@ -408,6 +409,8 @@ async def broadcast(self, credential: Credential, request: WireObject) -> Receip
if "receipt" not in response:
raise MppCredentialProblemError(response.get("problem"))
wire = decode_receipt(encode(response["receipt"]))
if get_inflow_transaction_id(wire) is None:
wire.pop("inflowTransactionId", None)
# Card settlement must identify the purchase before releasing its resource.
if (
credential.challenge.method in ("stripe", "card")
Expand Down
4 changes: 4 additions & 0 deletions src/inflowpay/x402/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
from ._core import (
INFLOW_AMOUNT_SCALE,
INFLOW_EIP7702_GAS_SPONSORING,
INFLOW_TRANSACTION,
NETWORK_INFLOW,
PAYMENT_IDENTIFIER,
X402_VERSION,
IdentifierDeclaration,
declare_payment_identifier,
declare_sponsorship,
generate_payment_id,
get_inflow_transaction_id,
normalize_decimal_string,
payment_identifier_entry,
read_payment_identifier,
Expand All @@ -30,6 +32,7 @@
__all__ = [
"INFLOW_AMOUNT_SCALE",
"INFLOW_EIP7702_GAS_SPONSORING",
"INFLOW_TRANSACTION",
"NETWORK_INFLOW",
"PAYMENT_IDENTIFIER",
"X402_VERSION",
Expand All @@ -45,6 +48,7 @@
"declare_payment_identifier",
"declare_sponsorship",
"generate_payment_id",
"get_inflow_transaction_id",
"normalize_decimal_string",
"payment_identifier_entry",
"read_payment_identifier",
Expand Down
18 changes: 18 additions & 0 deletions src/inflowpay/x402/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
from copy import deepcopy
from typing import TypedDict, cast

from x402.schemas import SettleResponse

X402_VERSION = 2
NETWORK_INFLOW = "inflow:1"
INFLOW_AMOUNT_SCALE = 18
PAYMENT_IDENTIFIER = "payment-identifier"
INFLOW_EIP7702_GAS_SPONSORING = "inflowEip7702GasSponsoring"
INFLOW_TRANSACTION = "inflow-transaction"
_ID_PATTERN = "^[a-zA-Z0-9_-]+$"


Expand Down Expand Up @@ -57,6 +60,21 @@ def _object(value: object) -> dict[str, object]:
return cast(dict[str, object], value) if isinstance(value, dict) else {}


def get_inflow_transaction_id(result: SettleResponse) -> str | None:
"""Read the seller's Transaction UUID without substituting the settlement reference."""
if not result.success:
return None
extension = _object((result.extensions or {}).get(INFLOW_TRANSACTION))
value = _object(extension.get("info")).get("transactionId")
if (
isinstance(value, str)
and len(value) == 36
and re.fullmatch(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", value, re.I)
):
return value
return None


def read_payment_identifier(value: object) -> IdentifierDeclaration | None:
"""Read a declaration without sharing its mutable data with the caller."""
fields = _object(value)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_mpp_seller.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
}
],
}
RECEIPT = {
RECEIPT: WireObject = {
"method": "inflow",
"status": "success",
"reference": "payment",
Expand Down
205 changes: 205 additions & 0 deletions tests/test_transaction_correlation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import base64
import json
from copy import deepcopy
from dataclasses import replace
from typing import Literal

import httpx
import pytest
from mpp import Receipt

from inflowpay.mpp import JsonValue, WireObject, decode_receipt, encode
from inflowpay.mpp import get_inflow_transaction_id as mpp_transaction_id
from inflowpay.mpp.seller import Seller
from inflowpay.x402 import INFLOW_TRANSACTION, SettleResponse
from inflowpay.x402 import get_inflow_transaction_id as x402_transaction_id
from test_mpp_seller import (
RECEIPT,
TERMS,
Platform,
app_for,
credential_for,
options,
wire_credential,
)
from test_x402_upfront import FlowPlatform, merchant, payment_headers

TRANSACTION_ID = "abcdefab-1234-4567-89ab-abcdef123456"
EXTENSION = {
"info": {"transactionId": TRANSACTION_ID},
"schema": {
"type": "object",
"properties": {"transactionId": {"type": "string", "format": "uuid"}},
"required": ["transactionId"],
},
}
INVALID_IDS: list[JsonValue] = [
None,
True,
42,
[],
{},
"",
"not-a-uuid",
"x" * 36,
"x" * 20000,
TRANSACTION_ID + "\n",
]


@pytest.mark.parametrize("value", [*INVALID_IDS, TRANSACTION_ID, TRANSACTION_ID.upper()])
async def test_mpp_optional_transaction_id(value: JsonValue) -> None:
wire: WireObject = {**RECEIPT, "inflowTransactionId": value}
before = deepcopy(wire)
expected = value if value in (TRANSACTION_ID, TRANSACTION_ID.upper()) else None
assert mpp_transaction_id(wire) == expected
assert decode_receipt(encode(wire)).get("inflowTransactionId") == value
platform = Platform()
platform.result = {"receipt": wire}
async with await Seller.create(options(platform)) as seller:
receipt = await seller.broadcast(wire_credential(), TERMS)
assert mpp_transaction_id(receipt) == expected
header = receipt.to_payment_receipt()
decoded = decode_receipt(header)
assert mpp_transaction_id(decoded) == expected
assert ("inflowTransactionId" in decoded) is (expected is not None)
assert receipt.reference == RECEIPT["reference"]
assert decoded["custom"] == RECEIPT["custom"]
assert Receipt.from_payment_receipt(header).reference == receipt.reference
assert len(platform.requests) == 2
assert wire == before


def test_mpp_native_receipt_does_not_infer_transaction_id() -> None:
receipt = Receipt.from_payment_receipt(encode({**RECEIPT, "reference": TRANSACTION_ID}))
assert mpp_transaction_id(receipt) is None
assert (
mpp_transaction_id(replace(receipt, extra={"inflowTransactionId": TRANSACTION_ID})) is None
)
assert mpp_transaction_id({**RECEIPT, "reference": TRANSACTION_ID}) is None
assert mpp_transaction_id({"status": "failed", "inflowTransactionId": TRANSACTION_ID}) is None
assert mpp_transaction_id({"inflowTransactionId": TRANSACTION_ID}) is None


@pytest.mark.parametrize("present", [True, False])
async def test_mpp_framework_preserves_transaction_id(present: bool) -> None:
platform = Platform()
wire = {**RECEIPT, **({"inflowTransactionId": TRANSACTION_ID} if present else {})}
platform.result = {"receipt": wire}
async with (
await Seller.create(options(platform)) as seller,
httpx.AsyncClient(
transport=httpx.ASGITransport(app_for(seller)), base_url="https://seller.example"
) as client,
):
credential = await credential_for(client)
for _ in range(2):
response = await client.get("/paid", headers={"Authorization": credential})
assert response.status_code == 200
assert response.json() == {"ok": True}
decoded = decode_receipt(response.headers["payment-receipt"])
assert decoded == wire
assert mpp_transaction_id(decoded) == (TRANSACTION_ID if present else None)
assert [r.url.path for r in platform.requests] == ["/v1/mpp/config"] + [
"/v1/mpp/validate",
"/v1/mpp/broadcast",
] * 2


@pytest.mark.parametrize(
"extension",
[
None,
True,
42,
[],
"bad",
{},
{"info": None},
{"info": []},
{"info": "bad"},
{"info": {}},
*({"info": {"transactionId": value}} for value in INVALID_IDS),
EXTENSION,
{"info": {"transactionId": TRANSACTION_ID.upper()}},
],
)
def test_x402_transaction_id(extension: object) -> None:
response = SettleResponse(
success=True,
transaction="blockchain-reference",
network="eip155:8453",
extensions={INFLOW_TRANSACTION: extension, "custom": {"items": [1, None]}},
)
before = response.model_copy(deep=True)
expected = (
TRANSACTION_ID
if extension == EXTENSION
else TRANSACTION_ID.upper()
if extension == {"info": {"transactionId": TRANSACTION_ID.upper()}}
else None
)
assert x402_transaction_id(response) == expected
assert response == before
response.success = False
assert x402_transaction_id(response) is None


@pytest.mark.parametrize("extensions", [None, {}, {"other": EXTENSION}])
def test_x402_absence_does_not_infer_transaction_id(extensions: dict[str, object] | None) -> None:
response = SettleResponse(
success=True, transaction=TRANSACTION_ID, network="inflow:1", extensions=extensions
)
assert x402_transaction_id(response) is None


@pytest.mark.parametrize("flow", ["authorization", "upfront"])
@pytest.mark.parametrize("scheme", ["balance", "exact"])
@pytest.mark.parametrize("value", [TRANSACTION_ID, None, 42])
async def test_x402_framework_preserves_transaction_id(
flow: Literal["authorization", "upfront"], scheme: str, value: JsonValue
) -> None:
platform = FlowPlatform()
extensions = {
"custom": {"items": [1, None]},
**(
{INFLOW_TRANSACTION: {**EXTENSION, "info": {"transactionId": value}}}
if value is not None
else {}
),
}
platform.settlement["extensions"] = deepcopy(extensions)
before = deepcopy(platform.settlement)
async with merchant(platform, flow=flow, scheme=scheme) as (client, payment):
for _ in range(2):
response = await client.get("/paid", headers=payment_headers(payment))
assert response.status_code == 200
wire = json.loads(base64.b64decode(response.headers["payment-response"]))
receipt = SettleResponse.model_validate(wire)
assert receipt.success and receipt.transaction == "tx"
assert receipt.extensions == extensions
assert x402_transaction_id(receipt) == (
TRANSACTION_ID if value == TRANSACTION_ID else None
)
events = (
["verify", "handler", "settle"] if flow == "authorization" else ["settle", "handler"]
)
assert platform.events == events * 2
assert len(platform.settlements) == 2
assert platform.settlements[0] == platform.settlements[1]
assert INFLOW_TRANSACTION not in platform.settlements[0]["paymentPayload"]["extensions"]
assert payment.extensions is None
assert platform.settlement == before


@pytest.mark.parametrize("throws", [False, True])
async def test_x402_upfront_handler_failure_retains_transaction_id(throws: bool) -> None:
platform = FlowPlatform()
platform.settlement["extensions"] = {INFLOW_TRANSACTION: deepcopy(EXTENSION)}
async with merchant(platform, handler_status=500, throws=throws) as (client, payment):
response = await client.get("/paid", headers=payment_headers(payment))
assert response.status_code == 500
wire = json.loads(base64.b64decode(response.headers["payment-response"]))
assert x402_transaction_id(SettleResponse.model_validate(wire)) == TRANSACTION_ID
assert wire["transaction"] == "tx"
assert platform.events == ["settle", "handler"]
Loading