diff --git a/README.md b/README.md index cd8a811..4ca3e8d 100644 --- a/README.md +++ b/README.md @@ -580,6 +580,38 @@ These entry points authenticate the credential before reaching the Seller hooks. Validation is non-mutating; broadcast may still fail after successful validation. Never invoke the protected application handler based on validation alone. +### Request-time MPP pricing + +Use `seller.priced(callback)` as the method registered with `Mpp`. The callback +receives pympp's `Request` and returns charge input, synchronously or asynchronously: + +```python +import httpx +from mpp.server import Mpp, Request +from inflowpay.mpp import WireObject + + +async def price(request: Request) -> WireObject: + large = httpx.URL(request.url).params.get("bundle") == "large" + return {"amount": "0.05" if large else "0.01", "currency": "USDC"} + + +payments = Mpp(methods=[seller.priced(price)], realm="seller.example", secret_key=secret) +# Use @pay(payments.charge()) on the protected endpoint. +``` + +The callback runs for each request, including paid retries. Return consistent +terms for the same purchase; changed terms invalidate a previously quoted payment. +InFlow and Tempo inputs use the same units as `charge_request`; Stripe and CARD +use decimal USD amounts, converted to cents by their existing helpers. + +Request bodies are not read for pricing unless `needs_request_body=True` is passed +to `priced`. Then `request.body` contains the bytes and the framework handler can +still read them. Apply request-size limits in your application. Body access alone +does not bind a challenge to the body; use pympp's `body` route option when needed. +Callback errors prevent payment processing and propagate through pympp. Keep the +Seller open for the lifetime of the application. + ## Migrating from InFlow Python 0.3 This dependency upgrade requires an InFlow minor-version release. Integrations @@ -907,6 +939,39 @@ async def serve() -> None: asyncio.run(serve()) ``` +For request-time pricing in FastAPI or Starlette, import `payment_middleware` from +`inflowpay.x402.fastapi`. Route entries may be fixed `RouteConfig` objects or sync/async +callbacks returning a complete `RouteConfig`: + +```python +from fastapi import Request +from x402.http.types import RouteConfig +from inflowpay.x402.fastapi import payment_middleware + + +async def report_route(request: Request) -> RouteConfig: + price = "0.05 USDC" if request.query_params.get("bundle") == "large" else "0.01 USDC" + return await seller.route(price) + + +app.middleware("http")(payment_middleware({"GET /report": report_route}, resource_server)) +``` + +Each matching request resolves its route once, including paid retries. The callback +can select currency, payment methods, and sponsorship through `seller.route`; +verification, settlement, receipts, and server hooks remain upstream behavior. +Use upstream route patterns such as `GET /reports/:id`; this also preserves Bazaar +route metadata. Unmatched requests pass through without invoking the callback. + +The callback receives the framework's request. It does not read the body unless +your callback explicitly uses `await request.body()` or `await request.json()`; +these cached reads preserve the body for the application handler. Apply request-size +limits in your application and do not consume `request.stream()` in the callback. +Failed or empty route resolution raises before payment or application handlers run; +the application controls error handling and logging. Cancellation propagates. +Fixed-price middleware can continue +using the upstream import directly. + Both clients own their HTTP connections and close them when their context exits. `Seller.create()` requires an API key and preloads configuration and capabilities. Configuration reads are cached for one hour; `await seller.config(refresh=True)` diff --git a/examples/README.md b/examples/README.md index 60f1448..52b4a6f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -43,6 +43,12 @@ export MPP_SECRET_KEY="$(uv run python -c 'import secrets; print(secrets.token_h uv run --locked python -m examples.mpp_seller ``` +The Seller's request callback selects its own price on every call: **0.01 USDC** +for `/api/widgets` and **0.05 USDC** for `/api/widgets?bundle=large`. Fixed prices +can use `charge_request`, `stripe_request`, or `card_request`. For Stripe and CARD, the +callback selects **USD 1.25** or **USD 2.50**; the helpers convert dollars to cents +and attach the configured payment details. + The server listens at `http://127.0.0.1:3000`. Check both routes without paying: ```sh @@ -137,7 +143,11 @@ curl -i http://127.0.0.1:3001/api/widgets ``` `/free` returns HTTP 200. `/api/widgets` returns HTTP 402 with a `PAYMENT-REQUIRED` -header describing the available offers. +header describing the available offers. Add `?bundle=large` to request **0.05 USDC** +instead. The Seller selects the price from its own price list on each request. +The async route callback calls `seller.route(...)` with the selected price and +currency. `inflowpay.x402.fastapi.payment_middleware` resolves that callback and +delegates payment handling to the upstream middleware. Run the [Buyer](x402_buyer.py) in a second terminal: diff --git a/examples/mpp_seller.py b/examples/mpp_seller.py index 5ffa5a7..c476a08 100644 --- a/examples/mpp_seller.py +++ b/examples/mpp_seller.py @@ -4,14 +4,17 @@ from collections.abc import AsyncIterator from contextlib import asynccontextmanager +import httpx import uvicorn from fastapi import FastAPI, Request from mpp import Credential, Receipt from mpp.server import Mpp +from mpp.server import Request as PaymentRequest from mpp.server.decorator import pay from starlette.responses import JSONResponse from inflowpay import ClientOptions +from inflowpay.mpp import WireObject from inflowpay.mpp.seller import Seller @@ -21,17 +24,17 @@ async def application( ) -> AsyncIterator[FastAPI]: # Keep the Seller open for the whole server lifetime, not just startup. async with await Seller.create(options, method=method) as seller: - # Stripe and CARD prices are dollars here; their challenges contain integer cents. - if method == "card": - terms = seller.card_request({"amount": "1.25"}) - elif method == "stripe": - terms = seller.stripe_request({"amount": "1.25"}) - else: - terms = seller.charge_request({"amount": "0.01", "currency": "USDC"}) + + def price(request: PaymentRequest) -> WireObject: + large = httpx.URL(request.url).params.get("bundle") == "large" + if method in ("stripe", "card"): + return {"amount": "2.50" if large else "1.25"} + return {"amount": "0.05" if large else "0.01", "currency": "USDC"} + app = FastAPI() @app.get("/api/widgets") - @pay(Mpp(methods=[seller], realm="localhost", secret_key=secret).charge(**terms)) + @pay(Mpp(methods=[seller.priced(price)], realm="localhost", secret_key=secret).charge()) async def widgets( request: Request, credential: Credential, receipt: Receipt ) -> JSONResponse: @@ -62,7 +65,8 @@ async def run() -> None: async with application(options, secret, method=method) as app: price = "0.01 USDC" if method == "inflow" else f"1.25 USD via {method}" print( - f"MPP: http://127.0.0.1:3000/api/widgets costs {price}; /free requires no payment.", + f"MPP: http://127.0.0.1:3000/api/widgets starts at {price}; " + "?bundle=large selects the larger bundle; /free requires no payment.", flush=True, ) await uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=3000)).serve() diff --git a/examples/x402_seller.py b/examples/x402_seller.py index a649194..6efe85d 100644 --- a/examples/x402_seller.py +++ b/examples/x402_seller.py @@ -6,13 +6,13 @@ from typing import Literal import uvicorn -from fastapi import FastAPI +from fastapi import FastAPI, Request from x402 import x402ResourceServer -from x402.http.middleware.fastapi import payment_middleware from x402.http.types import RouteConfig from inflowpay import ClientOptions from inflowpay.x402.facilitator import Facilitator +from inflowpay.x402.fastapi import payment_middleware from inflowpay.x402.seller import Seller @@ -31,17 +31,26 @@ async def application( resource = x402ResourceServer(facilitator) for registration in await seller.scheme_registrations(): resource.register(registration["network"], registration["server"]) - offers = await seller.offers( - "$1.25" if instrument else "0.01 USDC", - schemes=["instrument"] if instrument else ["balance", "exact"], - payment_flow=payment_flow, - ) - if not offers: + schemes = ["instrument"] if instrument else ["balance", "exact"] + if not await seller.offers( + "$1.25" if instrument else "0.01 USDC", schemes=schemes, payment_flow=payment_flow + ): raise ValueError("The Seller configuration has no matching payment offers.") + + async def route(request: Request) -> RouteConfig: + large = request.query_params.get("bundle") == "large" + if instrument: + price = "$2.50" if large else "$1.25" + else: + price = "0.05 USDC" if large else "0.01 USDC" + return await seller.route( + price, + schemes=schemes, + payment_flow=payment_flow, + ) + app = FastAPI() - app.middleware("http")( - payment_middleware({"GET /api/widgets": RouteConfig(accepts=offers)}, resource) - ) + app.middleware("http")(payment_middleware({"GET /api/widgets": route}, resource)) @app.get("/api/widgets") async def widgets() -> dict[str, list[int]]: @@ -74,9 +83,10 @@ async def run() -> None: instrument=scheme == "instrument", payment_flow="upfront" if payment_flow == "upfront" else "authorization", ) as app: - price = "1.25 USD via instrument" if scheme == "instrument" else "0.01 USDC" + description = "1.25 USD via instrument" if scheme == "instrument" else "0.01 USDC" print( - f"x402: http://127.0.0.1:3001/api/widgets costs {price}; /free requires no payment.", + f"x402: http://127.0.0.1:3001/api/widgets starts at {description}; " + "?bundle=large selects the larger bundle; /free requires no payment.", flush=True, ) await uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=3001)).serve() diff --git a/src/inflowpay/mpp/seller.py b/src/inflowpay/mpp/seller.py index c26658a..312bd5c 100644 --- a/src/inflowpay/mpp/seller.py +++ b/src/inflowpay/mpp/seller.py @@ -1,6 +1,8 @@ from __future__ import annotations +import inspect import re +from collections.abc import Awaitable, Callable from copy import deepcopy from dataclasses import dataclass, field, replace from types import TracebackType @@ -9,8 +11,8 @@ from mpp import Credential, Receipt from mpp.errors import InvalidChallengeError, PaymentError -from mpp.server import ServerMethod, Validation -from mpp.server.method import ValidateContext, VerifyContext +from mpp.server import Request, ServerMethod, Validation +from mpp.server.method import RequestContext, ValidateContext, VerifyContext from pydantic import BaseModel from .._runtime import Client @@ -234,6 +236,35 @@ async def __aexit__( async def aclose(self) -> None: await self._client.aclose() + def priced( + self, + request: Callable[[Request], WireObject | Awaitable[WireObject]], + *, + needs_request_body: bool = False, + ) -> ServerMethod: + """Resolve charge input per request; Stripe and CARD amounts are decimal USD.""" + + async def resolve(context: RequestContext) -> dict[str, object]: + if context.input is None: + raise MppSellerConfigurationError("Request-time pricing requires an HTTP request") + value = request(context.input) + terms = await value if inspect.isawaitable(value) else value + if self.name == "stripe": + prepared = self.stripe_request(terms) + elif self.name == "card": + prepared = self.card_request(terms) + else: + prepared = self.charge_request(terms) + return dict(prepared) + + return ServerMethod( + method=self.method, + validate=self._validate, + broadcast=self._broadcast, + resolve_request=resolve, + needs_request_body=needs_request_body, + ) + def charge_request(self, request: WireObject) -> WireObject: if self.name in ("stripe", "card"): raise MppSellerConfigurationError(f"Use {self.name}_request with a decimal USD amount") diff --git a/src/inflowpay/x402/fastapi.py b/src/inflowpay/x402/fastapi.py new file mode 100644 index 0000000..9a15ca9 --- /dev/null +++ b/src/inflowpay/x402/fastapi.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import asyncio +import inspect +from collections.abc import Awaitable, Callable, Mapping +from copy import deepcopy +from dataclasses import replace + +from fastapi import Request, Response +from x402 import x402ResourceServer +from x402.http.middleware.fastapi import FastAPIAdapter +from x402.http.middleware.fastapi import payment_middleware as upstream_payment_middleware +from x402.http.types import ( + HTTPRequestContext, + PaymentOption, + PaywallConfig, + RouteConfig, + RouteConfigurationError, +) +from x402.http.x402_http_server import PaywallProvider, x402HTTPResourceServer +from x402.schemas.hooks import GrantAccessResult + +RouteResolver = Callable[[Request], RouteConfig | Awaitable[RouteConfig]] +Middleware = Callable[[Request, Callable[[Request], Awaitable[Response]]], Awaitable[Response]] + + +def _copy_option(option: PaymentOption) -> PaymentOption: + return replace( + option, + price=option.price if callable(option.price) else deepcopy(option.price), + extra=deepcopy(option.extra), + ) + + +def _observe_initialization(task: asyncio.Task[None]) -> None: + if not task.cancelled(): + task.exception() + + +def payment_middleware( + routes: Mapping[str, RouteConfig | RouteResolver], + server: x402ResourceServer, + paywall_config: PaywallConfig | None = None, + paywall_provider: PaywallProvider | None = None, +) -> Middleware: + """Resolve complete routes per request, then delegate to upstream payment middleware. + + Resolvers receive a Starlette request; explicit body reads use its replay cache. + Keep the server and its facilitator clients open for the application lifetime. + """ + configured = dict(routes) + declarations = {pattern: RouteConfig(accepts=[]) for pattern in configured} + patterns = {id(route): pattern for pattern, route in declarations.items()} + initialization: asyncio.Task[None] | None = None + + async def middleware( + request: Request, call_next: Callable[[Request], Awaitable[Response]] + ) -> Response: + nonlocal initialization + matched: str | None = None + + def select(_: HTTPRequestContext, route: RouteConfig) -> GrantAccessResult: + nonlocal matched + matched = patterns[id(route)] + return GrantAccessResult() + + # Let upstream select the route, including precedence and encoded paths. + router = x402HTTPResourceServer(server, declarations) + router.on_protected_request(select) + path = request.url.path + root = request.scope.get("root_path", "") + if root and (path == root or path.startswith(root + "/")): + path = path[len(root) :] + await router.process_http_request( + HTTPRequestContext( + adapter=FastAPIAdapter(request), + path=request.scope["raw_path"].decode("ascii").split("?")[0], + decoded_path=path, + method=request.method, + ) + ) + if matched is None: + return await call_next(request) + pattern = matched + route = configured[pattern] + if callable(route): + value = route(request) + route = await value if inspect.isawaitable(value) else value + if not route.accepts: + raise ValueError("Request pricing requires at least one payment offer") + route = replace( + route, + accepts=( + _copy_option(route.accepts) + if isinstance(route.accepts, PaymentOption) + else [_copy_option(option) for option in route.accepts] + ), + extensions=deepcopy(route.extensions), + tags=deepcopy(route.tags), + ) + if initialization is None or ( + initialization.done() and initialization.exception() is not None + ): + initialization = asyncio.create_task(asyncio.to_thread(server.initialize)) + initialization.add_done_callback(_observe_initialization) + # Keep initialization independent of a cancelled request, including late failures. + task = initialization + await asyncio.wait((task,)) + task.result() + protected = upstream_payment_middleware( + {pattern: route}, + server, + paywall_config, + paywall_provider, + sync_facilitator_on_start=False, + ) + # Upstream initialize() also refreshes facilitators; use its route-only validation here. + errors = x402HTTPResourceServer(server, {pattern: route})._validate_route_configuration() + if errors: + raise RouteConfigurationError(errors) + return await protected(request, call_next) + + return middleware diff --git a/tests/test_request_pricing.py b/tests/test_request_pricing.py new file mode 100644 index 0000000..9f5cfd9 --- /dev/null +++ b/tests/test_request_pricing.py @@ -0,0 +1,862 @@ +import asyncio +import threading +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import asynccontextmanager +from copy import deepcopy +from typing import Literal, TypedDict + +import httpx +import pytest +from fastapi import FastAPI, Request +from mpp import Challenge, Credential, Receipt +from mpp.server import Mpp +from mpp.server import Request as PaymentRequest +from mpp.server.decorator import pay +from mpp.server.method import RequestContext +from starlette.responses import JSONResponse +from x402 import x402ResourceServer +from x402.extensions.bazaar import declare_discovery_extension +from x402.http import HTTPFacilitatorClient +from x402.http.types import ( + HTTPRequestContext, + HTTPResponseBody, + ProcessSettleResult, + RouteConfig, + RouteConfigurationError, +) +from x402.http.utils import decode_payment_required_header, encode_payment_signature_header +from x402.schemas import AssetAmount, PaymentPayload, PaymentRequired +from x402.schemas.hooks import SettleContext, VerifyContext + +from inflowpay.mpp import WireObject +from inflowpay.mpp.seller import MppSellerConfigurationError +from inflowpay.mpp.seller import Seller as MppSeller +from inflowpay.x402.facilitator import Facilitator +from inflowpay.x402.fastapi import RouteResolver, _observe_initialization, payment_middleware +from inflowpay.x402.seller import Seller +from test_card_seller import platform as card_platform +from test_instrument_parity import card_config +from test_mpp_seller import ID, Platform, options +from test_stripe_seller import platform as stripe_platform +from test_x402_seller import CASES +from test_x402_upfront import FlowPlatform + + +class PriceSpec(TypedDict): + amount: str + currency: str + + +DynamicPrice = Callable[[Request], str | PriceSpec | Awaitable[str | PriceSpec]] + + +@asynccontextmanager +async def merchant( + platform: FlowPlatform, + price: DynamicPrice, + *, + flow: Literal["authorization", "upfront"] = "authorization", + schemes: list[str] | None = None, + status: int = 200, +) -> AsyncIterator[httpx.AsyncClient]: + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + + async def route(request: Request) -> RouteConfig: + value = price(request) + selected = await value if isinstance(value, Awaitable) else value + amount = selected["amount"] if isinstance(selected, dict) else selected + currency = selected["currency"] if isinstance(selected, dict) else None + return await seller.route(amount, currency=currency, schemes=schemes, payment_flow=flow) + + fixed = await seller.route("3 USDC", schemes=["balance"]) + app = FastAPI() + app.middleware("http")( + payment_middleware({"GET /paid": route, "GET /fixed": fixed}, resource) + ) + + @app.get("/paid") + async def paid() -> JSONResponse: + platform.events.append("handler") + return JSONResponse({"paid": True}, status_code=status) + + @app.get("/free") + async def free() -> dict[str, bool]: + return {"free": True} + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app, raise_app_exceptions=False), + base_url="https://seller.example", + ) as client: + yield client + + +@pytest.mark.parametrize("flow", ["authorization", "upfront"]) +@pytest.mark.parametrize("scheme", ["exact", "balance", "instrument"]) +@pytest.mark.parametrize("outcome", ["success", "rejected", "handler-error"]) +async def test_dynamic_x402_execution( + flow: Literal["authorization", "upfront"], scheme: str, outcome: str +) -> None: + platform = FlowPlatform("rejected" if outcome == "rejected" else "success") + if scheme == "instrument": + platform.config = card_config().model_dump(by_alias=True) + platform.supported = { + "kinds": [{"scheme": scheme, "network": "inflow:1", "x402Version": 2}] + } + calls: list[str] = [] + + def price(context: Request) -> PriceSpec: + calls.append(str(context.url)) + return {"amount": "1.25", "currency": "USD" if scheme == "instrument" else "USDC"} + + async with merchant( + platform, + price, + schemes=[scheme], + flow=flow, + status=500 if outcome == "handler-error" else 200, + ) as client: + assert not calls + assert (await client.get("/free")).status_code == 200 + assert not calls + response = await client.get("/paid") + assert response.status_code == 402 + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + assert len(required.accepts) == 1 + accepted = required.accepts[0] + assert accepted.amount == str( + 125 * 10 ** ({"exact": 6, "balance": 8, "instrument": 18}[scheme] - 2) + ) + assert len(calls) == 1 + payment = PaymentPayload(accepted=accepted, payload={"transactionId": ID}) + response = await client.get( + "/paid", headers={"payment-signature": encode_payment_signature_header(payment)} + ) + assert len(calls) == 2 + if flow == "upfront": + assert platform.events == ( + ["settle"] if outcome == "rejected" else ["settle", "handler"] + ) + else: + assert platform.events == ( + ["verify", "handler"] + if outcome == "handler-error" + else ["verify", "handler", "settle"] + ) + assert response.status_code == ( + 402 if outcome == "rejected" else 500 if outcome == "handler-error" else 200 + ) + + +async def test_currency_changes_are_request_local() -> None: + platform = FlowPlatform() + platform.config["assets"].append( + { + **platform.config["assets"][0], + "assetId": "0xabcdef", + "currency": "USDT", + "assetName": "USDT", + } + ) + entered = asyncio.Event() + calls = 0 + + async def price(context: Request) -> PriceSpec: + nonlocal calls + calls += 1 + if calls == 2: + entered.set() + await entered.wait() + currency = context.query_params.get("currency") or "USDC" + assert isinstance(currency, str) + return {"amount": "1" if currency == "USDC" else "2", "currency": currency} + + async with merchant(platform, price) as client: + responses = await asyncio.gather( + client.get("/paid?currency=USDC"), client.get("/paid?currency=USDT") + ) + for response, currency, amount in zip(responses, ("USDC", "USDT"), ("1", "2"), strict=True): + assert response.status_code == 402 + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + offers = required.accepts + assert len(offers) == 2 + assert {offer.extra["assetName"] for offer in offers} == {currency} + assert offers[0].amount == amount + "000000" + assert offers[1].amount == amount + "00000000" + assert calls == 2 + assert not platform.events + + +@pytest.mark.parametrize("flow", ["authorization", "upfront"]) +@pytest.mark.parametrize("change", ["amount", "currency"]) +async def test_x402_paid_retry_must_match_current_price( + flow: Literal["authorization", "upfront"], change: str +) -> None: + platform = FlowPlatform() + platform.config["assets"].append( + {**platform.config["assets"][0], "assetId": "0xabcdef", "currency": "USDT"} + ) + current: PriceSpec = {"amount": "1", "currency": "USDC"} + async with merchant(platform, lambda context: current, flow=flow) as client: + response = await client.get("/paid") + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + payment = PaymentPayload(accepted=required.accepts[0], payload={"transactionId": ID}) + headers = {"payment-signature": encode_payment_signature_header(payment)} + if change == "amount": + current["amount"] = "2" + else: + current["currency"] = "USDT" + assert (await client.get("/paid", headers=headers)).status_code == 402 + assert not platform.events + current.update({"amount": "1", "currency": "USDC"}) + assert (await client.get("/paid", headers=headers)).status_code == 200 + assert platform.events == ( + ["settle", "handler"] if flow == "upfront" else ["verify", "handler", "settle"] + ) + + +async def test_cancelled_price_resolution_does_not_charge_or_poison_next_request() -> None: + platform = FlowPlatform() + started = asyncio.Event() + release = asyncio.Event() + + async def price(context: Request) -> str: + started.set() + await release.wait() + return "$1" + + async with merchant(platform, price) as client: + pending = asyncio.create_task(client.get("/paid")) + await started.wait() + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert not platform.events + release.set() + assert (await client.get("/paid")).status_code == 402 + assert not platform.events + + +@pytest.mark.parametrize("method", ["inflow", "instrument", "tempo", "stripe", "card"]) +async def test_mpp_helpers_resolve_current_request(method: str) -> None: + platform = ( + stripe_platform() + if method == "stripe" + else card_platform() + if method == "card" + else Platform() + ) + if method == "tempo": + assert isinstance(platform.config, dict) + platform.config["supportedMethods"] = [{"id": "tempo"}] + calls = 0 + + def price(request: PaymentRequest) -> WireObject: + nonlocal calls + calls += 1 + large = httpx.URL(request.url).params.get("bundle") == "large" + if method == "tempo": + return { + "amount": "2000000" if large else "1000000", + "currency": "0x" + "1" * 40, + "recipient": "0x" + "2" * 40, + } + return { + "amount": "2" if large else "1", + "currency": "USD" if method == "instrument" else "USDC", + } + + async with await MppSeller.create( + options(platform), method="inflow" if method == "instrument" else method + ) as seller: + app = FastAPI() + + @app.get("/paid") + @pay( + Mpp( + methods=[seller.priced(price)], realm="seller.example", secret_key="test-only" + ).charge() + ) + async def paid(request: Request, credential: Credential, receipt: Receipt) -> JSONResponse: + return JSONResponse({"paid": True}) + + assert calls == 0 + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + for suffix, multiplier in (("", 1), ("?bundle=large", 2)): + response = await client.get("/paid" + suffix) + assert response.status_code == 402 + challenge = Challenge.from_www_authenticate(response.headers["www-authenticate"]) + scale = 100 if method in ("stripe", "card") else 1000000 if method == "tempo" else 1 + assert challenge.request["amount"] == str(multiplier * scale) + assert calls == 2 + assert len(platform.requests) == 1 + + +async def test_mpp_paid_retry_rejects_a_changed_price() -> None: + platform = Platform() + amount = "1" + calls = 0 + handled = 0 + + def price(request: PaymentRequest) -> WireObject: + nonlocal calls + calls += 1 + return {"amount": amount, "currency": "USDC"} + + async with await MppSeller.create(options(platform)) as seller: + app = FastAPI() + + @app.get("/paid") + @pay( + Mpp( + methods=[seller.priced(price)], realm="seller.example", secret_key="test-only" + ).charge() + ) + async def paid(request: Request, credential: Credential, receipt: Receipt) -> JSONResponse: + nonlocal handled + handled += 1 + return JSONResponse({"paid": True}) + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + challenge = Challenge.from_www_authenticate( + (await client.get("/paid")).headers["www-authenticate"] + ) + authorization = Credential( + challenge=challenge.to_echo(), payload={"transactionId": ID} + ).to_authorization() + amount = "2" + assert ( + await client.get("/paid", headers={"authorization": authorization}) + ).status_code == 402 + assert len(platform.requests) == 1 + amount = "1" + assert ( + await client.get("/paid", headers={"authorization": authorization}) + ).status_code == 200 + assert [request.url.path for request in platform.requests][-2:] == [ + "/v1/mpp/validate", + "/v1/mpp/broadcast", + ] + assert handled == 1 + assert calls == 3 + + +async def test_mpp_callback_failure_and_unsupported_currency_do_not_pay() -> None: + platform = Platform() + mode = "raises" + supplied: WireObject = {"amount": "1", "currency": "UNKNOWN", "methodDetails": {}} + before = deepcopy(supplied) + + def price(request: PaymentRequest) -> WireObject: + if mode == "raises": + raise RuntimeError("Price unavailable") + return supplied + + async with await MppSeller.create(options(platform)) as seller: + app = FastAPI() + + @app.get("/paid") + @pay( + Mpp( + methods=[seller.priced(price)], realm="seller.example", secret_key="test-only" + ).charge() + ) + async def paid(request: Request, credential: Credential, receipt: Receipt) -> JSONResponse: + pytest.fail("Invalid pricing must not reach the paid handler") + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app, raise_app_exceptions=False), + base_url="https://seller.example", + ) as client: + assert (await client.get("/paid")).status_code == 500 + mode = "unsupported" + assert (await client.get("/paid")).status_code == 500 + assert len(platform.requests) == 1 + assert supplied == before + + +@pytest.mark.parametrize("body_enabled", [False, True]) +async def test_mpp_async_body_and_concurrent_prices(body_enabled: bool) -> None: + platform = Platform() + entered = asyncio.Event() + calls = 0 + seen: list[bytes | None] = [] + + async def price(request: PaymentRequest) -> WireObject: + nonlocal calls + calls += 1 + seen.append(request.body) + if calls == 2: + entered.set() + await entered.wait() + return {"amount": httpx.URL(request.url).params["amount"], "currency": "USDC"} + + async with await MppSeller.create(options(platform)) as seller: + method = seller.priced(price, needs_request_body=body_enabled) + app = FastAPI() + + @app.post("/paid") + @pay(Mpp(methods=[method], realm="seller.example", secret_key="test-only").charge()) + async def paid(request: Request, credential: Credential, receipt: Receipt) -> JSONResponse: + return JSONResponse({"body": (await request.body()).decode()}) + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + responses = await asyncio.gather( + *[ + client.post("/paid?amount=" + amount, content=b"original") + for amount in ("1", "2") + ] + ) + assert [ + Challenge.from_www_authenticate(r.headers["www-authenticate"]).request["amount"] + for r in responses + ] == ["1", "2"] + assert seen == ([b"original"] * 2 if body_enabled else [None] * 2) + challenge = Challenge.from_www_authenticate(responses[0].headers["www-authenticate"]) + credential = Credential(challenge=challenge.to_echo(), payload={"transactionId": ID}) + paid_response = await client.post( + "/paid?amount=1", + content=b"original", + headers={"authorization": credential.to_authorization()}, + ) + assert paid_response.status_code == 200 + assert paid_response.json() == {"body": "original"} + assert calls == 3 + assert method.resolve_request is not None + with pytest.raises(MppSellerConfigurationError, match="HTTP request"): + value = method.resolve_request(RequestContext(request={})) + assert isinstance(value, Awaitable) + await value + + +@pytest.mark.parametrize("mode", ["raises", "unsupported", "empty", "unregistered"]) +async def test_x402_invalid_route_fails_closed(mode: str) -> None: + platform = FlowPlatform() + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + if mode != "unregistered": + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + + async def route(request: Request) -> RouteConfig: + if mode == "raises": + raise RuntimeError("private pricing error") + if mode == "empty": + return RouteConfig(accepts=[]) + return await seller.route( + "1 UNKNOWN" if mode == "unsupported" else "1 USDC", schemes=["exact"] + ) + + app = FastAPI() + app.middleware("http")(payment_middleware({"GET /paid": route}, resource)) + + @app.get("/paid") + async def paid() -> None: + pytest.fail("Unpriced requests must not reach the application") + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app, raise_app_exceptions=False), + base_url="https://seller.example", + ) as client: + response = await client.get("/paid") + assert response.status_code == 500 + assert response.text == "Internal Server Error" + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + with pytest.raises((ValueError, RuntimeError, RouteConfigurationError)): + await client.get("/paid") + assert not platform.events + + +@pytest.mark.parametrize("root", ["", "/mounted"]) +async def test_x402_body_replay_static_routes_and_matching(root: str) -> None: + platform = FlowPlatform() + calls = [] + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + fixed = await seller.route("1 USDC", schemes=["balance"]) + before = deepcopy(fixed) + + async def route(request: Request) -> RouteConfig: + calls.append(await request.body()) + return fixed + + app = FastAPI() + app.middleware("http")( + payment_middleware({"POST /paid/:id": route, "GET /fixed": fixed}, resource) + ) + + @app.post("/paid/{item_id}") + async def paid(request: Request, item_id: str) -> JSONResponse: + return JSONResponse({"body": (await request.body()).decode()}) + + parent = FastAPI() + if root: + parent.mount(root, app) + else: + parent = app + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(parent), base_url="https://seller.example" + ) as client: + response = await client.post(root + "/paid/123", content=b"original") + assert response.status_code == 402 + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + payload = PaymentPayload(accepted=required.accepts[0], payload={"transactionId": ID}) + response = await client.post( + root + "/paid/123", + content=b"original", + headers={"payment-signature": encode_payment_signature_header(payload)}, + ) + assert response.status_code == 200 + assert response.json() == {"body": "original"} + assert calls == [b"original", b"original"] + assert (await client.get(root + "/paid/123")).status_code == 405 + assert (await client.get(root + "/fixed")).status_code == 402 + assert (await client.head(root + "/fixed")).status_code == 402 + assert (await client.get(root + "/%66ixed")).status_code == 402 + assert fixed == before + + +async def test_sponsorship_follows_selected_currency_through_verification_and_settlement() -> None: + case = next(case for case in CASES if case["id"] == "x402.seller.sponsorship-prefers-eip2612") + platform = FlowPlatform() + platform.config = deepcopy(case["input"]["config"]) + platform.supported = deepcopy(case["input"]["supported"]) + asset = platform.config["assets"][0] + platform.config["assets"].extend( + [ + { + **asset, + "assetId": "0x4444444444444444444444444444444444444444", + "currency": "USDT", + "supportsEip2612": False, + "supportsEip7702": False, + }, + { + **asset, + "assetId": "0x5555555555555555555555555555555555555555", + "currency": "DAI", + "supportsEip2612": False, + "supportsEip7702": True, + }, + ] + ) + calls: list[str] = [] + + async def price(context: Request) -> str: + currency = context.query_params.get("currency") + assert isinstance(currency, str) + calls.append(currency) + await asyncio.sleep(0.001 if currency == "USDC" else 0) + return "1 " + currency + + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + original = {"custom": {"info": {"keep": True}}} + + async def route(request: Request) -> RouteConfig: + resolved = await seller.route(await price(request), schemes=["exact"], permit2=True) + resolved.extensions = {**(resolved.extensions or {}), **deepcopy(original)} + return resolved + + observed: list[tuple[str, object]] = [] + + def verifying(context: VerifyContext) -> None: + observed.append(("verify", deepcopy(dict(context.declared_extensions or {})))) + + def settling(context: SettleContext) -> None: + observed.append(("settle", deepcopy(dict(context.declared_extensions or {})))) + + resource.on_before_verify(verifying) + resource.on_before_settle(settling) + routes: dict[str, RouteConfig | RouteResolver] = {"GET /paid": route} + currencies = ["USDC", "USDT", "DAI", "USD"] + for currency in currencies: + fixed_route = await seller.route("1 " + currency, schemes=["exact"], permit2=True) + fixed_route.extensions = {**(fixed_route.extensions or {}), **original} + routes["GET /fixed/" + currency] = fixed_route + app = FastAPI() + app.middleware("http")(payment_middleware(routes, resource)) + + @app.get("/paid") + async def paid() -> dict[str, bool]: + return {"paid": True} + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + responses = await asyncio.gather( + *[client.get("/paid?currency=" + currency) for currency in currencies] + ) + for currency, response in zip(currencies, responses, strict=True): + assert response.status_code == 402 + required = decode_payment_required_header(response.headers["payment-required"]) + fixed_response = await client.get("/fixed/" + currency) + fixed = decode_payment_required_header(fixed_response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) and isinstance(fixed, PaymentRequired) + assert required.accepts == fixed.accepts + assert required.extensions == fixed.extensions + expected_key = { + "USDC": "eip2612GasSponsoring", + "DAI": "inflowEip7702GasSponsoring", + }.get(currency) + assert set(required.extensions or {}) == ( + {"custom", expected_key} if expected_key else {"custom"} + ) + payload = PaymentPayload( + accepted=required.accepts[0], payload={"transactionId": ID} + ) + paid_response = await client.get( + "/paid?currency=" + currency, + headers={"payment-signature": encode_payment_signature_header(payload)}, + ) + assert paid_response.status_code == 200 + assert observed[-2:] == [ + ("verify", required.extensions), + ("settle", required.extensions), + ] + assert original == {"custom": {"info": {"keep": True}}} + assert len(calls) == 8 + + +async def test_x402_sync_bazaar_route_keeps_parameters() -> None: + platform = FlowPlatform() + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + fixed = await seller.route("1 USDC") + fixed.extensions = declare_discovery_extension() + before = deepcopy(fixed) + calls = [] + + def route(request: Request) -> RouteConfig: + calls.append(request.url.path) + return fixed + + app = FastAPI() + app.middleware("http")(payment_middleware({"GET /items/:id": route}, resource)) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + response = await client.get("/items/123") + assert response.status_code == 402 + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + assert required.extensions is not None + bazaar = required.extensions["bazaar"] + assert bazaar["routeTemplate"] == "/items/:id" + assert bazaar["info"]["input"]["pathParams"] == {"id": "123"} + assert (await client.options("/items/123")).status_code == 404 + assert calls == ["/items/123"] + assert fixed == before + + +async def test_mpp_cancelled_resolution_does_not_pay() -> None: + platform = Platform() + entered, release = asyncio.Event(), asyncio.Event() + + async def price(request: PaymentRequest) -> WireObject: + entered.set() + await release.wait() + return {"amount": "1", "currency": "USDC"} + + async with await MppSeller.create(options(platform)) as seller: + handler = Mpp( + methods=[seller.priced(price)], realm="seller.example", secret_key="test-only" + ).charge() + request = PaymentRequest(method="GET", url="https://seller.example/paid") + pending = asyncio.create_task(handler(request)) + await entered.wait() + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert len(platform.requests) == 1 + release.set() + assert (await handler(request)).status == 402 + assert len(platform.requests) == 1 + + +async def test_x402_preserves_application_callbacks() -> None: + platform = FlowPlatform("rejected") + async with ( + await Seller.create(platform.options()) as seller, + await Facilitator.create(platform.options()) as facilitator, + ): + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + route = await seller.route("1 USDC", schemes=["balance"], payment_flow="upfront") + assert isinstance(route.accepts, list) + option = route.accepts[0] + assert isinstance(option.price, AssetAmount) and isinstance(option.pay_to, str) + amount, recipient = option.price, option.pay_to + + class Callbacks: + def __init__(self) -> None: + self.lock = threading.Lock() + self.prices = 0 + self.recipients = 0 + self.unpaid_calls = 0 + self.failed_calls = 0 + + def __call__(self, context: HTTPRequestContext) -> AssetAmount: + self.prices += 1 + return amount + + def pay_to(self, context: HTTPRequestContext) -> str: + self.recipients += 1 + return recipient + + def unpaid(self, context: HTTPRequestContext) -> HTTPResponseBody: + self.unpaid_calls += 1 + return HTTPResponseBody("application/json", {"call": self.unpaid_calls}) + + def failed( + self, context: HTTPRequestContext, result: ProcessSettleResult + ) -> HTTPResponseBody: + self.failed_calls += 1 + return HTTPResponseBody("application/json", {"failure": self.failed_calls}) + + callbacks = Callbacks() + option.price, option.pay_to = callbacks, callbacks.pay_to + route.accepts = option + route.unpaid_response_body = callbacks.unpaid + route.settlement_failed_response_body = callbacks.failed + app = FastAPI() + app.middleware("http")(payment_middleware({"GET /paid": route}, resource)) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + for count in (1, 2): + response = await client.get("/paid") + assert response.status_code == 402 and response.json() == {"call": count} + required = decode_payment_required_header(response.headers["payment-required"]) + assert isinstance(required, PaymentRequired) + payload = PaymentPayload(accepted=required.accepts[0], payload={"transactionId": ID}) + response = await client.get( + "/paid", headers={"payment-signature": encode_payment_signature_header(payload)} + ) + assert response.status_code == 402 and response.json() == {"failure": 1} + assert (callbacks.prices, callbacks.recipients) == (3, 3) + assert (callbacks.unpaid_calls, callbacks.failed_calls) == (2, 1) + assert route.accepts is option and option.price is callbacks + assert platform.events == ["settle"] + + +@pytest.mark.parametrize("outcome", ["success", "failure", "cancel"]) +async def test_x402_initializes_once_without_blocking( + outcome: str, monkeypatch: pytest.MonkeyPatch +) -> None: + platform = FlowPlatform() + entered, arrivals = asyncio.Event(), asyncio.Event() + release = threading.Event() + loop = asyncio.get_running_loop() + event_thread = threading.get_ident() + calls = 0 + + def supported(request: httpx.Request) -> httpx.Response: + nonlocal calls + assert threading.get_ident() != event_thread + assert request.url.path.endswith("/supported") + calls += 1 + loop.call_soon_threadsafe(entered.set) + assert release.wait(5) + if outcome == "failure" and calls == 1: + return httpx.Response(503, text="Temporarily unavailable") + return httpx.Response(200, json=platform.supported) + + async with await Seller.create(platform.options()) as seller: + facilitator = HTTPFacilitatorClient() + monkeypatch.setattr( + facilitator, + "_get_sync_client", + lambda: httpx.Client(transport=httpx.MockTransport(supported)), + ) + resource = x402ResourceServer(facilitator) + for registration in await seller.scheme_registrations(): + resource.register(registration["network"], registration["server"]) + fixed = await seller.route("1 USDC", schemes=["balance"]) + resolved = 0 + + def route(request: Request) -> RouteConfig: + nonlocal resolved + resolved += 1 + if resolved == 2: + arrivals.set() + return fixed + + app = FastAPI() + app.middleware("http")(payment_middleware({"GET /paid": route}, resource)) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="https://seller.example" + ) as client: + assert (await client.get("/free")).status_code == 404 and calls == 0 + first = asyncio.create_task(client.get("/paid")) + try: + await asyncio.wait_for(entered.wait(), 2) + second = asyncio.create_task(client.get("/paid")) + await asyncio.wait_for(arrivals.wait(), 2) + if outcome == "cancel": + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + finally: + release.set() + results = await asyncio.gather(first, second, return_exceptions=True) + if outcome == "failure": + assert all(isinstance(result, ValueError) for result in results) + elif outcome == "cancel": + assert isinstance(results[0], asyncio.CancelledError) + assert isinstance(results[1], httpx.Response) and results[1].status_code == 402 + else: + assert all( + isinstance(result, httpx.Response) and result.status_code == 402 + for result in results + ) + assert calls == 1 + for _ in range(2): + assert (await client.get("/paid")).status_code == 402 + assert calls == (2 if outcome == "failure" else 1) + await facilitator.aclose() + assert not platform.events + + +async def test_x402_initialization_observer_accepts_shutdown_cancellation() -> None: + task = asyncio.create_task(asyncio.sleep(0)) + task.cancel() + await asyncio.gather(task, return_exceptions=True) + _observe_initialization(task) diff --git a/tests/test_x402_upfront.py b/tests/test_x402_upfront.py index c7c2e17..0991e6a 100644 --- a/tests/test_x402_upfront.py +++ b/tests/test_x402_upfront.py @@ -12,12 +12,14 @@ from starlette.responses import JSONResponse from x402 import x402ResourceServer from x402.http.middleware.fastapi import payment_middleware +from x402.http.types import RouteConfig from x402.schemas import PaymentPayload, PaymentRequirements from inflowpay.mpp.seller import Seller as MppSeller from inflowpay.x402 import declare_payment_identifier from inflowpay.x402._seller import SellerConfig, build_offers from inflowpay.x402.facilitator import Facilitator +from inflowpay.x402.fastapi import payment_middleware as request_payment_middleware from inflowpay.x402.seller import Seller from test_mpp_seller import Platform as MppPlatform from test_mpp_seller import app_for, credential_for, options @@ -145,6 +147,7 @@ async def merchant( scheme: str = "balance", handler_status: int = 200, throws: bool = False, + request_pricing: bool = False, ) -> AsyncIterator[tuple[httpx.AsyncClient, PaymentPayload]]: # Only platform HTTP is simulated. Registration, matching, settlement ordering, # receipts and the application dispatch use the actual upstream middleware. @@ -157,7 +160,14 @@ async def merchant( resource.register(registration["network"], registration["server"]) route = await seller.route("$1", schemes=[scheme], payment_flow=flow) app = FastAPI() - app.middleware("http")(payment_middleware({"GET /paid": route}, resource)) + if request_pricing: + + async def resolve(request: Request) -> RouteConfig: + return await seller.route("$1", schemes=[scheme], payment_flow=flow) + + app.middleware("http")(request_payment_middleware({"GET /paid": resolve}, resource)) + else: + app.middleware("http")(payment_middleware({"GET /paid": route}, resource)) @app.get("/paid") async def paid(request: Request) -> JSONResponse: @@ -207,11 +217,19 @@ def payment_headers(payment: PaymentPayload) -> dict[str, str]: ("empty", 1, 200, False, False), ], ) +@pytest.mark.parametrize("request_pricing", [False, True]) async def test_upfront_lifecycle( - outcome: str, attempts: int, handler_status: int, throws: bool, runs: bool + outcome: str, + attempts: int, + handler_status: int, + throws: bool, + runs: bool, + request_pricing: bool, ) -> None: platform = FlowPlatform(outcome) - async with merchant(platform, handler_status=handler_status, throws=throws) as (http, payment): + async with merchant( + platform, handler_status=handler_status, throws=throws, request_pricing=request_pricing + ) as (http, payment): response = await http.get("/paid", headers=payment_headers(payment)) assert platform.events == ["settle"] * attempts + (["handler"] if runs else []) assert all(value == platform.settlements[0] for value in platform.settlements)