Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_stripe.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_stripe.py · 41.1 KB · 954 lines
1"""Stripe primitives: webhook signature verification and the API call.
2
3Stripe is **a payment method, never the system of record**
4(plan/billing-metering-spec.md section 6). We already own invoices,
5payments, dunning and the books; Stripe's only jobs are to collect a card
6and to tell us it happened. So this module is deliberately small and
7deliberately dumb: it verifies that an inbound webhook really came from
8Stripe, it turns a request into a form-encoded HTTPS call, and it hands
9back plain dicts. It writes no records, reads no collections, registers no
10object, and knows nothing about invoices. The webhook endpoint and the
11actions that call these primitives live elsewhere.
12
13stdlib only -- ``hmac``/``hashlib`` for the signature, ``urllib`` for the
14call. No ``stripe`` SDK, no ``requests``. A money path is exactly the wrong
15place to inherit a dependency's transitive attack surface, and Stripe's
16wire protocol is form-encoded HTTP with a bearer token: there is nothing
17here an SDK would do better.
18
19**Custody.** Both secrets are deploy-time, server-wide credentials and
20live in the operator's env file (docs/secrets-and-credentials.md #1):
21``DBBASIC_STRIPE_SECRET_KEY`` and ``DBBASIC_STRIPE_WEBHOOK_SECRET``. They
22are never a record field, never in a backup, and -- enforced here -- never
23in a repr, a log line, or an exception message. ``StripeConfig.__repr__``
24masks, and every message that could carry a Stripe response is passed
25through ``_redact()`` before it reaches an exception. The module makes no
26logging calls of its own at all; what an operator sees is what a caller
27chose to print, and none of it contains key material.
28
29**Dormant unless configured**, the same posture as ``smtp_config_from_env``:
30an unconfigured deployment builds a config object fine, reports
31``configured == False``, and refuses to call out or to verify anything.
32The refusal on the verify side matters more than it looks -- see the
33"empty secret" note on :func:`verify_webhook_signature`.
34
35Four decisions here diverge from the obvious reading of Stripe's docs, and
36each one is a bug in something someone shipped:
37
381. **The signature is computed over raw bytes, never a decoded string.**
39 The documented signed payload is ``"{t}.{body}"``, which invites
40 ``payload.decode()``. Decoding is at best a no-op and at worst a
41 ``UnicodeDecodeError`` on a hand-crafted body -- i.e. a webhook endpoint
42 that 500s on garbage, which is an invitation to probe. We concatenate
43 ``t`` + ``b"."`` + the raw bytes and never decode. A ``str`` payload is
44 refused outright rather than re-encoded, because a body that has been
45 through a JSON round trip is not the body Stripe signed.
462. **An empty webhook secret can never verify.** HMAC with an empty key is
47 a perfectly well-defined function that *anyone* can compute, so an
48 unconfigured deployment that "verifies" against ``""`` accepts forged
49 events from the whole internet. Missing secret is an explicit refusal.
503. **The default transport never follows redirects.** urllib's redirect
51 handler replays the original headers at the new location, which would
52 walk the ``Authorization: Bearer sk_live_...`` header off to whatever
53 host answered. Any 3xx is an error here, not a hop.
544. **Checkout metadata is mirrored onto the PaymentIntent.** Session
55 metadata does not propagate to the payment_intent/charge, so a handler
56 watching ``payment_intent.succeeded`` sees no ``invoice_id`` and the
57 payment cannot be tied back. ``payment_intent_data[metadata]`` carries
58 the same dict so the round trip survives whichever event you settle on.
59"""
60
61from __future__ import annotations
62
63import hashlib
64import hmac
65import json
66import os
67import socket
68import string
69import time
70import urllib.error
71import urllib.parse
72import urllib.request
73import uuid
74from collections.abc import Mapping
75from decimal import Decimal
76from typing import Any, Callable
77
78DEFAULT_API_BASE = "https://api.stripe.com"
79
80#: Stripe's own replay window, and the one their libraries default to.
81DEFAULT_TOLERANCE_SECONDS = 300
82DEFAULT_TIMEOUT_SECONDS = 10
83
84MAX_PAYLOAD_BYTES = 1_000_000
85MAX_RESPONSE_BYTES = 1_000_000
86
87# Bounds on attacker-supplied shapes. None of these are Stripe limits --
88# they are the point past which an input stops being a webhook and starts
89# being a resource-exhaustion attempt. A real Stripe-Signature header with
90# two rotating secrets is under 200 characters.
91MAX_SIGNATURE_HEADER_CHARS = 2048
92MAX_SIGNATURES = 16
93MAX_TIMESTAMP_CHARS = 20
94
95MAX_PARAM_DEPTH = 8
96MAX_URL_CHARS = 2048
97
98# Stripe's documented ceilings, checked locally so a bad amount fails at
99# the call site (with a message naming the field) instead of coming back
100# as an opaque API error after a round trip.
101MAX_AMOUNT_CENTS = 99_999_999
102MAX_DESCRIPTION_CHARS = 500
103MAX_METADATA_KEYS = 50
104MAX_METADATA_KEY_CHARS = 40
105MAX_METADATA_VALUE_CHARS = 500
106MAX_EVENT_ID_CHARS = 255
107
108ALLOWED_METHODS = frozenset({"GET", "POST", "DELETE"})
109
110EVENT_MARKER_PREFIX = "stripe_evt/"
111
112USER_AGENT = "dbbasic-object-server (stdlib urllib)"
113
114# The only hosts we will talk to over plaintext http: a mock Stripe on the
115# loopback interface during a test or a local dev run. Everything else must
116# be https, because the request carries a live secret key in a header.
117_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "[::1]"})
118
119_ASCII_DIGITS = frozenset("0123456789")
120_EVENT_ID_CHARS = frozenset(string.ascii_letters + string.digits + "_-")
121
122# Prefixes safe to show in a repr: they identify which *kind* of key is
123# loaded (and, crucially, whether a live key is sitting in a staging box)
124# without revealing a single character of the secret material after them.
125_KEY_PREFIXES = ("sk_live_", "sk_test_", "rk_live_", "rk_test_", "whsec_")
126
127
128class StripeError(Exception):
129 """A Stripe call that did not produce a usable result.
130
131 Carries Stripe's own error taxonomy when it has one (``type``,
132 ``code``, ``param``) plus the HTTP ``status``. ``message`` is safe to
133 put in front of an operator: it is either our own text or Stripe's,
134 and both are run through :func:`_redact` so no key material can ride
135 along in an error string.
136 """
137
138 def __init__(self, message: str, *, error_type: str = "", code: str = "",
139 status: int | None = None, param: str = "") -> None:
140 super().__init__(message)
141 self.message = message
142 self.type = error_type
143 self.code = code
144 self.status = status
145 self.param = param
146
147
148class StripePayloadError(StripeError):
149 """Bytes we were handed, or handed back, that cannot be used as-is:
150 oversized, not JSON, not an object, or a parameter we refuse to send."""
151
152
153# --- configuration ----------------------------------------------------------
154
155class StripeConfig:
156 """Deploy-time Stripe configuration, read from ``DBBASIC_STRIPE_*``.
157
158 A plain class with ``__slots__`` rather than a dataclass or a
159 namedtuple, and that is a security choice, not a style one. A
160 dataclass generates a ``__repr__`` that prints every field; a
161 namedtuple additionally *is* a tuple, so ``str(tuple(config))``,
162 passing the config to any stdout write and any ``%``-formatting of the whole object dump
163 both secrets in cleartext into whatever log caught them -- and no
164 override of ``__repr__`` closes those doors. Here the only rendering
165 of the object is the masked one below.
166 """
167
168 __slots__ = ("secret_key", "webhook_secret", "api_base", "api_version")
169
170 def __init__(self, *, secret_key: str = "", webhook_secret: str = "",
171 api_base: str = DEFAULT_API_BASE, api_version: str = "") -> None:
172 self.secret_key = secret_key or ""
173 self.webhook_secret = webhook_secret or ""
174 self.api_base = api_base or DEFAULT_API_BASE
175 self.api_version = api_version or ""
176
177 @property
178 def configured(self) -> bool:
179 """Both halves present: a key to call with and a secret to verify
180 with. Either one alone is a half-wired integration -- it would
181 take money without being able to hear that it did, or the
182 reverse -- so neither counts as configured."""
183 return bool(self.secret_key and self.webhook_secret)
184
185 def __repr__(self) -> str:
186 return (f"StripeConfig(api_base={self.api_base!r}, "
187 f"api_version={self.api_version!r}, "
188 f"secret_key={_mask(self.secret_key)}, "
189 f"webhook_secret={_mask(self.webhook_secret)}, "
190 f"configured={self.configured})")
191
192 __str__ = __repr__
193
194
195def _mask(value: str) -> str:
196 """"unset", "set", or the key's non-secret kind prefix.
197
198 ``sk_live_***`` tells an operator the thing they actually need to know
199 at a glance -- test key or live key -- and nothing else. The prefix is
200 only shown when there is material behind it to hide, so a truncated
201 secret that *is* just the prefix never gets echoed back whole.
202 """
203 text = str(value or "")
204 if not text:
205 return "unset"
206 for prefix in _KEY_PREFIXES:
207 if text.startswith(prefix) and len(text) > len(prefix) + 4:
208 return prefix + "***"
209 return "set"
210
211
212def stripe_config_from_env(env: Mapping[str, str] | None = None) -> StripeConfig:
213 """Read the operator's env into a config. Never raises, never logs.
214
215 ``api_base`` is overridable so a test or a local mock server is a
216 matter of configuration rather than of monkeypatching this module's
217 internals -- the internals are exactly what a test of a money path
218 should not be reaching into.
219
220 ``api_version`` is optional and unset by default (Stripe then uses the
221 account's pinned version). Setting ``DBBASIC_STRIPE_API_VERSION``
222 pins it per-request instead, which is the safer posture once the
223 integration is live: an account-level version bump changes response
224 shapes underneath running code.
225
226 Values are stripped, because a trailing newline in an env file is the
227 classic reason a correct secret produces an invalid-signature storm.
228 """
229 env = os.environ if env is None else env
230 return StripeConfig(
231 secret_key=(env.get("DBBASIC_STRIPE_SECRET_KEY") or "").strip(),
232 webhook_secret=(env.get("DBBASIC_STRIPE_WEBHOOK_SECRET") or "").strip(),
233 api_base=(env.get("DBBASIC_STRIPE_API_BASE") or "").strip() or DEFAULT_API_BASE,
234 api_version=(env.get("DBBASIC_STRIPE_API_VERSION") or "").strip(),
235 )
236
237
238def _redact(text: Any, config: Any) -> str:
239 """Blank any configured secret out of a string bound for an exception.
240
241 Belt and braces: nothing here deliberately puts a key in a message,
242 but the message may quote a response body or an OSError from a layer
243 that did. Short values are left alone -- redacting a two-character
244 "secret" would black out half the sentence for no benefit.
245 """
246 out = str(text)
247 for secret in (getattr(config, "secret_key", ""), getattr(config, "webhook_secret", "")):
248 material = str(secret or "")
249 if len(material) >= 8:
250 out = out.replace(material, "***")
251 return out
252
253
254# --- webhook signatures -----------------------------------------------------
255#
256# The whole security of the inbound path is this function. A webhook
257# endpoint is a public, unauthenticated URL that creates payment records;
258# if the signature check is wrong, anyone who guesses the URL can credit
259# themselves an invoice. Three properties are load-bearing:
260#
261# * comparison is `hmac.compare_digest` and nothing else. A byte-at-a-
262# time `==` on a hex digest leaks the correct prefix through timing,
263# which is a forgery oracle, not a theoretical concern.
264# * the timestamp window is enforced, so a *genuine* signed event
265# captured off the wire cannot be replayed a week later.
266# * nothing raises. A 500 on malformed input tells a prober that their
267# input reached code, and distinguishes shapes of garbage from each
268# other; every path here returns a dict.
269
270
271def _refused(reason: str) -> dict:
272 return {"ok": False, "reason": reason}
273
274
275def _parse_signature_header(header: Any) -> tuple[str, list[str], str]:
276 """``Stripe-Signature`` -> (t token, v1 candidates, refusal reason).
277
278 Stripe emits ``t=1700000000,v1=abc...`` with no spaces. We strip
279 whitespace around every element and around each key and value anyway:
280 a proxy that reformats a header into ``t=1, v1=abc`` is a plausible
281 thing to sit behind, and whitespace cannot change what gets verified
282 (the HMAC input is the *token*, and the token is constrained to ASCII
283 digits below). Leniency here costs nothing; leniency about the digest
284 itself would cost everything, so there is none of that.
285
286 Unknown schemes are ignored, which is how ``v0`` (Stripe's test-mode
287 scheme, not a signature over the real payload) and anything Stripe
288 adds later are handled -- ignored, never treated as a signature. A
289 header carrying *only* v0 therefore reads as "no v1", which is a
290 refusal.
291
292 Two ``t`` values is a refusal rather than a pick-the-first: an
293 ambiguous timestamp is exactly the shape of a request-smuggling
294 attempt, and there is no correct answer to choose.
295 """
296 if not isinstance(header, str):
297 return "", [], "signature header is missing"
298 raw = header.strip()
299 if not raw:
300 return "", [], "signature header is missing"
301 if len(raw) > MAX_SIGNATURE_HEADER_CHARS:
302 return "", [], f"signature header is longer than {MAX_SIGNATURE_HEADER_CHARS} characters"
303
304 timestamps: list[str] = []
305 signatures: list[str] = []
306 for element in raw.split(","):
307 item = element.strip()
308 if not item or "=" not in item:
309 continue
310 name, _, value = item.partition("=")
311 name = name.strip()
312 value = value.strip()
313 if not value:
314 continue
315 if name == "t":
316 timestamps.append(value)
317 elif name == "v1":
318 signatures.append(value)
319
320 if not timestamps:
321 return "", [], "signature header has no t= timestamp"
322 if len(timestamps) > 1:
323 return "", [], "signature header carries more than one t= timestamp"
324 if not signatures:
325 return "", [], "signature header has no v1= signature"
326 if len(signatures) > MAX_SIGNATURES:
327 return "", [], f"signature header carries more than {MAX_SIGNATURES} v1 signatures"
328 return timestamps[0], signatures, ""
329
330
331def _timestamp_value(token: str) -> int | None:
332 """The ``t`` token as an int, or None when it is not a plain integer.
333
334 ``str.isdigit()`` is deliberately not used: it is True for Arabic-Indic
335 and other Unicode digits, and ``int()`` happily parses them, so
336 ``t=١٧٠٠`` would sail through a naive check. Only ASCII digits, and
337 only a sane number of them -- a 5000-digit token is a CPU attack on
338 ``int()`` before it is anything else.
339 """
340 if not token or len(token) > MAX_TIMESTAMP_CHARS:
341 return None
342 if not set(token) <= _ASCII_DIGITS:
343 return None
344 return int(token)
345
346
347def verify_webhook_signature(payload_bytes: bytes, signature_header: str,
348 webhook_secret: str, *,
349 tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
350 now: int | None = None) -> dict:
351 """Verify a ``Stripe-Signature`` header against the raw request body.
352
353 Returns ``{"ok": True, "timestamp": <int>}`` or
354 ``{"ok": False, "reason": <text>}``. **Never raises** and never returns
355 a reason that echoes the expected digest or any part of the secret --
356 the reasons are written for an operator reading a log, and every one of
357 them describes only what the *caller* sent.
358
359 ``payload_bytes`` must be the bytes read off the socket. Not the body
360 a JSON round trip produced, not a decoded string: Stripe signed those
361 exact bytes, and ``json.dumps(json.loads(body))`` is a different
362 sequence of them. A ``str`` is refused rather than quietly encoded,
363 because refusing surfaces the mistake at the first test while encoding
364 hides it until a payload with an unusual escape shows up in production.
365
366 ``now`` is injectable so the replay window is testable at its exact
367 boundary; the window is symmetric (a timestamp that far in the future
368 is refused too, allowing for ordinary clock skew in between).
369 """
370 try:
371 if isinstance(payload_bytes, str):
372 return _refused("payload must be the raw request bytes, not a decoded string")
373 if not isinstance(payload_bytes, (bytes, bytearray, memoryview)):
374 return _refused(f"payload must be bytes, got {type(payload_bytes).__name__}")
375 body = bytes(payload_bytes)
376
377 # An empty key is not "no verification", it is verification that
378 # every attacker can also perform. Fail closed.
379 material = webhook_secret if isinstance(webhook_secret, str) else ""
380 if not material.strip():
381 return _refused("webhook secret is not configured")
382
383 token, offered_list, refusal = _parse_signature_header(signature_header)
384 if refusal:
385 return _refused(refusal)
386
387 stamp = _timestamp_value(token)
388 if stamp is None:
389 return _refused("t= timestamp is not a plain unsigned integer")
390
391 moment = int(time.time()) if now is None else int(now)
392 window = int(tolerance_seconds)
393 drift = moment - stamp
394 if abs(drift) > window:
395 direction = "old" if drift > 0 else "in the future"
396 return _refused(
397 f"timestamp is {abs(drift)}s {direction}, outside the {window}s tolerance")
398
399 # The signed payload uses the timestamp token *as it arrived*, not
400 # a reformatted int: Stripe hashed the characters it sent, so a
401 # round trip through int() would break on any representation we
402 # did not anticipate.
403 expected = hmac.new(
404 material.encode("utf-8"),
405 token.encode("ascii") + b"." + body,
406 hashlib.sha256,
407 ).hexdigest().encode("ascii")
408
409 for candidate in offered_list:
410 try:
411 offered = candidate.encode("ascii")
412 except UnicodeEncodeError:
413 # compare_digest refuses non-ASCII str; a non-ASCII digest
414 # is not a digest, so skip rather than blow up.
415 continue
416 if hmac.compare_digest(offered, expected):
417 return {"ok": True, "timestamp": stamp}
418
419 return _refused("no v1 signature matched")
420 except Exception as exc: # pragma: no cover - belt and braces
421 # Nothing above should reach here. If something does, a webhook
422 # endpoint still must not 500 and must not leak the exception text,
423 # which could quote the payload back at whoever sent it.
424 return _refused(f"signature could not be checked ({type(exc).__name__})")
425
426
427def parse_event(payload_bytes: bytes, *, max_bytes: int = MAX_PAYLOAD_BYTES) -> dict:
428 """The verified body as an event dict.
429
430 Call this *after* :func:`verify_webhook_signature`, never before:
431 parsing untrusted JSON is cheap but acting on it is not, and the size
432 cap here is the second line of defence, not the first (the endpoint
433 should refuse an oversized body before it is ever read into memory).
434
435 Raises :class:`StripePayloadError` for anything unusable -- over the
436 cap, not UTF-8, not JSON, or a JSON value that is not an object. A
437 top-level list or string is not an event no matter how well-formed it
438 is, and the caller's ``event["type"]`` would otherwise raise something
439 far less clear several frames later.
440 """
441 if isinstance(payload_bytes, str):
442 raise StripePayloadError(
443 "Event payload must be the raw request bytes, not a decoded string")
444 if not isinstance(payload_bytes, (bytes, bytearray, memoryview)):
445 raise StripePayloadError(
446 f"Event payload must be bytes, got {type(payload_bytes).__name__}")
447 body = bytes(payload_bytes)
448 cap = int(max_bytes)
449 if len(body) > cap:
450 raise StripePayloadError(
451 f"Event payload is {len(body)} bytes, over the {cap}-byte cap")
452 if not body.strip():
453 raise StripePayloadError("Event payload is empty")
454 try:
455 text = body.decode("utf-8")
456 except UnicodeDecodeError as exc:
457 raise StripePayloadError("Event payload is not valid UTF-8") from exc
458 try:
459 event = json.loads(text)
460 except ValueError as exc:
461 raise StripePayloadError(f"Event payload is not valid JSON: {exc}") from exc
462 if not isinstance(event, dict):
463 raise StripePayloadError(
464 f"Event payload is a JSON {type(event).__name__}, not an object")
465 return event
466
467
468def event_marker(event: Mapping[str, Any]) -> str:
469 """``stripe_evt/<id>`` -- the ``generated_from`` idempotency stamp.
470
471 This string is what makes webhook processing exactly-once without a
472 ProcessedStripeEvent table: the payment (and the journal behind it) is
473 stamped with it, and the composer already refuses to compose the same
474 provenance twice (object_finance.compose_posted_journal). Stripe
475 retries a webhook for days, so this is not an edge case -- it is the
476 normal path.
477
478 The id is validated hard, and the reason is this store: records are
479 tab-separated rows. An id containing a tab or a newline would not
480 merely look odd, it would split one record into two. Stripe ids are
481 ``[A-Za-z0-9_]``; anything else is either an attack or a bug, and both
482 should stop here rather than at the row writer.
483 """
484 if not isinstance(event, Mapping):
485 raise StripePayloadError(
486 f"Not a Stripe event object: {type(event).__name__}")
487 ident = event.get("id")
488 if not isinstance(ident, str) or not ident:
489 raise StripePayloadError("Stripe event has no string id to stamp provenance with")
490 if len(ident) > MAX_EVENT_ID_CHARS or not set(ident) <= _EVENT_ID_CHARS:
491 raise StripePayloadError(f"Refusing an unusable Stripe event id: {ident[:32]!r}")
492 return EVENT_MARKER_PREFIX + ident
493
494
495# --- parameters -------------------------------------------------------------
496#
497# Stripe's API takes form-encoded parameters and expresses structure with
498# brackets: nested objects become key[sub], arrays become key[0]. There is
499# no JSON request body option for most endpoints, so this encoding *is*
500# the API, and getting a bracket wrong means a silently-ignored parameter
501# rather than an error -- a checkout session that quietly loses its
502# metadata still succeeds, and the payment then cannot be tied to its
503# invoice. Hence a separate, directly testable function.
504
505
506def flatten_params(params: Any) -> list[tuple[str, str]]:
507 """Nested params -> Stripe's flat bracketed (name, value) pairs.
508
509 ``{"line_items": [{"price_data": {"currency": "usd"}}]}`` becomes
510 ``[("line_items[0][price_data][currency]", "usd")]``.
511
512 Rules, each of which has a reason:
513
514 * ``None`` is **omitted entirely**. Stripe treats a present-but-empty
515 parameter as "set this to empty", which is not the same request as
516 not mentioning it.
517 * ``bool`` before ``int``, because ``bool`` *is* an ``int`` in Python
518 and ``str(True)`` is ``"True"``, which Stripe reads as a non-empty
519 string -- i.e. truthy either way, so ``False`` would silently mean
520 ``True``. Emitted as ``"true"``/``"false"``.
521 * ``float`` is **refused**. Money never travels as a float in this
522 codebase (object_money's opening paragraph), and a float that
523 reached here is a bug worth failing on rather than rounding into a
524 charge. ``Decimal`` and ``str`` are accepted for the rare genuinely
525 fractional Stripe field.
526 * Names may not contain ``[``, ``]``, ``&``, ``=`` or control
527 characters: those are the structure of the encoding, and a metadata
528 key that contained one could otherwise forge a sibling parameter.
529 * Depth is capped, which also makes a self-referencing dict a clean
530 error instead of a RecursionError.
531 """
532 return _flatten(params, "", 0)
533
534
535def _flatten(value: Any, prefix: str, depth: int) -> list[tuple[str, str]]:
536 if depth > MAX_PARAM_DEPTH:
537 raise StripePayloadError(
538 f"Parameters nest deeper than {MAX_PARAM_DEPTH} levels")
539 if value is None:
540 return []
541 if isinstance(value, Mapping):
542 pairs: list[tuple[str, str]] = []
543 for key, item in value.items():
544 name = str(key)
545 if not name or any(ch in name for ch in "[]&=") or not name.isprintable():
546 raise StripePayloadError(f"Unusable parameter name: {key!r}")
547 child = f"{prefix}[{name}]" if prefix else name
548 pairs.extend(_flatten(item, child, depth + 1))
549 return pairs
550 if isinstance(value, (list, tuple)):
551 pairs = []
552 for index, item in enumerate(value):
553 pairs.extend(_flatten(item, f"{prefix}[{index}]", depth + 1))
554 return pairs
555 if not prefix:
556 raise StripePayloadError(
557 f"Top-level parameters must be a mapping, got {type(value).__name__}")
558 return [(prefix, _scalar(value))]
559
560
561def _scalar(value: Any) -> str:
562 if isinstance(value, bool):
563 return "true" if value else "false"
564 if isinstance(value, int):
565 return str(value)
566 if isinstance(value, float):
567 raise StripePayloadError(
568 "Refusing a float parameter: amounts are integer minor units and "
569 "fractional fields must be passed as a string or Decimal")
570 if isinstance(value, Decimal):
571 return str(value)
572 if isinstance(value, str):
573 return value
574 raise StripePayloadError(f"Unsupported parameter type: {type(value).__name__}")
575
576
577def encode_params(params: Any) -> str:
578 """Flattened params as an ``application/x-www-form-urlencoded`` body.
579
580 Brackets come out percent-encoded (``line_items%5B0%5D%5B...``), which
581 is what Stripe's own client library sends and what the standard calls
582 for; Stripe's docs show them literally only for readability. Encoding
583 them removes any question about who is allowed to introduce structure:
584 the answer is only :func:`flatten_params`, never a value.
585 """
586 return urllib.parse.urlencode(flatten_params(params))
587
588
589# --- the API call -----------------------------------------------------------
590
591
592def _api_url(api_base: str, path: str) -> str:
593 """Join base and path, refusing every way this could point elsewhere.
594
595 The request carries a live secret key in a header, so where it is
596 pointed is a security question, not a plumbing one:
597
598 * scheme must be http or https (no ``file:``, no ``gopher:``);
599 * plaintext http is allowed only to loopback, for a mock server -- a
600 secret key must never cross a network in the clear;
601 * the path may not be an absolute or protocol-relative URL, so a
602 caller-built path cannot redirect the call to another host;
603 * no whitespace or control characters, which is request-line and
604 header injection.
605 """
606 base = str(api_base or "").strip().rstrip("/")
607 if not base:
608 raise StripeError("Stripe API base is not configured")
609 parts = urllib.parse.urlsplit(base)
610 if parts.scheme not in ("http", "https"):
611 raise StripeError(
612 f"Refusing a non-HTTP Stripe API base: {parts.scheme or 'no scheme'}")
613 host = (parts.hostname or "").lower()
614 if not host:
615 raise StripeError("Stripe API base names no host")
616 if parts.scheme == "http" and host not in _LOCAL_HOSTS:
617 raise StripeError(
618 f"Refusing to send a Stripe secret key over plaintext http to {host}")
619
620 tail = str(path or "").strip()
621 if "://" in tail:
622 raise StripeError(f"Refusing an absolute URL as an API path: {path!r}")
623 if not tail.startswith("/"):
624 tail = "/" + tail
625 if tail.startswith("//"):
626 raise StripeError(f"Refusing a protocol-relative API path: {path!r}")
627 if "/.." in tail:
628 raise StripeError(f"Refusing a traversing API path: {path!r}")
629 if any(ch.isspace() or not ch.isprintable() for ch in tail):
630 raise StripeError("Refusing an API path containing whitespace or control characters")
631
632 url = base + tail
633 if len(url) > MAX_URL_CHARS:
634 raise StripeError(f"Stripe request URL is longer than {MAX_URL_CHARS} characters")
635 return url
636
637
638class _NoRedirect(urllib.request.HTTPRedirectHandler):
639 """Refuse to follow redirects.
640
641 urllib's default handler rebuilds the request at the new location and
642 carries the original headers with it -- including
643 ``Authorization: Bearer sk_live_...``. A redirect off api.stripe.com is
644 therefore a credential-exfiltration primitive, and Stripe's API has no
645 legitimate reason to emit one. Returning None makes urlopen raise
646 HTTPError for the 3xx instead, which :func:`api_request` turns into a
647 plain error.
648 """
649
650 def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102
651 return None
652
653
654def _default_transport(url: str, data: bytes | None, headers: Mapping[str, str],
655 method: str) -> tuple[int, bytes]:
656 """urllib, with a timeout, no redirects, and a bounded read.
657
658 An HTTP error status comes back as ``(status, body)`` rather than as an
659 exception, because Stripe's error body is the useful part -- the
660 ``code`` on a card decline is the thing a caller acts on. Only failures
661 with no HTTP answer at all (timeout, DNS, refused connection) raise.
662 """
663 request = urllib.request.Request(url, data=data, headers=dict(headers), method=method)
664 opener = urllib.request.build_opener(_NoRedirect)
665 try:
666 with opener.open(request, timeout=DEFAULT_TIMEOUT_SECONDS) as response:
667 return int(response.status or 0), response.read(MAX_RESPONSE_BYTES + 1)
668 except urllib.error.HTTPError as exc:
669 try:
670 body = exc.read(MAX_RESPONSE_BYTES + 1)
671 except OSError:
672 body = b""
673 finally:
674 exc.close()
675 return int(exc.code), body
676 except (socket.timeout, TimeoutError) as exc:
677 raise StripeError(
678 f"Stripe request timed out after {DEFAULT_TIMEOUT_SECONDS}s") from exc
679 except urllib.error.URLError as exc:
680 raise StripeError(f"Stripe request failed: {exc.reason}") from exc
681 except OSError as exc:
682 raise StripeError(f"Stripe request failed: {exc}") from exc
683
684
685def api_request(config: StripeConfig, method: str, path: str,
686 params: dict | None = None, *, idempotency_key: str | None = None,
687 transport: Callable[..., tuple[int, bytes]] | None = None) -> dict:
688 """One Stripe API call. Returns the parsed response object.
689
690 ``transport(url, data, headers, method) -> (status, body_bytes)`` is
691 injectable so that no test ever opens a socket, and so a caller can
692 wrap the call (a circuit breaker, a recorder) without this module
693 growing an opinion about either.
694
695 **Idempotency is on by default for POSTs.** Stripe deduplicates
696 retries by ``Idempotency-Key``; without one, a request that succeeded
697 at Stripe but timed out on our side charges the customer twice when
698 anyone retries it. A uuid4 is generated when the caller does not
699 supply one, so the default is safe. But note the limit, because it is
700 the sharp edge of this function: an auto-generated key protects only
701 against a retry *inside* Stripe's infrastructure, not against a caller
702 calling ``api_request`` twice. **A caller that retries must pass the
703 same ``idempotency_key`` both times** -- ideally one derived from the
704 thing being paid for (an invoice id), not from the attempt.
705
706 Raises :class:`StripeError` on a Stripe error object or any non-2xx,
707 and :class:`StripePayloadError` on a response that is not a JSON
708 object. Every message is redacted before it leaves.
709 """
710 verb = str(method or "").strip().upper()
711 if verb not in ALLOWED_METHODS:
712 raise StripeError(f"Unsupported HTTP method for the Stripe API: {method!r}")
713
714 key = str(getattr(config, "secret_key", "") or "").strip()
715 if not key:
716 # Checked before anything is built, so an unconfigured deployment
717 # fails at the call site instead of sending an anonymous request.
718 raise StripeError("Stripe secret key is not configured")
719
720 url = _api_url(getattr(config, "api_base", "") or DEFAULT_API_BASE, path)
721 encoded = encode_params(params or {})
722
723 body: bytes | None = None
724 if verb == "GET":
725 if encoded:
726 url = f"{url}?{encoded}"
727 else:
728 body = encoded.encode("ascii")
729
730 headers = {
731 "Authorization": f"Bearer {key}",
732 "Accept": "application/json",
733 "User-Agent": USER_AGENT,
734 }
735 if body is not None:
736 headers["Content-Type"] = "application/x-www-form-urlencoded"
737 version = str(getattr(config, "api_version", "") or "").strip()
738 if version:
739 headers["Stripe-Version"] = version
740
741 stamp = idempotency_key
742 if stamp is None and verb == "POST":
743 stamp = str(uuid.uuid4())
744 if stamp:
745 headers["Idempotency-Key"] = str(stamp)
746
747 send = _default_transport if transport is None else transport
748 try:
749 status, raw = send(url, body, headers, verb)
750 except StripeError:
751 raise
752 except Exception as exc:
753 raise StripeError(_redact(f"Stripe transport failed: {exc}", config)) from exc
754
755 return _parse_response(status, raw, config)
756
757
758def _parse_response(status: Any, raw: Any, config: Any) -> dict:
759 """Turn (status, bytes) into a dict or the right exception.
760
761 Anything at or above 300 is an error, not just 4xx/5xx: the default
762 transport refuses redirects on purpose, and a 3xx that arrived anyway
763 means the call did not reach Stripe's API, so returning its body as if
764 it were a resource would be the worst possible outcome. An ``error``
765 object in the body is honoured regardless of status, because a
766 response that describes an error is one whatever the header said.
767 """
768 try:
769 code = int(status)
770 except (TypeError, ValueError):
771 raise StripePayloadError(f"Transport returned a non-numeric status: {status!r}")
772 if not isinstance(raw, (bytes, bytearray)):
773 raise StripePayloadError(
774 f"Transport returned {type(raw).__name__}, not response bytes")
775 payload_bytes = bytes(raw)
776 if len(payload_bytes) > MAX_RESPONSE_BYTES:
777 raise StripePayloadError(
778 f"Stripe response is over the {MAX_RESPONSE_BYTES}-byte cap")
779
780 if not payload_bytes.strip():
781 if code >= 300:
782 raise StripeError(f"Stripe returned HTTP {code} with an empty body", status=code)
783 return {}
784
785 try:
786 payload = json.loads(payload_bytes.decode("utf-8"))
787 except (UnicodeDecodeError, ValueError) as exc:
788 snippet = payload_bytes[:200].decode("utf-8", "replace")
789 raise StripePayloadError(_redact(
790 f"Stripe returned HTTP {code} with a non-JSON body: {snippet!r}",
791 config)) from exc
792 if not isinstance(payload, dict):
793 raise StripePayloadError(
794 f"Stripe returned HTTP {code} with a JSON {type(payload).__name__}, "
795 "not an object")
796
797 error = payload.get("error")
798 if isinstance(error, dict) or code >= 300:
799 detail = error if isinstance(error, dict) else {}
800 message = str(detail.get("message") or "").strip() or f"Stripe returned HTTP {code}"
801 raise StripeError(
802 _redact(message, config),
803 error_type=str(detail.get("type") or ""),
804 code=str(detail.get("code") or ""),
805 status=code,
806 param=str(detail.get("param") or ""),
807 )
808 return payload
809
810
811# --- checkout ---------------------------------------------------------------
812
813
814def _checked_amount(amount_cents: Any) -> int:
815 """A positive whole number of minor units, and nothing else.
816
817 ``bool`` is excluded explicitly: ``True`` is an ``int`` worth 1, so
818 without this check ``amount_cents=True`` would charge one cent.
819 """
820 if isinstance(amount_cents, bool) or not isinstance(amount_cents, int):
821 raise StripePayloadError(
822 "amount_cents must be a whole number of minor units, got "
823 f"{type(amount_cents).__name__}")
824 if amount_cents <= 0:
825 raise StripePayloadError(f"amount_cents must be positive, got {amount_cents}")
826 if amount_cents > MAX_AMOUNT_CENTS:
827 raise StripePayloadError(
828 f"amount_cents {amount_cents} is over Stripe's {MAX_AMOUNT_CENTS} limit")
829 return amount_cents
830
831
832def _checked_currency(currency: Any) -> str:
833 """Stripe's lowercase three-letter code.
834
835 Case is normalised rather than refused -- "USD" is unambiguous and a
836 case mismatch has no security meaning -- but the shape is enforced,
837 and ASCII-only, so a full-width "usd" cannot slip past ``isalpha()``.
838 """
839 code = str(currency or "").strip().lower()
840 if len(code) != 3 or not code.isascii() or not code.isalpha():
841 raise StripePayloadError(
842 f"currency must be a three-letter code, got {currency!r}")
843 return code
844
845
846def _checked_return_url(field: str, url: Any) -> str:
847 """An http(s) URL a browser will be sent to after payment.
848
849 The scheme check is the point: these values end up as a redirect
850 target, and ``javascript:`` or ``data:`` there is a script-injection
851 hand-off dressed up as a config field. Control characters are refused
852 for the same reason they are in a path.
853 """
854 text = str(url or "").strip()
855 if not text:
856 raise StripePayloadError(f"{field} is required")
857 if len(text) > MAX_URL_CHARS:
858 raise StripePayloadError(f"{field} is longer than {MAX_URL_CHARS} characters")
859 if any(ch.isspace() or not ch.isprintable() for ch in text):
860 raise StripePayloadError(
861 f"{field} contains whitespace or control characters")
862 parts = urllib.parse.urlsplit(text)
863 if parts.scheme not in ("http", "https") or not parts.netloc:
864 raise StripePayloadError(
865 f"{field} must be an http(s) URL, got {text[:64]!r}")
866 return text
867
868
869def _checked_metadata(metadata: Any) -> dict:
870 """Stripe's metadata limits, enforced locally.
871
872 Metadata is how ``invoice_id`` and the portal token survive the round
873 trip, so a silently-dropped key here is a payment that cannot be
874 matched to what it paid for. Failing loudly before the call beats
875 discovering it in a webhook handler that has no invoice to credit.
876 """
877 if metadata is None:
878 return {}
879 if not isinstance(metadata, Mapping):
880 raise StripePayloadError(
881 f"metadata must be a mapping, got {type(metadata).__name__}")
882 if len(metadata) > MAX_METADATA_KEYS:
883 raise StripePayloadError(
884 f"metadata has {len(metadata)} keys, over Stripe's {MAX_METADATA_KEYS} limit")
885 out: dict[str, str] = {}
886 for key, value in metadata.items():
887 name = str(key).strip()
888 if not name or len(name) > MAX_METADATA_KEY_CHARS:
889 raise StripePayloadError(f"Unusable metadata key: {key!r}")
890 if value is None:
891 continue
892 text = _scalar(value)
893 if len(text) > MAX_METADATA_VALUE_CHARS:
894 raise StripePayloadError(
895 f"metadata[{name}] is {len(text)} characters, over Stripe's "
896 f"{MAX_METADATA_VALUE_CHARS} limit")
897 out[name] = text
898 return out
899
900
901def create_checkout_session(config: StripeConfig, *, amount_cents: int, currency: str,
902 description: str, success_url: str, cancel_url: str,
903 metadata: dict,
904 transport: Callable[..., tuple[int, bytes]] | None = None) -> dict:
905 """A one-off ``mode=payment`` Checkout Session for a single amount.
906
907 One inline ``price_data`` line item rather than a Stripe Price object:
908 the price book lives here (billing_plans), and creating a mirrored
909 Price in Stripe for every invoice is the first step towards Stripe
910 becoming a second, divergent system of record.
911
912 ``metadata`` is set on **both** the session and the PaymentIntent. This
913 is not belt-and-braces, it is required: session metadata does not
914 propagate down to the payment_intent or the charge, so a handler for
915 ``payment_intent.succeeded`` (or a payout reconciliation months later
916 reading the charge) would find nothing tying the money to an invoice.
917 Mirroring it means the identifier survives whichever object the
918 downstream code happens to be holding.
919
920 Every argument is validated before the transport is touched, so a bad
921 amount or currency costs nothing and cannot half-create anything.
922 """
923 amount = _checked_amount(amount_cents)
924 code = _checked_currency(currency)
925
926 name = str(description or "").strip()
927 if not name:
928 raise StripePayloadError("description is required (it is the line item's name)")
929 if len(name) > MAX_DESCRIPTION_CHARS:
930 raise StripePayloadError(
931 f"description is longer than {MAX_DESCRIPTION_CHARS} characters")
932
933 success = _checked_return_url("success_url", success_url)
934 cancel = _checked_return_url("cancel_url", cancel_url)
935 tags = _checked_metadata(metadata)
936
937 params: dict[str, Any] = {
938 "mode": "payment",
939 "success_url": success,
940 "cancel_url": cancel,
941 "line_items": [{
942 "quantity": 1,
943 "price_data": {
944 "currency": code,
945 "unit_amount": amount,
946 "product_data": {"name": name},
947 },
948 }],
949 }
950 if tags:
951 params["metadata"] = tags
952 params["payment_intent_data"] = {"metadata": tags}
953
954 return api_request(config, "POST", "/v1/checkout/sessions", params, transport=transport)