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/tests/test_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
test_object_stripe.py · 50.5 KB · 1258 lines
1"""Adversarial tests for the Stripe primitives.
2
3The posture: this is the money path, so every test here is written as an
4attempt to break object_stripe rather than to demonstrate it. The webhook
5verifier gets tampered payloads, wrong secrets, replayed and future
6timestamps, rotation headers, and a pile of malformed input that a prober
7would send; the API layer gets a transport that never touches a socket and
8is inspected for exactly what went on the wire.
9
10No test in this file makes a network call. ``api_request`` takes an
11injected ``transport``, and the one test that exercises the default
12transport's URL rules stops before any connection is opened.
13"""
14
15import ast
16import hashlib
17import hmac
18import inspect
19import json
20import urllib.parse
21from decimal import Decimal
22
23import pytest
24
25import object_stripe
26
27
28SECRET = "whsec_test_0123456789abcdef"
29NOW = 1_700_000_000
30
31
32def sign_header(payload: bytes, secret: str = SECRET, timestamp: int = NOW,
33 scheme: str = "v1") -> str:
34 """Build a Stripe-Signature header the way Stripe documents it."""
35 digest = hmac.new(secret.encode("utf-8"),
36 str(timestamp).encode("ascii") + b"." + payload,
37 hashlib.sha256).hexdigest()
38 return f"t={timestamp},{scheme}={digest}"
39
40
41PAYLOAD = b'{"id":"evt_1Abc","type":"checkout.session.completed","data":{}}'
42
43
44# --- signature: the fixed vector --------------------------------------------
45
46def test_fixed_vector_pins_the_signed_string_format():
47 """A hardcoded digest computed outside this module.
48
49 The other signature tests build their header with the same HMAC recipe
50 the implementation uses, so they would all still pass if the signed
51 string quietly became, say, "{t}:{body}". This one would not: the
52 digest below was computed once, by hand, over "1700000000." + body.
53 """
54 payload = b'{"id":"evt_fixed","type":"checkout.session.completed"}'
55 header = ("t=1700000000,"
56 "v1=b0ffffece04823710d9c27175b5093fa7c7416f9f6de5572499420eeaba0c6a8")
57 result = object_stripe.verify_webhook_signature(
58 payload, header, "whsec_fixed_vector_secret", now=1700000000)
59 assert result == {"ok": True, "timestamp": 1700000000}
60
61
62# --- signature: the happy path and the near misses --------------------------
63
64def test_valid_signature_accepted():
65 result = object_stripe.verify_webhook_signature(
66 PAYLOAD, sign_header(PAYLOAD), SECRET, now=NOW)
67 assert result["ok"] is True
68 assert result["timestamp"] == NOW
69
70
71def test_one_flipped_byte_in_the_payload_is_rejected():
72 header = sign_header(PAYLOAD)
73 tampered = bytearray(PAYLOAD)
74 tampered[10] ^= 0x01
75 result = object_stripe.verify_webhook_signature(bytes(tampered), header, SECRET, now=NOW)
76 assert result["ok"] is False
77 assert "no v1 signature matched" in result["reason"]
78
79
80def test_appended_byte_is_rejected():
81 result = object_stripe.verify_webhook_signature(
82 PAYLOAD + b" ", sign_header(PAYLOAD), SECRET, now=NOW)
83 assert result["ok"] is False
84
85
86def test_wrong_secret_is_rejected():
87 result = object_stripe.verify_webhook_signature(
88 PAYLOAD, sign_header(PAYLOAD), "whsec_a_different_secret_entirely", now=NOW)
89 assert result["ok"] is False
90 assert "no v1 signature matched" in result["reason"]
91
92
93def test_secret_off_by_one_character_is_rejected():
94 result = object_stripe.verify_webhook_signature(
95 PAYLOAD, sign_header(PAYLOAD), SECRET + "0", now=NOW)
96 assert result["ok"] is False
97
98
99def test_signature_for_a_different_timestamp_is_rejected():
100 """The timestamp is inside the MAC, so swapping it invalidates."""
101 header = sign_header(PAYLOAD, timestamp=NOW)
102 digest = header.split("v1=", 1)[1]
103 forged = f"t={NOW + 1},v1={digest}"
104 result = object_stripe.verify_webhook_signature(PAYLOAD, forged, SECRET, now=NOW)
105 assert result["ok"] is False
106 assert "no v1 signature matched" in result["reason"]
107
108
109# --- signature: the replay window -------------------------------------------
110
111def test_stale_timestamp_rejected():
112 header = sign_header(PAYLOAD, timestamp=NOW - 3600)
113 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
114 assert result["ok"] is False
115 assert "3600s old" in result["reason"]
116 assert "outside the 300s tolerance" in result["reason"]
117
118
119def test_future_timestamp_beyond_tolerance_rejected():
120 header = sign_header(PAYLOAD, timestamp=NOW + 3600)
121 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
122 assert result["ok"] is False
123 assert "in the future" in result["reason"]
124
125
126@pytest.mark.parametrize("offset", [-300, -299, 0, 299, 300])
127def test_inside_or_exactly_at_tolerance_is_accepted(offset):
128 """The window is closed at both ends: |now - t| == tolerance passes."""
129 stamp = NOW + offset
130 header = sign_header(PAYLOAD, timestamp=stamp)
131 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
132 assert result["ok"] is True
133 assert result["timestamp"] == stamp
134
135
136@pytest.mark.parametrize("offset", [-301, 301])
137def test_one_second_past_tolerance_is_rejected(offset):
138 header = sign_header(PAYLOAD, timestamp=NOW + offset)
139 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
140 assert result["ok"] is False
141 assert "tolerance" in result["reason"]
142
143
144def test_tolerance_is_configurable():
145 header = sign_header(PAYLOAD, timestamp=NOW - 600)
146 assert object_stripe.verify_webhook_signature(
147 PAYLOAD, header, SECRET, now=NOW)["ok"] is False
148 assert object_stripe.verify_webhook_signature(
149 PAYLOAD, header, SECRET, tolerance_seconds=900, now=NOW)["ok"] is True
150
151
152def test_default_now_uses_the_clock(monkeypatch):
153 monkeypatch.setattr(object_stripe.time, "time", lambda: float(NOW))
154 result = object_stripe.verify_webhook_signature(PAYLOAD, sign_header(PAYLOAD), SECRET)
155 assert result["ok"] is True
156
157
158def test_a_captured_valid_event_cannot_be_replayed_later():
159 """The whole point of the window: a real, correctly-signed event
160 sniffed off the wire is worthless an hour after it was sent."""
161 header = sign_header(PAYLOAD, timestamp=NOW)
162 assert object_stripe.verify_webhook_signature(
163 PAYLOAD, header, SECRET, now=NOW)["ok"] is True
164 assert object_stripe.verify_webhook_signature(
165 PAYLOAD, header, SECRET, now=NOW + 3601)["ok"] is False
166
167
168# --- signature: secret rotation ---------------------------------------------
169
170def test_multiple_v1_signatures_accepted_when_one_matches():
171 good = sign_header(PAYLOAD).split("v1=", 1)[1]
172 header = f"t={NOW},v1={'0' * 64},v1={good}"
173 assert object_stripe.verify_webhook_signature(
174 PAYLOAD, header, SECRET, now=NOW)["ok"] is True
175
176
177def test_multiple_v1_signatures_rejected_when_none_match():
178 header = f"t={NOW},v1={'0' * 64},v1={'f' * 64}"
179 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
180 assert result["ok"] is False
181 assert "no v1 signature matched" in result["reason"]
182
183
184def test_v0_only_is_rejected():
185 """v0 is Stripe's test-mode scheme over a different payload. Treating
186 it as a signature would accept anything the dashboard can send."""
187 header = sign_header(PAYLOAD, scheme="v0")
188 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
189 assert result["ok"] is False
190 assert "no v1= signature" in result["reason"]
191
192
193def test_v0_alongside_a_valid_v1_still_verifies():
194 good = sign_header(PAYLOAD).split("v1=", 1)[1]
195 header = f"t={NOW},v0={'a' * 64},v1={good}"
196 assert object_stripe.verify_webhook_signature(
197 PAYLOAD, header, SECRET, now=NOW)["ok"] is True
198
199
200def test_too_many_v1_values_is_refused():
201 """A rotation uses two secrets, not sixty. A header stuffed with
202 candidates is a resource-exhaustion probe, not a webhook."""
203 # 17 candidates stays under the 2048-char header cap, so the
204 # signature-count limit itself fires; 40 would trip the length cap
205 # first, which the length test covers separately.
206 header = "t=%d,%s" % (NOW, ",".join(f"v1={'0' * 64}" for _ in range(17)))
207 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
208 assert result["ok"] is False
209 assert "more than 16 v1 signatures" in result["reason"]
210
211
212# --- signature: malformed headers -------------------------------------------
213
214MALFORMED = [
215 ("", "signature header is missing"),
216 (" ", "signature header is missing"),
217 (None, "signature header is missing"),
218 (12345, "signature header is missing"),
219 (b"t=1,v1=abc", "signature header is missing"),
220 ("v1=" + "a" * 64, "no t= timestamp"),
221 (f"t={NOW}", "no v1= signature"),
222 (f"t={NOW},v1=", "no v1= signature"),
223 ("t=,v1=" + "a" * 64, "no t= timestamp"),
224 ("t=abc,v1=" + "a" * 64, "not a plain unsigned integer"),
225 ("t=-1,v1=" + "a" * 64, "not a plain unsigned integer"),
226 ("t=1.5,v1=" + "a" * 64, "not a plain unsigned integer"),
227 ("t=0x10,v1=" + "a" * 64, "not a plain unsigned integer"),
228 ("t=١٧٠٠٠٠٠٠٠٠,v1=" + "a" * 64, "not a plain unsigned integer"),
229 # 5000 nines would trip the header-length cap first; 100 exercises the
230 # timestamp check itself (a digit-length cap on t=, refused as not a
231 # plain unsigned integer rather than parsed into a bignum).
232 ("t=" + "9" * 100 + ",v1=" + "a" * 64, "not a plain unsigned integer"),
233 (f"t={NOW},t={NOW + 1},v1=" + "a" * 64, "more than one t= timestamp"),
234 ("wat", "no t= timestamp"),
235 (",,,,", "no t= timestamp"),
236 ("=", "no t= timestamp"),
237 ("t", "no t= timestamp"),
238 ("\x00\x01\x02", "no t= timestamp"),
239 ("t=" + str(NOW) + ",v1=" + "z" * 64, "no v1 signature matched"),
240]
241
242
243@pytest.mark.parametrize("header,expected", MALFORMED)
244def test_malformed_headers_are_refused_never_raised(header, expected):
245 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
246 assert result["ok"] is False
247 assert isinstance(result["reason"], str) and result["reason"]
248 assert expected in result["reason"]
249
250
251def test_oversized_header_is_refused():
252 header = f"t={NOW},v1=" + "a" * 4000
253 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
254 assert result["ok"] is False
255 assert "longer than 2048 characters" in result["reason"]
256
257
258def test_spaces_after_commas_are_tolerated():
259 """Stripe emits none, but a reverse proxy that normalises headers is a
260 realistic thing to sit behind. Whitespace cannot change what is
261 verified -- the t token is constrained to ASCII digits and the digest
262 is compared byte for byte -- so leniency here is free."""
263 header = sign_header(PAYLOAD).replace(",", ", ")
264 assert object_stripe.verify_webhook_signature(
265 PAYLOAD, header, SECRET, now=NOW)["ok"] is True
266
267
268def test_leading_and_trailing_header_whitespace_tolerated():
269 header = " " + sign_header(PAYLOAD) + " \r\n"
270 assert object_stripe.verify_webhook_signature(
271 PAYLOAD, header, SECRET, now=NOW)["ok"] is True
272
273
274def test_uppercase_hex_digest_is_refused():
275 """A deliberate strictness: hex is case-insensitive in principle, but
276 Stripe emits lowercase, so accepting mixed case would mean
277 canonicalising attacker input immediately before a security
278 comparison. If Stripe ever changes, every webhook fails loudly and
279 visibly rather than one of them passing quietly."""
280 header = sign_header(PAYLOAD)
281 upper = header.split("v1=", 1)[1].upper()
282 result = object_stripe.verify_webhook_signature(
283 PAYLOAD, f"t={NOW},v1={upper}", SECRET, now=NOW)
284 assert result["ok"] is False
285
286
287def test_non_ascii_signature_candidate_is_skipped_not_raised():
288 """hmac.compare_digest raises TypeError on non-ASCII str -- exactly the
289 500-on-garbage a public webhook URL must never do."""
290 good = sign_header(PAYLOAD).split("v1=", 1)[1]
291 header = f"t={NOW},v1=café{'a' * 60},v1={good}"
292 assert object_stripe.verify_webhook_signature(
293 PAYLOAD, header, SECRET, now=NOW)["ok"] is True
294
295 only_bad = f"t={NOW},v1=café{'a' * 60}"
296 result = object_stripe.verify_webhook_signature(PAYLOAD, only_bad, SECRET, now=NOW)
297 assert result["ok"] is False
298
299
300def test_timestamp_token_is_signed_verbatim_not_reparsed():
301 """A token with a leading zero still verifies against what was signed.
302
303 Stripe hashes the characters it sent. Re-serialising int(t) back into
304 the signed string would break on any representation we did not
305 anticipate; hashing the token as it arrived cannot.
306 """
307 token = "01700000000"
308 digest = hmac.new(SECRET.encode(), token.encode() + b"." + PAYLOAD,
309 hashlib.sha256).hexdigest()
310 result = object_stripe.verify_webhook_signature(
311 PAYLOAD, f"t={token},v1={digest}", SECRET, now=1700000000)
312 assert result["ok"] is True
313 assert result["timestamp"] == 1700000000
314
315
316# --- signature: the empty-secret hole ---------------------------------------
317
318def test_empty_webhook_secret_never_verifies():
319 """The one that matters most.
320
321 HMAC keyed with "" is a function anyone can compute, so an
322 unconfigured deployment that verified against an empty secret would
323 accept forged payment events from the entire internet. Here is the
324 exact forgery, and it must be refused.
325 """
326 forged_digest = hmac.new(b"", str(NOW).encode() + b"." + PAYLOAD,
327 hashlib.sha256).hexdigest()
328 header = f"t={NOW},v1={forged_digest}"
329 for absent in ("", " ", None, 0):
330 result = object_stripe.verify_webhook_signature(PAYLOAD, header, absent, now=NOW)
331 assert result["ok"] is False
332 assert "webhook secret is not configured" in result["reason"]
333
334
335def test_unconfigured_config_cannot_verify_anything():
336 config = object_stripe.stripe_config_from_env({})
337 assert config.configured is False
338 result = object_stripe.verify_webhook_signature(
339 PAYLOAD, sign_header(PAYLOAD), config.webhook_secret, now=NOW)
340 assert result["ok"] is False
341
342
343# --- signature: payload typing ----------------------------------------------
344
345def test_decoded_string_payload_is_refused():
346 """The single most common real-world webhook bug: handing the verifier
347 the framework's decoded body. It usually works, which is why it is
348 dangerous -- so it is refused outright."""
349 result = object_stripe.verify_webhook_signature(
350 PAYLOAD.decode(), sign_header(PAYLOAD), SECRET, now=NOW)
351 assert result["ok"] is False
352 assert "raw request bytes" in result["reason"]
353
354
355@pytest.mark.parametrize("payload", [None, 12, {"id": "evt_1"}, ["a"]])
356def test_non_bytes_payload_is_refused(payload):
357 result = object_stripe.verify_webhook_signature(
358 payload, sign_header(PAYLOAD), SECRET, now=NOW)
359 assert result["ok"] is False
360 assert "must be" in result["reason"]
361
362
363def test_bytearray_and_memoryview_payloads_work():
364 header = sign_header(PAYLOAD)
365 for shape in (bytearray(PAYLOAD), memoryview(PAYLOAD)):
366 assert object_stripe.verify_webhook_signature(
367 shape, header, SECRET, now=NOW)["ok"] is True
368
369
370def test_payload_that_is_not_valid_utf8_still_verifies():
371 """The divergence from the docs' "{t}.{body}" string formulation: the
372 MAC is over raw bytes. A body with an invalid UTF-8 sequence would
373 make a decode-then-hash implementation raise -- i.e. 500 -- on input
374 an attacker fully controls."""
375 payload = b'{"id":"evt_1","raw":"\xff\xfe"}'
376 result = object_stripe.verify_webhook_signature(
377 payload, sign_header(payload), SECRET, now=NOW)
378 assert result["ok"] is True
379
380
381def test_empty_payload_still_verifies_against_its_own_signature():
382 assert object_stripe.verify_webhook_signature(
383 b"", sign_header(b""), SECRET, now=NOW)["ok"] is True
384
385
386def test_no_reason_string_ever_leaks_the_secret_or_a_digest():
387 expected = hmac.new(SECRET.encode(), str(NOW).encode() + b"." + PAYLOAD,
388 hashlib.sha256).hexdigest()
389 for header, _ in MALFORMED:
390 result = object_stripe.verify_webhook_signature(PAYLOAD, header, SECRET, now=NOW)
391 assert SECRET not in result["reason"]
392 assert expected not in result["reason"]
393 stale = object_stripe.verify_webhook_signature(
394 PAYLOAD, sign_header(PAYLOAD, timestamp=1), SECRET, now=NOW)
395 assert SECRET not in stale["reason"] and expected not in stale["reason"]
396
397
398@pytest.mark.parametrize("junk", [
399 "t=1,v1=" + "\x00" * 64,
400 "t=1;v1=abc",
401 "t==1,v1==abc",
402 "t=1,,v1=abc,",
403 "T=1,V1=abc",
404 "t=1,v1=abc" * 50,
405 "\t\n",
406 "t=99999999999999999999999999,v1=" + "a" * 64,
407])
408def test_hostile_headers_never_raise(junk):
409 result = object_stripe.verify_webhook_signature(PAYLOAD, junk, SECRET, now=NOW)
410 assert result["ok"] is False
411 assert isinstance(result["reason"], str)
412
413
414# --- timing safety ----------------------------------------------------------
415
416_SENSITIVE_NAMES = {
417 "expected", "offered", "offered_list", "candidate", "digest", "hexdigest",
418 "signature", "signatures", "secret", "webhook_secret", "material", "mac",
419 "compare_digest",
420}
421
422
423def _names_in(node):
424 found = set()
425 for child in ast.walk(node):
426 if isinstance(child, ast.Name):
427 found.add(child.id)
428 elif isinstance(child, ast.Attribute):
429 found.add(child.attr)
430 return found
431
432
433def test_signature_comparison_uses_compare_digest_only():
434 """Belt and braces for a rule whose regression would be invisible.
435
436 A `==` on a hex digest compares byte by byte and returns early, which
437 leaks the length of the correct prefix through timing -- enough, over
438 many requests, to reconstruct a valid signature. Nothing in this
439 module may ever compare secret-derived values with == or !=, and a
440 reviewer cannot see the difference by reading the diff, so the check
441 is mechanical.
442 """
443 source = inspect.getsource(object_stripe)
444 assert "hmac.compare_digest(" in source
445
446 tree = ast.parse(source)
447 offenders = []
448 for node in ast.walk(tree):
449 if not isinstance(node, ast.Compare):
450 continue
451 for op, right in zip(node.ops, node.comparators):
452 if not isinstance(op, (ast.Eq, ast.NotEq)):
453 continue
454 names = _names_in(node.left) | _names_in(right)
455 if names & _SENSITIVE_NAMES:
456 offenders.append((node.lineno, sorted(names & _SENSITIVE_NAMES)))
457 assert offenders == [], f"secret-derived == comparison at {offenders}"
458
459
460def test_verification_never_calls_hexdigest_into_an_equality():
461 source = inspect.getsource(object_stripe.verify_webhook_signature)
462 assert "compare_digest" in source
463 for line in source.splitlines():
464 if "hexdigest" in line:
465 assert "==" not in line and "!=" not in line
466
467
468# --- parse_event ------------------------------------------------------------
469
470def test_parse_event_returns_the_dict():
471 event = object_stripe.parse_event(PAYLOAD)
472 assert event["id"] == "evt_1Abc"
473 assert event["type"] == "checkout.session.completed"
474
475
476def test_parse_event_rejects_oversized_payload():
477 body = b'{"id":"evt_1","pad":"' + b"x" * 2000 + b'"}'
478 with pytest.raises(object_stripe.StripePayloadError) as exc:
479 object_stripe.parse_event(body, max_bytes=1000)
480 assert "over the 1000-byte cap" in str(exc.value)
481
482
483def test_parse_event_default_cap_is_one_megabyte():
484 assert object_stripe.MAX_PAYLOAD_BYTES == 1_000_000
485 body = b'{"id":"evt_1","pad":"' + b"x" * 1_000_001 + b'"}'
486 with pytest.raises(object_stripe.StripePayloadError):
487 object_stripe.parse_event(body)
488
489
490def test_parse_event_checks_size_before_parsing():
491 """The cap must gate the parse, not follow it -- otherwise a 200MB
492 body is already decoded and in memory by the time it is refused."""
493 body = b"[" + b"1," * 500_000 + b"1]"
494 with pytest.raises(object_stripe.StripePayloadError) as exc:
495 object_stripe.parse_event(body, max_bytes=100)
496 assert "cap" in str(exc.value)
497
498
499@pytest.mark.parametrize("body", [b"[]", b'"a string"', b"42", b"null", b"true"])
500def test_parse_event_rejects_non_object_json(body):
501 with pytest.raises(object_stripe.StripePayloadError) as exc:
502 object_stripe.parse_event(body)
503 assert "not an object" in str(exc.value)
504
505
506@pytest.mark.parametrize("body", [b"{", b"", b" ", b"not json at all", b"{'a': 1}"])
507def test_parse_event_rejects_unparseable(body):
508 with pytest.raises(object_stripe.StripePayloadError):
509 object_stripe.parse_event(body)
510
511
512def test_parse_event_rejects_invalid_utf8():
513 with pytest.raises(object_stripe.StripePayloadError) as exc:
514 object_stripe.parse_event(b'{"id":"\xff\xfe"}')
515 assert "UTF-8" in str(exc.value)
516
517
518def test_parse_event_rejects_a_decoded_string():
519 with pytest.raises(object_stripe.StripePayloadError) as exc:
520 object_stripe.parse_event(PAYLOAD.decode())
521 assert "raw request bytes" in str(exc.value)
522
523
524def test_parse_event_errors_are_stripe_errors():
525 assert issubclass(object_stripe.StripePayloadError, object_stripe.StripeError)
526 with pytest.raises(object_stripe.StripeError):
527 object_stripe.parse_event(b"[]")
528
529
530# --- event_marker -----------------------------------------------------------
531
532def test_event_marker_shape():
533 assert object_stripe.event_marker({"id": "evt_1Abc"}) == "stripe_evt/evt_1Abc"
534
535
536@pytest.mark.parametrize("event", [
537 {}, {"id": ""}, {"id": None}, {"id": 12}, {"id": ["evt_1"]}, {"identifier": "evt_1"},
538])
539def test_event_marker_requires_a_string_id(event):
540 with pytest.raises(object_stripe.StripePayloadError):
541 object_stripe.event_marker(event)
542
543
544@pytest.mark.parametrize("event", [None, "evt_1", ["evt_1"], 7])
545def test_event_marker_requires_an_event_object(event):
546 with pytest.raises(object_stripe.StripePayloadError):
547 object_stripe.event_marker(event)
548
549
550@pytest.mark.parametrize("ident", [
551 "evt_1\tevil", "evt_1\nevil", "evt_1\revil", "evt 1", "evt/1", "evt_1\x00",
552 "../../etc/passwd", "evt_1;DROP", "évt_1",
553])
554def test_event_marker_refuses_ids_that_would_corrupt_a_tsv_row(ident):
555 """The store is tab-separated rows. A tab or newline inside the
556 provenance stamp does not look odd in a log -- it splits one record
557 into two."""
558 with pytest.raises(object_stripe.StripePayloadError):
559 object_stripe.event_marker({"id": ident})
560
561
562def test_event_marker_refuses_an_absurdly_long_id():
563 with pytest.raises(object_stripe.StripePayloadError):
564 object_stripe.event_marker({"id": "e" * 500})
565
566
567def test_event_marker_error_does_not_echo_a_whole_hostile_id():
568 with pytest.raises(object_stripe.StripePayloadError) as exc:
569 object_stripe.event_marker({"id": "evt_" + "A" * 300})
570 assert len(str(exc.value)) < 120
571
572
573# --- flatten_params ---------------------------------------------------------
574
575def test_flatten_nested_dicts_and_lists():
576 pairs = object_stripe.flatten_params(
577 {"line_items": [{"price_data": {"currency": "usd", "unit_amount": 1250}}]})
578 assert pairs == [
579 ("line_items[0][price_data][currency]", "usd"),
580 ("line_items[0][price_data][unit_amount]", "1250"),
581 ]
582
583
584def test_flatten_list_indices_are_positional():
585 pairs = object_stripe.flatten_params({"items": [{"a": "1"}, {"a": "2"}]})
586 assert pairs == [("items[0][a]", "1"), ("items[1][a]", "2")]
587
588
589def test_flatten_booleans_are_lowercase_json_style():
590 pairs = dict(object_stripe.flatten_params({"yes": True, "no": False}))
591 assert pairs == {"yes": "true", "no": "false"}
592
593
594def test_flatten_false_does_not_become_truthy_text():
595 """bool is an int subclass; str(False) is "True"-shaped to Stripe (a
596 non-empty string), so the bool branch has to come first."""
597 assert object_stripe.flatten_params({"expand": False}) == [("expand", "false")]
598
599
600def test_flatten_ints_and_decimals():
601 pairs = dict(object_stripe.flatten_params({"n": 0, "neg": -5, "d": Decimal("1.5")}))
602 assert pairs == {"n": "0", "neg": "-5", "d": "1.5"}
603
604
605def test_flatten_omits_none_entirely():
606 assert object_stripe.flatten_params({"a": "1", "b": None}) == [("a", "1")]
607
608
609def test_flatten_none_inside_a_list_does_not_renumber_siblings():
610 pairs = object_stripe.flatten_params({"xs": [None, {"a": "1"}]})
611 assert pairs == [("xs[1][a]", "1")]
612
613
614def test_flatten_empty_containers_emit_nothing():
615 assert object_stripe.flatten_params({}) == []
616 assert object_stripe.flatten_params({"a": {}, "b": []}) == []
617
618
619def test_flatten_refuses_floats():
620 with pytest.raises(object_stripe.StripePayloadError) as exc:
621 object_stripe.flatten_params({"unit_amount": 12.50})
622 assert "float" in str(exc.value)
623
624
625@pytest.mark.parametrize("value", [object(), b"bytes", {1, 2}])
626def test_flatten_refuses_unsupported_types(value):
627 with pytest.raises(object_stripe.StripePayloadError):
628 object_stripe.flatten_params({"x": value})
629
630
631@pytest.mark.parametrize("key", ["a[b]", "a=b", "a&b", "", "a\nb", "a\tb"])
632def test_flatten_refuses_names_that_could_forge_structure(key):
633 with pytest.raises(object_stripe.StripePayloadError):
634 object_stripe.flatten_params({key: "1"})
635
636
637def test_flatten_refuses_a_top_level_scalar():
638 with pytest.raises(object_stripe.StripePayloadError):
639 object_stripe.flatten_params("mode=payment")
640
641
642def test_flatten_caps_depth():
643 deep = value = {}
644 for _ in range(20):
645 value["k"] = {}
646 value = value["k"]
647 with pytest.raises(object_stripe.StripePayloadError) as exc:
648 object_stripe.flatten_params(deep)
649 assert "nest deeper" in str(exc.value)
650
651
652def test_flatten_survives_a_self_referencing_dict():
653 """Without a depth cap this is a RecursionError, which is a crash, not
654 a refusal."""
655 loop = {"a": {}}
656 loop["a"]["self"] = loop
657 with pytest.raises(object_stripe.StripePayloadError):
658 object_stripe.flatten_params(loop)
659
660
661def test_encode_params_percent_encodes_structure_and_values():
662 body = object_stripe.encode_params({"metadata": {"invoice_id": "inv 1&2"}})
663 assert body == "metadata%5Binvoice_id%5D=inv+1%262"
664 assert dict(urllib.parse.parse_qsl(body)) == {"metadata[invoice_id]": "inv 1&2"}
665
666
667def test_encode_params_output_is_ascii():
668 body = object_stripe.encode_params({"metadata": {"note": "café ☕"}})
669 assert body.isascii()
670 assert dict(urllib.parse.parse_qsl(body))["metadata[note]"] == "café ☕"
671
672
673def test_a_value_cannot_introduce_a_parameter():
674 """The injection question: can a metadata value forge a sibling key?"""
675 body = object_stripe.encode_params(
676 {"metadata": {"note": "x&mode=subscription"}, "mode": "payment"})
677 pairs = urllib.parse.parse_qsl(body)
678 assert [k for k, _ in pairs] == ["metadata[note]", "mode"]
679 assert dict(pairs)["mode"] == "payment"
680
681
682# --- api_request ------------------------------------------------------------
683
684class Recorder:
685 """A transport that records and never opens a socket."""
686
687 def __init__(self, status=200, body=b'{"id":"cs_test_1","object":"checkout.session"}'):
688 self.status = status
689 self.body = body
690 self.calls = []
691
692 def __call__(self, url, data, headers, method):
693 self.calls.append({"url": url, "data": data,
694 "headers": dict(headers), "method": method})
695 return self.status, self.body
696
697 @property
698 def last(self):
699 return self.calls[-1]
700
701
702def config(**overrides):
703 base = {"secret_key": "sk_test_51abcDEFghiJKL", "webhook_secret": SECRET,
704 "api_base": "https://api.stripe.test"}
705 base.update(overrides)
706 return object_stripe.StripeConfig(**base)
707
708
709def test_api_request_sends_bearer_auth_and_form_body():
710 transport = Recorder()
711 object_stripe.api_request(config(), "POST", "/v1/customers",
712 {"email": "a@b.test"}, transport=transport)
713 call = transport.last
714 assert call["method"] == "POST"
715 assert call["url"] == "https://api.stripe.test/v1/customers"
716 assert call["headers"]["Authorization"] == "Bearer sk_test_51abcDEFghiJKL"
717 assert call["headers"]["Content-Type"] == "application/x-www-form-urlencoded"
718 assert call["data"] == b"email=a%40b.test"
719
720
721def test_api_request_returns_the_parsed_object():
722 transport = Recorder(body=b'{"id":"cus_1","livemode":false}')
723 result = object_stripe.api_request(config(), "POST", "/v1/customers", {},
724 transport=transport)
725 assert result == {"id": "cus_1", "livemode": False}
726
727
728def test_post_gets_an_idempotency_key_automatically():
729 transport = Recorder()
730 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
731 key = transport.last["headers"]["Idempotency-Key"]
732 assert len(key) == 36 and key.count("-") == 4
733
734
735def test_auto_idempotency_keys_differ_per_call():
736 """Documenting the sharp edge: the auto key protects against Stripe's
737 own retries, NOT against a caller retrying. Two calls are two charges,
738 which is why a retrying caller must pass its own key."""
739 transport = Recorder()
740 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
741 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
742 keys = [c["headers"]["Idempotency-Key"] for c in transport.calls]
743 assert keys[0] != keys[1]
744
745
746def test_explicit_idempotency_key_is_used_verbatim():
747 transport = Recorder()
748 object_stripe.api_request(config(), "POST", "/v1/charges", {},
749 idempotency_key="invoice-42-attempt", transport=transport)
750 assert transport.last["headers"]["Idempotency-Key"] == "invoice-42-attempt"
751
752
753def test_get_carries_params_in_the_query_string_and_no_body():
754 transport = Recorder(body=b'{"object":"list","data":[]}')
755 object_stripe.api_request(config(), "GET", "/v1/events",
756 {"limit": 3, "type": "checkout.session.completed"},
757 transport=transport)
758 call = transport.last
759 assert call["data"] is None
760 assert "Content-Type" not in call["headers"]
761 assert "Idempotency-Key" not in call["headers"]
762 assert call["url"].endswith("?limit=3&type=checkout.session.completed")
763
764
765def test_get_without_params_has_a_clean_url():
766 transport = Recorder(body=b"{}")
767 object_stripe.api_request(config(), "GET", "/v1/balance", None, transport=transport)
768 assert transport.last["url"] == "https://api.stripe.test/v1/balance"
769
770
771def test_api_version_header_only_when_pinned():
772 transport = Recorder()
773 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
774 assert "Stripe-Version" not in transport.last["headers"]
775
776 object_stripe.api_request(config(api_version="2026-01-01"), "POST", "/v1/charges",
777 {}, transport=transport)
778 assert transport.last["headers"]["Stripe-Version"] == "2026-01-01"
779
780
781def test_stripe_error_body_becomes_a_stripe_error():
782 body = json.dumps({"error": {
783 "type": "card_error", "code": "card_declined", "param": "number",
784 "message": "Your card was declined."}}).encode()
785 transport = Recorder(status=402, body=body)
786 with pytest.raises(object_stripe.StripeError) as exc:
787 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
788 err = exc.value
789 assert err.status == 402
790 assert err.type == "card_error"
791 assert err.code == "card_declined"
792 assert err.param == "number"
793 assert err.message == "Your card was declined."
794 assert str(err) == "Your card was declined."
795
796
797def test_error_object_on_a_200_is_still_an_error():
798 transport = Recorder(status=200, body=b'{"error":{"message":"nope"}}')
799 with pytest.raises(object_stripe.StripeError):
800 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
801
802
803def test_plain_5xx_without_an_error_object_is_an_error():
804 transport = Recorder(status=500, body=b"{}")
805 with pytest.raises(object_stripe.StripeError) as exc:
806 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
807 assert exc.value.status == 500
808 assert "HTTP 500" in str(exc.value)
809
810
811def test_redirect_status_is_an_error_not_a_result():
812 """The default transport refuses to follow redirects (they would carry
813 the Authorization header elsewhere), so a 3xx reaching this layer
814 means the call never got to Stripe."""
815 transport = Recorder(status=302, body=b'{"id":"not_really"}')
816 with pytest.raises(object_stripe.StripeError) as exc:
817 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
818 assert exc.value.status == 302
819
820
821def test_non_json_response_is_a_clear_error():
822 transport = Recorder(status=502, body=b"<html><body>Bad Gateway</body></html>")
823 with pytest.raises(object_stripe.StripePayloadError) as exc:
824 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
825 assert "non-JSON" in str(exc.value)
826 assert "HTTP 502" in str(exc.value)
827
828
829def test_non_object_json_response_is_a_clear_error():
830 transport = Recorder(status=200, body=b"[1,2,3]")
831 with pytest.raises(object_stripe.StripePayloadError) as exc:
832 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
833 assert "not an object" in str(exc.value)
834
835
836def test_empty_2xx_body_is_an_empty_dict():
837 transport = Recorder(status=204, body=b"")
838 assert object_stripe.api_request(config(), "DELETE", "/v1/customers/cus_1", None,
839 transport=transport) == {}
840
841
842def test_empty_error_body_still_raises():
843 transport = Recorder(status=500, body=b"")
844 with pytest.raises(object_stripe.StripeError):
845 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
846
847
848def test_oversized_response_is_refused():
849 transport = Recorder(body=b"x" * (object_stripe.MAX_RESPONSE_BYTES + 1))
850 with pytest.raises(object_stripe.StripePayloadError) as exc:
851 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=transport)
852 assert "cap" in str(exc.value)
853
854
855def test_transport_returning_junk_is_a_clear_error():
856 with pytest.raises(object_stripe.StripePayloadError):
857 object_stripe.api_request(config(), "POST", "/v1/charges", {},
858 transport=lambda *a: (200, "a string, not bytes"))
859 with pytest.raises(object_stripe.StripePayloadError):
860 object_stripe.api_request(config(), "POST", "/v1/charges", {},
861 transport=lambda *a: ("wat", b"{}"))
862
863
864def test_transport_exception_is_wrapped_in_a_stripe_error():
865 def boom(url, data, headers, method):
866 raise OSError("connection reset")
867
868 with pytest.raises(object_stripe.StripeError) as exc:
869 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=boom)
870 assert "connection reset" in str(exc.value)
871
872
873def test_a_secret_in_an_error_message_is_redacted():
874 """Defence in depth: nothing deliberately puts a key in a message, but
875 a proxy error page or an OSError from a lower layer might."""
876 key = "sk_test_51abcDEFghiJKL"
877 body = json.dumps({"error": {"message": f"bad key {key} supplied"}}).encode()
878 with pytest.raises(object_stripe.StripeError) as exc:
879 object_stripe.api_request(config(), "POST", "/v1/charges", {},
880 transport=Recorder(status=401, body=body))
881 assert key not in str(exc.value)
882 assert "***" in str(exc.value)
883
884
885def test_a_secret_in_a_transport_exception_is_redacted():
886 key = "sk_test_51abcDEFghiJKL"
887
888 def boom(url, data, headers, method):
889 raise RuntimeError(f"failed talking to stripe with {key}")
890
891 with pytest.raises(object_stripe.StripeError) as exc:
892 object_stripe.api_request(config(), "POST", "/v1/charges", {}, transport=boom)
893 assert key not in str(exc.value)
894
895
896def test_missing_secret_key_refuses_before_the_transport_is_called():
897 transport = Recorder()
898 with pytest.raises(object_stripe.StripeError) as exc:
899 object_stripe.api_request(object_stripe.StripeConfig(webhook_secret=SECRET),
900 "POST", "/v1/charges", {}, transport=transport)
901 assert "secret key is not configured" in str(exc.value)
902 assert transport.calls == []
903
904
905@pytest.mark.parametrize("method", ["PUT", "PATCH", "TRACE", "", None, "post; drop"])
906def test_unsupported_methods_are_refused(method):
907 transport = Recorder()
908 with pytest.raises(object_stripe.StripeError):
909 object_stripe.api_request(config(), method, "/v1/charges", {}, transport=transport)
910 assert transport.calls == []
911
912
913def test_method_is_case_normalised():
914 transport = Recorder()
915 object_stripe.api_request(config(), "post", "/v1/charges", {}, transport=transport)
916 assert transport.last["method"] == "POST"
917
918
919# --- api_request: where the key is allowed to go ----------------------------
920
921@pytest.mark.parametrize("base", [
922 "http://api.stripe.com", "http://example.test", "ftp://api.stripe.com",
923 "file:///etc/passwd", "api.stripe.com", "https://",
924])
925def test_unsafe_api_bases_are_refused(base):
926 """A live secret key rides in a header on every request, so plaintext
927 http to anything but loopback is refused outright."""
928 transport = Recorder()
929 with pytest.raises(object_stripe.StripeError):
930 object_stripe.api_request(config(api_base=base), "POST", "/v1/charges", {},
931 transport=transport)
932 assert transport.calls == []
933
934
935def test_an_empty_api_base_is_coerced_to_the_official_default():
936 """Blank is not a destination: both StripeConfig and api_request fold an
937 empty base to the official endpoint rather than refusing -- an operator
938 who cleared the variable gets Stripe, never a relative-URL surprise.
939 Coercion here is SAFER than rejection, which is why this is its own
940 test instead of a row in the refusal table."""
941 transport = Recorder()
942 object_stripe.api_request(config(api_base=""), "POST", "/v1/charges", {},
943 transport=transport)
944 assert transport.calls[0]["url"].startswith("https://api.stripe.com/")
945
946
947@pytest.mark.parametrize("base", ["http://localhost:12111", "http://127.0.0.1:8080"])
948def test_loopback_http_is_allowed_for_a_mock_server(base):
949 transport = Recorder()
950 object_stripe.api_request(config(api_base=base), "POST", "/v1/charges", {},
951 transport=transport)
952 assert transport.last["url"].startswith(base)
953
954
955@pytest.mark.parametrize("path", [
956 "https://evil.test/v1/charges", "//evil.test/v1/charges",
957 "/v1/../../secret", "/v1/charges\r\nX-Evil: 1", "/v1/ charges", "/v1/\x00",
958])
959def test_a_path_cannot_point_the_call_somewhere_else(path):
960 transport = Recorder()
961 with pytest.raises(object_stripe.StripeError):
962 object_stripe.api_request(config(), "POST", path, {}, transport=transport)
963 assert transport.calls == []
964
965
966def test_a_bare_path_segment_is_accepted_and_rooted():
967 transport = Recorder()
968 object_stripe.api_request(config(), "POST", "v1/charges", {}, transport=transport)
969 assert transport.last["url"] == "https://api.stripe.test/v1/charges"
970
971
972def test_trailing_slash_on_the_base_does_not_double_up():
973 transport = Recorder()
974 object_stripe.api_request(config(api_base="https://api.stripe.test/"), "POST",
975 "/v1/charges", {}, transport=transport)
976 assert transport.last["url"] == "https://api.stripe.test/v1/charges"
977
978
979def test_default_transport_refuses_a_bad_url_before_any_socket():
980 """Exercises the real default transport path far enough to prove the
981 URL gate runs first; no connection is ever attempted."""
982 with pytest.raises(object_stripe.StripeError):
983 object_stripe.api_request(config(api_base="http://evil.test"), "POST",
984 "/v1/charges", {})
985
986
987# --- create_checkout_session ------------------------------------------------
988
989CHECKOUT = {
990 "amount_cents": 12500,
991 "currency": "usd",
992 "description": "Invoice INV-1042",
993 "success_url": "https://pay.example.test/done?s={CHECKOUT_SESSION_ID}",
994 "cancel_url": "https://pay.example.test/cancel",
995 "metadata": {"invoice_id": "inv_1042", "portal_token": "tok_abc"},
996}
997
998
999def test_checkout_session_encodes_stripes_exact_key_syntax():
1000 transport = Recorder()
1001 object_stripe.create_checkout_session(config(), transport=transport, **CHECKOUT)
1002 body = transport.last["data"].decode()
1003 pairs = dict(urllib.parse.parse_qsl(body))
1004
1005 assert pairs["mode"] == "payment"
1006 assert pairs["line_items[0][quantity]"] == "1"
1007 assert pairs["line_items[0][price_data][currency]"] == "usd"
1008 assert pairs["line_items[0][price_data][unit_amount]"] == "12500"
1009 assert pairs["line_items[0][price_data][product_data][name]"] == "Invoice INV-1042"
1010 assert pairs["success_url"] == CHECKOUT["success_url"]
1011 assert pairs["cancel_url"] == CHECKOUT["cancel_url"]
1012
1013 # and the same thing asserted on the raw wire bytes, brackets encoded
1014 assert "line_items%5B0%5D%5Bprice_data%5D%5Bcurrency%5D=usd" in body
1015 assert transport.last["url"] == "https://api.stripe.test/v1/checkout/sessions"
1016 assert transport.last["method"] == "POST"
1017 assert "Idempotency-Key" in transport.last["headers"]
1018
1019
1020def test_checkout_metadata_survives_on_both_the_session_and_the_intent():
1021 """Session metadata does not reach the PaymentIntent or the charge, so
1022 a handler for payment_intent.succeeded would have no invoice_id to
1023 credit. Mirroring is required, not decorative."""
1024 transport = Recorder()
1025 object_stripe.create_checkout_session(config(), transport=transport, **CHECKOUT)
1026 pairs = dict(urllib.parse.parse_qsl(transport.last["data"].decode()))
1027 assert pairs["metadata[invoice_id]"] == "inv_1042"
1028 assert pairs["metadata[portal_token]"] == "tok_abc"
1029 assert pairs["payment_intent_data[metadata][invoice_id]"] == "inv_1042"
1030 assert pairs["payment_intent_data[metadata][portal_token]"] == "tok_abc"
1031
1032
1033def test_checkout_with_no_metadata_sends_no_metadata_keys():
1034 transport = Recorder()
1035 object_stripe.create_checkout_session(config(), transport=transport,
1036 **{**CHECKOUT, "metadata": {}})
1037 body = transport.last["data"].decode()
1038 assert "metadata" not in urllib.parse.unquote_plus(body)
1039
1040
1041def test_checkout_returns_the_session():
1042 transport = Recorder(body=b'{"id":"cs_test_9","url":"https://checkout.stripe.test/c/9"}')
1043 session = object_stripe.create_checkout_session(config(), transport=transport, **CHECKOUT)
1044 assert session["id"] == "cs_test_9"
1045 assert session["url"].startswith("https://")
1046
1047
1048@pytest.mark.parametrize("amount", [
1049 0, -1, -12500, 12.50, "12500", None, True, False, Decimal("125"),
1050 object_stripe.MAX_AMOUNT_CENTS + 1,
1051])
1052def test_bad_amounts_are_refused_before_any_transport_call(amount):
1053 transport = Recorder()
1054 with pytest.raises(object_stripe.StripePayloadError):
1055 object_stripe.create_checkout_session(config(), transport=transport,
1056 **{**CHECKOUT, "amount_cents": amount})
1057 assert transport.calls == []
1058
1059
1060def test_boolean_amount_would_have_charged_one_cent():
1061 """bool is an int worth 1; without an explicit bool guard True is a
1062 valid, positive, one-cent charge."""
1063 with pytest.raises(object_stripe.StripePayloadError) as exc:
1064 object_stripe.create_checkout_session(config(), transport=Recorder(),
1065 **{**CHECKOUT, "amount_cents": True})
1066 assert "bool" in str(exc.value)
1067
1068
1069@pytest.mark.parametrize("currency", ["", "us", "usdd", "u$d", "12 ", None, "usd", "us d"])
1070def test_bad_currencies_are_refused_before_any_transport_call(currency):
1071 transport = Recorder()
1072 with pytest.raises(object_stripe.StripePayloadError):
1073 object_stripe.create_checkout_session(config(), transport=transport,
1074 **{**CHECKOUT, "currency": currency})
1075 assert transport.calls == []
1076
1077
1078def test_currency_case_is_normalised():
1079 transport = Recorder()
1080 object_stripe.create_checkout_session(config(), transport=transport,
1081 **{**CHECKOUT, "currency": " EUR "})
1082 pairs = dict(urllib.parse.parse_qsl(transport.last["data"].decode()))
1083 assert pairs["line_items[0][price_data][currency]"] == "eur"
1084
1085
1086@pytest.mark.parametrize("field", ["success_url", "cancel_url"])
1087@pytest.mark.parametrize("url", [
1088 "", None, "javascript:alert(1)", "data:text/html,<script>", "/relative/path",
1089 "pay.example.test/done", "https://pay.example.test/a\nb", "ftp://pay.example.test",
1090])
1091def test_bad_return_urls_are_refused(field, url):
1092 transport = Recorder()
1093 with pytest.raises(object_stripe.StripePayloadError):
1094 object_stripe.create_checkout_session(config(), transport=transport,
1095 **{**CHECKOUT, field: url})
1096 assert transport.calls == []
1097
1098
1099@pytest.mark.parametrize("description", ["", " ", None, "x" * 501])
1100def test_bad_descriptions_are_refused(description):
1101 transport = Recorder()
1102 with pytest.raises(object_stripe.StripePayloadError):
1103 object_stripe.create_checkout_session(config(), transport=transport,
1104 **{**CHECKOUT, "description": description})
1105 assert transport.calls == []
1106
1107
1108@pytest.mark.parametrize("metadata", [
1109 "invoice_id=1", ["invoice_id"], {"": "1"}, {"k" * 41: "1"},
1110 {"invoice_id": "v" * 501}, {f"k{i}": "1" for i in range(51)},
1111 {"invoice_id": 1.5}, {"inv[oice]": "1"},
1112])
1113def test_bad_metadata_is_refused_before_any_transport_call(metadata):
1114 transport = Recorder()
1115 with pytest.raises(object_stripe.StripePayloadError):
1116 object_stripe.create_checkout_session(config(), transport=transport,
1117 **{**CHECKOUT, "metadata": metadata})
1118 assert transport.calls == []
1119
1120
1121def test_metadata_scalars_are_stringified_and_nones_dropped():
1122 transport = Recorder()
1123 object_stripe.create_checkout_session(
1124 config(), transport=transport,
1125 **{**CHECKOUT, "metadata": {"n": 7, "flag": True, "gone": None}})
1126 pairs = dict(urllib.parse.parse_qsl(transport.last["data"].decode()))
1127 assert pairs["metadata[n]"] == "7"
1128 assert pairs["metadata[flag]"] == "true"
1129 assert "metadata[gone]" not in pairs
1130
1131
1132def test_checkout_refuses_when_stripe_is_unconfigured():
1133 transport = Recorder()
1134 with pytest.raises(object_stripe.StripeError):
1135 object_stripe.create_checkout_session(object_stripe.StripeConfig(),
1136 transport=transport, **CHECKOUT)
1137 assert transport.calls == []
1138
1139
1140# --- configuration ----------------------------------------------------------
1141
1142def test_config_defaults_are_dormant():
1143 cfg = object_stripe.stripe_config_from_env({})
1144 assert cfg.secret_key == ""
1145 assert cfg.webhook_secret == ""
1146 assert cfg.api_base == "https://api.stripe.com"
1147 assert cfg.api_version == ""
1148 assert cfg.configured is False
1149
1150
1151def test_config_reads_the_env():
1152 cfg = object_stripe.stripe_config_from_env({
1153 "DBBASIC_STRIPE_SECRET_KEY": "sk_live_abc123456789",
1154 "DBBASIC_STRIPE_WEBHOOK_SECRET": "whsec_def123456789",
1155 "DBBASIC_STRIPE_API_BASE": "https://api.stripe.test",
1156 "DBBASIC_STRIPE_API_VERSION": "2026-01-01",
1157 })
1158 assert cfg.secret_key == "sk_live_abc123456789"
1159 assert cfg.webhook_secret == "whsec_def123456789"
1160 assert cfg.api_base == "https://api.stripe.test"
1161 assert cfg.api_version == "2026-01-01"
1162 assert cfg.configured is True
1163
1164
1165@pytest.mark.parametrize("env", [
1166 {"DBBASIC_STRIPE_SECRET_KEY": "sk_live_abc123456789"},
1167 {"DBBASIC_STRIPE_WEBHOOK_SECRET": "whsec_def123456789"},
1168 {"DBBASIC_STRIPE_SECRET_KEY": " ", "DBBASIC_STRIPE_WEBHOOK_SECRET": "whsec_x1234567"},
1169 {},
1170])
1171def test_either_secret_missing_means_unconfigured(env):
1172 assert object_stripe.stripe_config_from_env(env).configured is False
1173
1174
1175def test_env_values_are_stripped():
1176 """A trailing newline in an env file is the classic cause of an
1177 invalid-signature storm on an otherwise correct secret."""
1178 cfg = object_stripe.stripe_config_from_env({
1179 "DBBASIC_STRIPE_SECRET_KEY": " sk_live_abc123456789\n",
1180 "DBBASIC_STRIPE_WEBHOOK_SECRET": "whsec_def123456789 ",
1181 })
1182 assert cfg.secret_key == "sk_live_abc123456789"
1183 assert cfg.webhook_secret == "whsec_def123456789"
1184
1185
1186def test_blank_api_base_falls_back_to_stripe():
1187 cfg = object_stripe.stripe_config_from_env({"DBBASIC_STRIPE_API_BASE": " "})
1188 assert cfg.api_base == "https://api.stripe.com"
1189
1190
1191def test_repr_masks_both_secrets():
1192 secret_key = "sk_live_51SUPERSECRETMATERIAL"
1193 webhook_secret = "whsec_ANOTHERSECRETVALUE"
1194 cfg = object_stripe.StripeConfig(secret_key=secret_key, webhook_secret=webhook_secret)
1195
1196 for rendering in (repr(cfg), str(cfg), f"{cfg}", "%s" % (cfg,), format(cfg)):
1197 assert secret_key not in rendering
1198 assert webhook_secret not in rendering
1199 assert "SUPERSECRETMATERIAL" not in rendering
1200 assert "ANOTHERSECRETVALUE" not in rendering
1201 assert "sk_live_***" in rendering
1202 assert "whsec_***" in rendering
1203 assert "configured=True" in rendering
1204
1205
1206def test_repr_of_an_unknown_key_shape_says_only_set():
1207 cfg = object_stripe.StripeConfig(secret_key="totally-custom-key-value")
1208 assert "totally-custom-key-value" not in repr(cfg)
1209 assert "secret_key=set" in repr(cfg)
1210
1211
1212def test_repr_of_a_short_prefix_only_secret_does_not_echo_it():
1213 cfg = object_stripe.StripeConfig(secret_key="sk_live_")
1214 assert "secret_key=set" in repr(cfg)
1215
1216
1217def test_repr_of_an_unconfigured_config_says_unset():
1218 text = repr(object_stripe.StripeConfig())
1219 assert "secret_key=unset" in text
1220 assert "webhook_secret=unset" in text
1221 assert "configured=False" in text
1222
1223
1224def test_config_is_not_a_tuple_that_could_be_unpacked_into_a_log():
1225 """A namedtuple would satisfy the same API while still dumping both
1226 secrets through str(tuple(cfg)) or print(*cfg) -- doors no __repr__
1227 override can close."""
1228 cfg = object_stripe.StripeConfig(secret_key="sk_live_51SUPERSECRET", webhook_secret=SECRET)
1229 assert not isinstance(cfg, tuple)
1230 with pytest.raises(TypeError):
1231 list(cfg)
1232 assert not hasattr(cfg, "__dict__")
1233
1234
1235def test_config_exposes_no_secret_dumping_helpers():
1236 cfg = object_stripe.StripeConfig(secret_key="sk_live_51SUPERSECRET")
1237 extras = [name for name in dir(cfg)
1238 if not name.startswith("_")
1239 and name not in {"secret_key", "webhook_secret", "api_base",
1240 "api_version", "configured"}]
1241 assert extras == []
1242
1243
1244# --- module posture ---------------------------------------------------------
1245
1246def test_module_never_logs():
1247 """Secrets and payloads must not be able to reach a log from here.
1248 The module makes no logging calls at all; a caller decides what to
1249 record, and the reasons/messages it is given are already safe."""
1250 source = inspect.getsource(object_stripe)
1251 for banned in ("import logging", "logging.", "print("):
1252 assert banned not in source
1253
1254
1255def test_module_imports_no_third_party():
1256 source = inspect.getsource(object_stripe)
1257 for banned in ("import stripe", "import requests", "from stripe", "from requests"):
1258 assert banned not in source