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

9 downloads

dbbasic-object-server/tests/test_stripe_wiring.py
Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_stripe_wiring.py · 10.5 KB · 249 lines
1"""Stripe as a payment method, not a system of record.
2
3The predecessor's Stripe silo happened because webhook code did bespoke
4things with money. These tests pin the opposite: a verified event writes
5ONE ordinary payments row and then gets out of the way, so the invoice
6flip, the books journal and the receipt all come from the same reaction
7chain a hand-entered payment triggers.
8
9The adversarial half matters more than the happy path here, because this
10endpoint is reachable by anyone on the internet.
11"""
12
13import hashlib
14import hmac
15import json
16import pathlib
17import time
18
19from conftest import stage_collection
20
21import object_execution
22import object_records
23import object_stripe
24import python_object_runtime
25
26REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
27PACKAGES = REPO_ROOT / "packages"
28PAYMENTS_OBJECTS = PACKAGES / "app-payments" / "objects"
29RUNTIME = python_object_runtime.PythonObjectRuntime()
30
31SECRET = "whsec_test_secret"
32KEY = "sk_test_key"
33
34
35def setup_env(tmp_path, monkeypatch, *, configured=True):
36 data_dir = tmp_path / "data"
37 for pkg, name in (("app-invoices", "invoices"), ("app-payments", "payments"),
38 ("app-payments", "refunds"), ("app-settings", "app_settings")):
39 stage_collection(data_dir, pkg, name)
40 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
41 if configured:
42 monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", KEY)
43 monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", SECRET)
44 else:
45 monkeypatch.delenv("DBBASIC_STRIPE_SECRET_KEY", raising=False)
46 monkeypatch.delenv("DBBASIC_STRIPE_WEBHOOK_SECRET", raising=False)
47 object_records.create_collection_record(
48 "invoices",
49 {"id": "inv-1", "number": "INV-1", "customer_name": "Grace Ltd",
50 "status": "sent", "issue_date": "2026-07-01", "due_date": "2026-07-31",
51 "total_cents": "250000", "owner_id": "dan"},
52 base_dir=data_dir)
53 # portal_token is schema read_only so no client can choose a
54 # predictable capability URL; server-side writers use the same narrow
55 # escape hatch the real minting handler does.
56 object_records.update_collection_record(
57 "invoices", "inv-1", {"portal_token": "tok-abcdefghijklmnop"},
58 base_dir=data_dir, actor="test-setup", preserve_read_only=True)
59 return data_dir
60
61
62def signed(payload: bytes, *, secret=SECRET, when=None):
63 ts = when if when is not None else int(time.time())
64 mac = hmac.new(secret.encode(), f"{ts}.".encode() + payload, hashlib.sha256).hexdigest()
65 return f"t={ts},v1={mac}"
66
67
68def event_bytes(*, event_id="evt_1", event_type="checkout.session.completed",
69 invoice_id="inv-1", amount=250000, session_id="cs_1",
70 payment_status="paid", currency="usd"):
71 # payment_status and currency are always present on a real Checkout
72 # Session, and the webhook now refuses to record money without them.
73 return json.dumps({
74 "id": event_id, "type": event_type, "created": 1785000000,
75 "data": {"object": {"id": session_id, "amount_total": amount,
76 "payment_status": payment_status, "currency": currency,
77 "metadata": ({"invoice_id": invoice_id} if invoice_id else {})}},
78 }).encode()
79
80
81def post_webhook(raw: bytes, signature: str):
82 return object_execution.execute_object(
83 RUNTIME,
84 object_execution.ObjectExecutionRequest(
85 "webhook_stripe", method="POST",
86 payload={"_raw_body": raw.decode(),
87 "_headers": {"stripe-signature": signature}}),
88 roots=[PAYMENTS_OBJECTS]).result
89
90
91def payments(data_dir):
92 return object_records.read_collection_records("payments", base_dir=data_dir)
93
94
95# --- the webhook: what it refuses ---------------------------------------------
96
97def test_a_forged_event_records_nothing(tmp_path, monkeypatch):
98 data_dir = setup_env(tmp_path, monkeypatch)
99 raw = event_bytes()
100 forged = post_webhook(raw, signed(raw, secret="whsec_attacker_guess"))
101 assert forged["status"] == 400
102 assert payments(data_dir) == []
103
104 tampered_body = event_bytes(amount=1) # signature was over the original
105 tampered = post_webhook(tampered_body, signed(event_bytes()))
106 assert tampered["status"] == 400
107 assert payments(data_dir) == []
108
109
110def test_a_replayed_old_event_is_refused(tmp_path, monkeypatch):
111 data_dir = setup_env(tmp_path, monkeypatch)
112 raw = event_bytes()
113 stale = post_webhook(raw, signed(raw, when=int(time.time()) - 3600))
114 assert stale["status"] == 400
115 assert payments(data_dir) == []
116
117
118def test_unconfigured_stripe_gives_a_prober_nothing(tmp_path, monkeypatch):
119 setup_env(tmp_path, monkeypatch, configured=False)
120 raw = event_bytes()
121 result = post_webhook(raw, signed(raw))
122 assert result["status"] == 404 # not 500, not "not configured"
123
124
125# --- the webhook: what it does ------------------------------------------------
126
127def test_a_verified_event_writes_one_ordinary_payment(tmp_path, monkeypatch):
128 data_dir = setup_env(tmp_path, monkeypatch)
129 raw = event_bytes()
130 result = post_webhook(raw, signed(raw))
131 assert result["status"] == 200
132 rows = payments(data_dir)
133 assert len(rows) == 1
134 row = rows[0]
135 assert row["invoice_id"] == "inv-1"
136 assert row["amount_cents"] == "250000"
137 # "card" -- the enum names the instrument a bookkeeper reconciles by;
138 # the provider's identity rides in `reference`, not in a second
139 # vocabulary. (The schema enum rejected "stripe" outright: a gate
140 # doing its job on money-path code written minutes earlier.)
141 assert row["method"] == "card"
142 assert row["status"] == "received"
143 assert row["owner_id"] == "dan" # stamped from the invoice, not the event
144 assert "evt_1" in row["reference"] and "cs_1" in row["reference"]
145
146
147def test_redelivery_never_records_money_twice(tmp_path, monkeypatch):
148 """Stripe redelivers for days on any non-2xx, and retries succeed
149 later -- so the SAME event arriving twice must be a no-op."""
150 data_dir = setup_env(tmp_path, monkeypatch)
151 raw = event_bytes()
152 first = post_webhook(raw, signed(raw))
153 again = post_webhook(raw, signed(raw))
154 assert first["status"] == 200 and again["status"] == 200
155 assert again.get("duplicate") == "evt_1"
156 assert len(payments(data_dir)) == 1
157
158
159def test_events_we_do_not_handle_are_acknowledged_not_rejected(tmp_path, monkeypatch):
160 """A 4xx would make Stripe redeliver an event we will never want."""
161 data_dir = setup_env(tmp_path, monkeypatch)
162 raw = event_bytes(event_type="customer.subscription.updated")
163 result = post_webhook(raw, signed(raw))
164 assert result["status"] == 200 and result["ignored"]
165 assert payments(data_dir) == []
166
167
168def test_a_session_we_did_not_mint_books_nothing(tmp_path, monkeypatch):
169 """No invoice_id in metadata means this payment belongs to some other
170 integration on the same Stripe account -- acknowledge, record nothing."""
171 data_dir = setup_env(tmp_path, monkeypatch)
172 raw = event_bytes(invoice_id=None)
173 result = post_webhook(raw, signed(raw))
174 assert result["status"] == 200
175 assert payments(data_dir) == []
176
177
178# --- checkout: the amount is ours to decide -----------------------------------
179
180def checkout(payload, monkeypatch, *, url="https://checkout.stripe.com/pay/x"):
181 calls = []
182
183 def fake_transport(u, data, headers, method):
184 calls.append({"url": u, "data": data})
185 return 200, json.dumps({"id": "cs_new", "url": url}).encode()
186
187 monkeypatch.setattr(object_stripe, "_default_transport", fake_transport, raising=False)
188 original = object_stripe.create_checkout_session
189
190 def patched(config, **kwargs):
191 return original(config, transport=fake_transport, **kwargs)
192
193 monkeypatch.setattr(object_stripe, "create_checkout_session", patched)
194 result = object_execution.execute_object(
195 RUNTIME,
196 object_execution.ObjectExecutionRequest(
197 "action_stripe_checkout", method="POST", payload=payload),
198 roots=[PAYMENTS_OBJECTS]).result
199 return result, calls
200
201
202def test_checkout_charges_the_open_balance_not_a_client_number(tmp_path, monkeypatch):
203 data_dir = setup_env(tmp_path, monkeypatch)
204 object_records.create_collection_record(
205 "app_settings", {"id": "s1", "key": "portal.base_url",
206 "value": "https://books.example"}, base_dir=data_dir)
207 # Half already paid: checkout must ask for the REMAINDER.
208 object_records.create_collection_record(
209 "payments", {"id": "p-part", "invoice_id": "inv-1", "amount_cents": "100000",
210 "method": "card", "received_on": "2026-07-10",
211 "status": "received", "owner_id": "dan"}, base_dir=data_dir)
212 result, calls = checkout({"token": "tok-abcdefghijklmnop", "amount_cents": 1},
213 monkeypatch)
214 assert result["status"] == 200
215 assert result["amount_cents"] == 150000 # NOT the client's 1
216 assert result["url"].startswith("https://checkout.stripe.com/")
217
218
219def test_checkout_refuses_bad_tokens_paid_and_void_invoices(tmp_path, monkeypatch):
220 data_dir = setup_env(tmp_path, monkeypatch)
221 object_records.create_collection_record(
222 "app_settings", {"id": "s1", "key": "portal.base_url",
223 "value": "https://books.example"}, base_dir=data_dir)
224 missing, _ = checkout({"token": "not-a-real-token"}, monkeypatch)
225 assert missing["status"] == 404 # never "bad token"
226
227 object_records.create_collection_record(
228 "payments", {"id": "p-full", "invoice_id": "inv-1", "amount_cents": "250000",
229 "method": "card", "received_on": "2026-07-10",
230 "status": "received", "owner_id": "dan"}, base_dir=data_dir)
231 paid, calls = checkout({"token": "tok-abcdefghijklmnop"}, monkeypatch)
232 assert paid["status"] == 409 and calls == [] # no Stripe call at all
233
234
235def test_checkout_without_stripe_configured_says_so_plainly(tmp_path, monkeypatch):
236 setup_env(tmp_path, monkeypatch, configured=False)
237 result, calls = checkout({"token": "tok-abcdefghijklmnop"}, monkeypatch)
238 assert result["status"] == 409
239 assert "not configured" in result["error"]
240 assert calls == []
241
242
243def test_checkout_refuses_to_guess_a_return_host(tmp_path, monkeypatch):
244 """Stripe needs absolute return URLs; guessing one would send a paying
245 customer to a hostname this server does not control."""
246 setup_env(tmp_path, monkeypatch)
247 result, calls = checkout({"token": "tok-abcdefghijklmnop"}, monkeypatch)
248 assert result["status"] == 409 and "portal.base_url" in result["error"]
249 assert calls == []