AgPerry's picture
Add files using upload-large-folder tool
584ed90 verified
Raw History Blame Contribute Delete
13.6 kB
"""Narrow Stripe Checkout client for the opt-in external test profile.
The default benchmark never imports credentials or contacts this client. In
the Cloudflare profile the client talks only to ``stripe.internal``; the edge
proxy validates the request shape and injects the Stripe test secret.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import os
import re
import time
from dataclasses import dataclass
from typing import Any, Mapping
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, urlopen
PAYMENT_MODE_LOCAL = "local-sandbox"
PAYMENT_MODE_STRIPE_TEST = "stripe-test"
PAYMENT_MODES = frozenset({PAYMENT_MODE_LOCAL, PAYMENT_MODE_STRIPE_TEST})
STRIPE_INTERNAL_API = "http://stripe.internal/v1"
STRIPE_WEBHOOK_PATH = "/api/stripe/webhook"
STRIPE_WEBHOOK_MAX_BYTES = 64 * 1024
STRIPE_WEBHOOK_TOLERANCE_SECONDS = 300
STRIPE_SESSION_TTL_SECONDS = 30 * 60
STRIPE_MAX_PRODUCT_LINES = 99
STRIPE_PROVIDER_SESSION_PATTERN = re.compile(
r"^cs_test_[A-Za-z0-9_]{8,240}$"
)
class StripeConfigurationError(ValueError):
"""The explicit Stripe profile is incomplete or unsafe."""
class StripeAPIError(RuntimeError):
"""A provider request failed without exposing provider response details."""
class StripeResponseError(StripeAPIError):
"""The provider returned a malformed or inconsistent response."""
class StripeSignatureError(ValueError):
"""A webhook did not carry a current valid Stripe signature."""
@dataclass(frozen=True, slots=True)
class PaymentConfig:
mode: str
api_base: str | None = None
webhook_secret: str | None = None
trust_edge_webhook: bool = False
@property
def stripe_enabled(self) -> bool:
return self.mode == PAYMENT_MODE_STRIPE_TEST
def _env_flag(environment: Mapping[str, str], name: str) -> bool:
return str(environment.get(name, "")).strip().casefold() in {
"1",
"true",
"yes",
"on",
}
def load_payment_config(
environment: Mapping[str, str] | None = None,
) -> PaymentConfig:
source = os.environ if environment is None else environment
mode = str(source.get("AMAZON_PAYMENT_MODE", PAYMENT_MODE_LOCAL)).strip()
if mode not in PAYMENT_MODES:
raise StripeConfigurationError(
"AMAZON_PAYMENT_MODE must be local-sandbox or stripe-test"
)
if mode == PAYMENT_MODE_LOCAL:
return PaymentConfig(mode=mode)
api_base = str(
source.get("AMAZON_STRIPE_API_URL", STRIPE_INTERNAL_API)
).strip().rstrip("/")
parsed = urlsplit(api_base)
if (
parsed.scheme != "http"
or parsed.hostname != "stripe.internal"
or parsed.path != "/v1"
or parsed.username
or parsed.password
or parsed.port is not None
or parsed.query
or parsed.fragment
):
raise StripeConfigurationError(
"stripe-test requires the Worker-owned http://stripe.internal/v1 proxy"
)
trust_edge = _env_flag(source, "AMAZON_STRIPE_WEBHOOK_TRUST_EDGE")
webhook_secret = str(
source.get("STRIPE_TEST_WEBHOOK_SECRET", "")
).strip()
if not trust_edge and not re.fullmatch(r"whsec_[A-Za-z0-9_]{16,240}", webhook_secret):
raise StripeConfigurationError(
"stripe-test requires STRIPE_TEST_WEBHOOK_SECRET unless edge verification is enabled"
)
return PaymentConfig(
mode=mode,
api_base=api_base,
webhook_secret=webhook_secret or None,
trust_edge_webhook=trust_edge,
)
def verify_stripe_signature(
raw_body: bytes,
signature_header: str,
webhook_secret: str,
*,
now: int | None = None,
tolerance_seconds: int = STRIPE_WEBHOOK_TOLERANCE_SECONDS,
) -> int:
if not raw_body or len(raw_body) > STRIPE_WEBHOOK_MAX_BYTES:
raise StripeSignatureError("invalid webhook body")
if not isinstance(signature_header, str) or len(signature_header) > 4096:
raise StripeSignatureError("invalid webhook signature")
if not re.fullmatch(r"whsec_[A-Za-z0-9_]{16,240}", webhook_secret):
raise StripeSignatureError("invalid webhook configuration")
timestamps: list[int] = []
signatures: list[str] = []
for component in signature_header.split(","):
name, separator, value = component.strip().partition("=")
if not separator:
continue
if name == "t" and value.isascii() and value.isdecimal():
timestamps.append(int(value))
elif name == "v1" and re.fullmatch(r"[0-9a-fA-F]{64}", value):
signatures.append(value.casefold())
if len(timestamps) != 1 or not signatures:
raise StripeSignatureError("invalid webhook signature")
timestamp = timestamps[0]
current = int(time.time()) if now is None else int(now)
if abs(current - timestamp) > tolerance_seconds:
raise StripeSignatureError("stale webhook signature")
signed = str(timestamp).encode("ascii") + b"." + raw_body
expected = hmac.new(
webhook_secret.encode("utf-8"), signed, hashlib.sha256
).hexdigest()
if not any(hmac.compare_digest(expected, candidate) for candidate in signatures):
raise StripeSignatureError("invalid webhook signature")
return timestamp
def _safe_product_name(value: Any) -> str:
normalized = " ".join(str(value or "Amazon Clone item").split())
if not normalized:
normalized = "Amazon Clone item"
return normalized[:240]
def checkout_session_form(
preparation: Mapping[str, Any],
*,
success_url: str,
cancel_url: str,
) -> list[tuple[str, str]]:
items = preparation.get("items")
if not isinstance(items, list) or not items:
raise StripeResponseError("checkout snapshot has no items")
if len(items) > STRIPE_MAX_PRODUCT_LINES:
raise StripeResponseError(
"Stripe Checkout supports at most 99 product lines plus shipping"
)
currency = str(preparation.get("currency") or "").lower()
if re.fullmatch(r"[a-z]{3}", currency) is None:
raise StripeResponseError("checkout currency is invalid")
token = str(preparation.get("checkout_token") or "")
flow_id = str(preparation.get("flow_id") or "")
owner = str(preparation.get("owner") or "")
fingerprint = str(preparation.get("cart_fingerprint") or "")
amount_minor = int(preparation.get("amount_minor") or -1)
email = str(preparation.get("customer_email") or "")
expires_at = int(preparation.get("expires_at") or 0)
if (
not re.fullmatch(r"[A-Za-z0-9_-]{24,160}", token)
or not re.fullmatch(r"payflow_[A-Za-z0-9_-]{12,120}", flow_id)
or not re.fullmatch(r"[A-Za-z0-9._:-]{8,240}", owner)
or not re.fullmatch(r"[0-9a-f]{64}", fingerprint)
or amount_minor < 0
or not re.fullmatch(r"[^@\s]+@[^@\s]+", email)
or expires_at <= 0
):
raise StripeResponseError("checkout metadata is invalid")
for return_url in (success_url, cancel_url):
parsed = urlsplit(return_url)
if (
parsed.scheme not in {"http", "https"}
or not parsed.netloc
or parsed.username
or parsed.password
or parsed.fragment
):
raise StripeResponseError("checkout return URL is invalid")
fields: list[tuple[str, str]] = [
("mode", "payment"),
("payment_method_types[0]", "card"),
("payment_method_types[1]", "link"),
("customer_email", email),
("success_url", success_url),
("cancel_url", cancel_url),
("client_reference_id", flow_id),
("expires_at", str(expires_at)),
("metadata[site_id]", "amazon"),
("metadata[flow_id]", flow_id),
("metadata[owner]", owner),
("metadata[amount_minor]", str(amount_minor)),
("metadata[currency]", currency.upper()),
("metadata[fingerprint]", fingerprint),
("metadata[is_simulation]", "true"),
]
for index, item in enumerate(items):
quantity = int(item.get("quantity") or 0)
unit_amount = int(item.get("price_minor") or -1)
if not 1 <= quantity <= 30 or unit_amount < 0:
raise StripeResponseError("checkout item quote is invalid")
prefix = f"line_items[{index}]"
fields.extend(
(
(f"{prefix}[price_data][currency]", currency),
(f"{prefix}[price_data][unit_amount]", str(unit_amount)),
(
f"{prefix}[price_data][product_data][name]",
_safe_product_name(item.get("title")),
),
(f"{prefix}[quantity]", str(quantity)),
)
)
shipping_minor = int(preparation.get("shipping_minor") or 0)
if shipping_minor:
prefix = f"line_items[{len(items)}]"
fields.extend(
(
(f"{prefix}[price_data][currency]", currency),
(f"{prefix}[price_data][unit_amount]", str(shipping_minor)),
(
f"{prefix}[price_data][product_data][name]",
"Shipping and handling",
),
(f"{prefix}[quantity]", "1"),
)
)
return fields
class StripeGateway:
"""Minimal Checkout Session create/read/expire client."""
def __init__(self, api_base: str = STRIPE_INTERNAL_API, timeout: float = 10.0):
self.api_base = api_base.rstrip("/")
self.timeout = timeout
def _request(
self,
method: str,
path: str,
fields: list[tuple[str, str]] | None = None,
*,
idempotency_key: str | None = None,
) -> dict[str, Any]:
body = urlencode(fields or []).encode("utf-8") if fields is not None else None
headers = {
"Accept": "application/json",
"User-Agent": "WebsiteBench-Amazon-Stripe-Test/1.0",
}
effects_token = os.environ.get(
"WEBSITEBENCH_EFFECTS_INTERNAL_TOKEN",
os.environ.get("CLAWBENCH_EFFECTS_INTERNAL_TOKEN", ""),
).strip()
if effects_token:
headers["X-WebsiteBench-Effects-Token"] = effects_token
if body is not None:
headers["Content-Type"] = "application/x-www-form-urlencoded"
if idempotency_key is not None:
headers["Idempotency-Key"] = idempotency_key
request = Request(
f"{self.api_base}{path}",
data=body,
headers=headers,
method=method,
)
try:
with urlopen(request, timeout=self.timeout) as response:
raw = response.read(256 * 1024 + 1)
except (HTTPError, URLError, TimeoutError, OSError) as exc:
raise StripeAPIError("Stripe test service is temporarily unavailable") from exc
if len(raw) > 256 * 1024:
raise StripeResponseError("Stripe response was too large")
try:
payload = json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise StripeResponseError("Stripe returned an invalid response") from exc
if not isinstance(payload, dict):
raise StripeResponseError("Stripe returned an invalid response")
return payload
def create_checkout_session(
self,
preparation: Mapping[str, Any],
*,
success_url: str,
cancel_url: str,
) -> dict[str, Any]:
payload = self._request(
"POST",
"/checkout/sessions",
checkout_session_form(
preparation,
success_url=success_url,
cancel_url=cancel_url,
),
idempotency_key=str(preparation["provider_idempotency_key"]),
)
session_id = str(payload.get("id") or "")
checkout_url = str(payload.get("url") or "")
parsed = urlsplit(checkout_url)
if (
STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id) is None
or parsed.scheme != "https"
or parsed.hostname != "checkout.stripe.com"
or parsed.username
or parsed.password
or parsed.port is not None
or parsed.fragment
):
raise StripeResponseError("Stripe returned an invalid Checkout Session")
return payload
def retrieve_checkout_session(self, session_id: str) -> dict[str, Any]:
if STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id) is None:
raise StripeResponseError("Stripe Checkout Session ID is invalid")
return self._request("GET", f"/checkout/sessions/{session_id}")
def expire_checkout_session(self, session_id: str) -> dict[str, Any]:
if STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id) is None:
raise StripeResponseError("Stripe Checkout Session ID is invalid")
return self._request(
"POST", f"/checkout/sessions/{session_id}/expire", []
)
__all__ = [
"PAYMENT_MODE_LOCAL",
"PAYMENT_MODE_STRIPE_TEST",
"PaymentConfig",
"STRIPE_MAX_PRODUCT_LINES",
"STRIPE_PROVIDER_SESSION_PATTERN",
"STRIPE_SESSION_TTL_SECONDS",
"STRIPE_WEBHOOK_MAX_BYTES",
"STRIPE_WEBHOOK_PATH",
"StripeAPIError",
"StripeConfigurationError",
"StripeGateway",
"StripeResponseError",
"StripeSignatureError",
"checkout_session_form",
"load_payment_config",
"verify_stripe_signature",
]