Introducing a new way to review your PRs.

Read the announcement

solana-foundation / pay

CLI for Agentic payments (x402, MPP, AP2).

View on GitHub

30 documents · Updated Nov 11, 2026

docs / http-payment-proxy

HTTP payment proxy

The HTTP payment proxy is the public data plane for payment-aware API traffic. It applies the shared payment decision rules at the HTTP edge, returns 402 Payment Required challenges when a request needs payment, and sends an accepted request to its real provider without exposing payment credentials to that provider. It keeps the public listener separate from the in-process control-plane gateway.

Proxy boundary

The proxy is the standalone pay-proxy crate at rust/…/lib.rs. It uses Pingora for the public HTTP listener and receives a PaymentState from the host. The shared pay-core gate remains the source of truth for payment decisions, so the proxy does not create a second payment policy.

The proxy has two traffic roles:

TrafficDestinationPurpose
Control-plane trafficInternal Axum serviceServes health, discovery, OpenAPI, debugger, and local response paths.
API trafficProvider upstreamServes free API routes or paid routes after the payment gate allows them.

The proxy is therefore a network boundary rather than a replacement for the runtime gateway. Read Rust payment runtime for the wider system and runtime payment gateway for the shared server-side payment contract.

Public data plane

The public listener accepts client requests and runs Http402Gate before it selects an upstream. A request that passes payment checks goes directly to the provider from the proxy. It does not make a second public hop through the internal Axum service.

This placement keeps the high-volume request path in the standalone proxy while the host can keep discovery and control routes in its existing HTTP service. The same host state supplies API definitions, payment backends, session state, and optional request telemetry to both paths.

References: rust/…/lib.rs• L1-10 rust/…/lib.rs• L35-49 rust/…/http402.rs• L1-11 rust/…/http402.rs• L160-184

Control-plane boundary

Control-plane paths are requests for gateway functions rather than provider resources. The proxy sends the root path, __402/*, /openapi.json, and /.well-known/* to the internal Axum service when the request is free or for discovery. A verified paid request always targets the provider, even when its path could otherwise look like a control-plane path.

This distinction prevents a client that has paid for a provider endpoint from losing that payment by being sent back to a service that does not own the provider route. It also keeps internal service paths out of the public provider path.

References: rust/…/http402.rs• L203-261 rust/…/http402.rs• L864-949 rust/…/http402.rs• L1320-1325 rust/…/start.rs• L2656-2723

HTTP 402 handling

HTTP 402 handling is the proxy's main payment boundary. For each request, the proxy gives the framework-neutral PaymentGate safe request metadata such as the method, host, path, accepted response type, authorization value, content length, query, and x402 payment header. The gate returns a challenge response, a forward decision, or a pass-through decision without reading the request body.

The request flow separates payment choice from provider delivery. This diagram shows how a first request becomes a challenge or a paid provider response.

flowchart TD
    A[Client request] --> B[HTTP payment proxy]
    B --> C[Shared payment gate]
    C -->|No usable payment| D[402 challenge]
    D --> E[Client creates payment credential]
    E --> B
    C -->|Free or discovery request| F[Control plane or provider]
    C -->|Verified payment| G[Prepare provider route]
    G --> H[Provider response]
    H --> I[Receipt or settlement headers]
    I --> J[Client response]

Payment challenge

The proxy returns the gate's 402 response as-is, including its payment challenge headers and body. The challenge states the payment options and terms that the client must use on its retry. A missing, unsupported, or invalid credential never reaches the provider.

The gate recognizes MPP and x402 payment headers while leaving ordinary provider authorization available for upstream authentication. This lets a client first receive an offer and then follow the normal challenge, approval, credential, and retry flow described in runtime client payment flows.

References: rust/…/gate.rs• L55-76 rust/…/gate.rs• L330-351 rust/…/payment.rs• L37-90 rust/…/http402.rs• L794-863 rust/…/http402.rs• L1471-1487

After verification, the proxy keeps the payment result with the request until the provider response or a terminal error. It can attach a payment receipt to a successful response. For channel-based or response-metered payments, it also settles or refunds the pending authorization based on whether the provider served the request.

This makes provider success part of the payment outcome for deferred payment forms. A provider failure does not silently become a successful paid delivery, and an already settled exact payment still returns its receipt when provider preparation fails.

References: rust/…/http402.rs• L264-345 rust/…/http402.rs• L1001-1081 rust/…/http402.rs• L1121-1181 rust/…/http402.rs• L1210-1287

Provider forwarding

Provider forwarding turns a declared API route into a request to the real service. The proxy reuses the shared route preparation rules so path rewrites, provider authentication, response handling, and the Axum adapter describe the same upstream contract.

Route and credential isolation

The API definition selects the provider URL and can select a route for a specific endpoint. The proxy forwards ordinary request headers and the request body, but removes hop-by-hop headers, the host header, and payment headers before the provider call. It then adds provider authentication from server configuration rather than from the caller's payment credential.

The supported provider-auth group includes direct header or query values, HMAC request signing, OAuth2, and access-token fetches. Missing provider secrets fail the request instead of sending an empty credential. Cached provider tokens are reused until they are close to expiry.

References: rust/…/proxy.rs• L35-48 rust/…/proxy.rs• L94-111 rust/…/proxy.rs• L223-375 rust/…/proxy.rs• L497-613 rust/…/http402.rs• L953-999

Streaming and buffering

The proxy keeps normal provider traffic on Pingora's streaming path. It uses a bounded buffered path only when the payment or provider contract needs the complete request or response before delivery.

The main buffered cases are:

  • A provider signature uses a digest of the request body.
  • Delegated session usage must be measured before response data is released.
  • x402 upto pricing needs response data to calculate the final charge.
  • A bounded batch response must be captured for safe replay.

Oversized buffered data fails with an error rather than growing without a limit. A failed buffered request or response releases pending session or channel state when the payment form allows it.

References: rust/…/http402.rs• L13-21 rust/…/http402.rs• L46-47 rust/…/http402.rs• L381-585 rust/…/http402.rs• L1373-1404 rust/…/proxy.rs• L76-93

Response usage and telemetry

The proxy can observe streamed provider output without changing the normal response flow. Its observer reads bounded SSE, NDJSON, or JSON shapes to identify model names, token counts, time to first byte, and rate estimates. The host receives live or final usage only when it opts into exchange tracking.

This observation supports response-based payment and operational views without making the payment debugger part of payment enforcement. Control-plane traffic is excluded from exchange tracking, while real provider requests and short-circuit payment responses remain visible to the host's telemetry hooks.

References: rust/…/observer.rs• L1-13 rust/…/observer.rs• L28-113 rust/…/http402.rs• L805-835 rust/…/http402.rs• L1084-1118 rust/…/http402.rs• L1121-1200

Configuration and lifecycle

The host configures the proxy with the public bind address, the internal control-plane address, the payment state, and an optional worker count. The paywall and payment provider settings are prepared by the server host; the proxy uses the resulting state while it handles traffic.

Gateway settings

The important settings describe network placement and trust boundaries rather than payment policy. Payment recipients, currencies, RPC settings, and provider auth values belong to the host's payment and API configuration. The proxy-specific choices are:

SettingRole
Public bind addressWhere clients connect to the payment-aware HTTP service.
Internal control-plane addressWhere free control and discovery requests are served.
Worker countHow much Pingora concurrency the public listener uses. The default follows available CPU parallelism.
TLS certificate and keyWhether the public listener terminates native TLS.
Shutdown signalWhether a caller can stop the proxy and regain process or terminal control.

The server command loads the paywall and constructs the internal Axum service before it starts the public proxy. This means an operator should treat the public listener and its private control-plane listener as one gateway deployment with two network roles.

References: rust/…/lib.rs• L35-49 rust/…/lib.rs• L73-119 rust/…/start.rs• L803-837 rust/…/start.rs• L2656-2744

TLS listener

The proxy can serve cleartext HTTP or terminate TLS with a certificate and private key. The certificate must cover the address that clients use. TLS advertises HTTP/2 while keeping HTTP/1.1 available, and the same Rustls path also supports HTTPS provider connections.

The proxy installs its Rustls crypto provider before it creates HTTP or telemetry clients. This startup step keeps the selected TLS backend stable when the wider dependency tree contains more than one Rustls crypto provider.

References: rust/…/lib.rs• L25-33 rust/…/lib.rs• L52-70 rust/…/lib.rs• L80-110 rust/…/Cargo.toml• L15-25

Process lifecycle

The normal run and run_tls entry points let Pingora own the public server lifecycle and block until process termination. A separate run_with_shutdown entry point supports hosts that need the proxy to return after a caller-owned signal, such as an inference TUI that must restore the terminal.

The proxy owns its Pingora runtime. Callers must start it outside an ambient Tokio runtime. On Unix, the caller-owned watcher also treats a dropped shutdown sender as a fast shutdown and keeps SIGTERM as a graceful-termination fallback.

References: rust/…/lib.rs• L35-49 rust/…/lib.rs• L122-168 rust/…/lib.rs• L170-195 rust/…/mod.rs• L488-553

Relationship to the runtime gateway

The standalone proxy and the in-process runtime gateway share the same payment gate and provider preparation rules, but they serve different hosting needs. The standalone proxy is the public edge and forwards provider traffic natively. The Axum middleware is an adapter for hosts that already own an in-process HTTP stack.

ConcernStandalone HTTP payment proxyIn-process runtime gateway
Public edgePingora listenerHost's Axum listener or middleware stack
Payment decisionShared PaymentGate through Http402GateShared PaymentGate through Axum middleware
Paid provider trafficNative proxy connection to the providerHost handler uses shared forwarding helpers
Control and discovery trafficInternal Axum service behind PingoraServed directly by the host's Axum service
LifecyclePingora-owned or caller-owned shutdownHost-owned runtime lifecycle

The separation keeps payment rules consistent while allowing the deployment to choose a public data-plane process model. See runtime payment gateway for request enforcement and runtime client payment flows for the client behavior after a 402 response.

Shared payment contract

The shared gate reads request metadata and returns a framework-neutral decision. The HTTP proxy maps that decision to Pingora actions. The Axum adapter maps the same decision to an Axum response or handler call. Changes to payment schemes, challenge fields, receipt headers, or settlement timing therefore affect both adapters.

References: rust/…/gate.rs• L1-14 rust/…/gate.rs• L55-76 rust/…/payment.rs• L21-40 rust/…/http402.rs• L773-950

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the control-plane path list aligned between Http402Gate, the internal Axum routes, and exchange tracking. A new discovery or debugger path can otherwise be sent to the provider or appear as paid API traffic.
  • Keep the GateDecision mapping aligned between the Pingora adapter and the Axum middleware. Challenge headers, receipt headers, pass-through behavior, and post-response settlement must mean the same thing in both paths.
  • Keep payment-header stripping aligned between shared request preparation and Pingora's native upstream request filter. A missed header can leak a payment credential to a provider.
  • Keep body-signing detection aligned with the buffered request path. A new body-dependent auth mode must not use an empty body on the streaming path.
  • Keep response buffering limits aligned with x402 upto, delegated sessions, and batch replay. A change can strand a channel or make a response impossible to replay safely.
  • Keep provider auth environment names and route rewrites aligned with the paywall schema. A valid payment can still fail at the provider boundary if the prepared request no longer matches the configured contract.
  • Keep TLS startup, certificate coverage, and provider HTTPS support aligned when changing the Rustls or Pingora feature set.
  • Keep caller-owned shutdown behavior aligned with hosts that run Pingora on a worker thread. A lifecycle change can leave the public listener alive after the host UI or terminal has exited.

Important failure modes

TriggerConsequenceGuard
A request has no usable payment credential for a metered endpointThe proxy returns 402 Payment Required and does not call the providerThe shared gate evaluates request metadata and builds the challenge before forwarding (rust/…/gate.rs• L330-351, rust/…/http402.rs• L845-863)
A paid request is sent to the internal control planeThe paid client can receive a control response instead of the provider resourceVerified forwards disable control-plane routing (rust/…/http402.rs• L921-934)
Payment or provider headers are copied to the upstreamThe provider can receive or log caller payment credentialsShared header stripping and the Pingora upstream filter remove payment and hop-by-hop headers (rust/…/proxy.rs• L35-48, rust/…/http402.rs• L980-997)
A provider auth secret is absent or emptyThe request fails with a gateway error instead of using blank authAuth preparation fails loudly before the provider call (rust/…/proxy.rs• L509-555)
A body-signing route uses the native streaming pathThe provider verifies a signature for the wrong bodyBody-dependent routes use bounded request buffering (rust/…/http402.rs• L234-240, rust/…/http402.rs• L404-435)
A buffered request or response exceeds its limitThe request returns a size or response-metering error and pending deferred payment is releasedRequest and response reads enforce fixed bounds and drain payment state on failure (rust/…/http402.rs• L404-417, rust/…/http402.rs• L527-582)
The provider fails before a response filter runsAn open deferred payment could remain charged or an exact payment could lose its receiptTerminal proxy failure handling refunds pending channels and preserves payment headers (rust/…/http402.rs• L1210-1287)
The public TLS certificate does not cover the client addressClients reject the gateway connectionTLS setup requires a certificate and key for the public listener, and operators must provide a matching name or IP (rust/…/lib.rs• L52-70, rust/…/lib.rs• L104-110)
Pingora runs inside an ambient Tokio runtimeThe server lifecycle can fail because Pingora owns its own runtimeStart run outside the caller's Tokio runtime (rust/…/lib.rs• L35-42, rust/…/start.rs• L2728-2744)

Key files

FileWhy to read it
rust/…/lib.rsShows the standalone proxy boundary, public listener modes, TLS setup, worker choice, and shutdown contracts.
rust/…/http402.rsShows how Pingora maps payment decisions to control-plane or provider traffic and how it completes settlement and error paths.
rust/…/observer.rsShows the bounded response observer used for inference usage and request telemetry.
rust/…/Cargo.tomlShows why the heavy Pingora and Rustls data-plane dependencies remain outside pay-core.
rust/…/gate.rsDefines the shared HTTP 402, payment verification, forwarding, receipt, and settlement decision contract.
rust/…/proxy.rsDefines route preparation, upstream auth, header isolation, and the framework-neutral forwarding plan.
rust/…/payment.rsShows the in-process Axum adapter and provides the comparison point for Pingora behavior.
rust/…/start.rsShows how the host creates the internal control plane and starts the public proxy.
rust/…/mod.rsShows caller-owned proxy shutdown for the inference TUI.