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_stripe_wiring.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_stripe_wiring.py · 10.2 KB · 245 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 return json.dumps({
71 "id": event_id, "type": event_type, "created": 1785000000,
72 "data": {"object": {"id": session_id, "amount_total": amount,
73 "metadata": ({"invoice_id": invoice_id} if invoice_id else {})}},
74 }).encode()
75
76
77def post_webhook(raw: bytes, signature: str):
78 return object_execution.execute_object(
79 RUNTIME,
80 object_execution.ObjectExecutionRequest(
81 "webhook_stripe", method="POST",
82 payload={"_raw_body": raw.decode(),
83 "_headers": {"stripe-signature": signature}}),
84 roots=[PAYMENTS_OBJECTS]).result
85
86
87def payments(data_dir):
88 return object_records.read_collection_records("payments", base_dir=data_dir)
89
90
91# --- the webhook: what it refuses ---------------------------------------------
92
93def test_a_forged_event_records_nothing(tmp_path, monkeypatch):
94 data_dir = setup_env(tmp_path, monkeypatch)
95 raw = event_bytes()
96 forged = post_webhook(raw, signed(raw, secret="whsec_attacker_guess"))
97 assert forged["status"] == 400
98 assert payments(data_dir) == []
99
100 tampered_body = event_bytes(amount=1) # signature was over the original
101 tampered = post_webhook(tampered_body, signed(event_bytes()))
102 assert tampered["status"] == 400
103 assert payments(data_dir) == []
104
105
106def test_a_replayed_old_event_is_refused(tmp_path, monkeypatch):
107 data_dir = setup_env(tmp_path, monkeypatch)
108 raw = event_bytes()
109 stale = post_webhook(raw, signed(raw, when=int(time.time()) - 3600))
110 assert stale["status"] == 400
111 assert payments(data_dir) == []
112
113
114def test_unconfigured_stripe_gives_a_prober_nothing(tmp_path, monkeypatch):
115 setup_env(tmp_path, monkeypatch, configured=False)
116 raw = event_bytes()
117 result = post_webhook(raw, signed(raw))
118 assert result["status"] == 404 # not 500, not "not configured"
119
120
121# --- the webhook: what it does ------------------------------------------------
122
123def test_a_verified_event_writes_one_ordinary_payment(tmp_path, monkeypatch):
124 data_dir = setup_env(tmp_path, monkeypatch)
125 raw = event_bytes()
126 result = post_webhook(raw, signed(raw))
127 assert result["status"] == 200
128 rows = payments(data_dir)
129 assert len(rows) == 1
130 row = rows[0]
131 assert row["invoice_id"] == "inv-1"
132 assert row["amount_cents"] == "250000"
133 # "card" -- the enum names the instrument a bookkeeper reconciles by;
134 # the provider's identity rides in `reference`, not in a second
135 # vocabulary. (The schema enum rejected "stripe" outright: a gate
136 # doing its job on money-path code written minutes earlier.)
137 assert row["method"] == "card"
138 assert row["status"] == "received"
139 assert row["owner_id"] == "dan" # stamped from the invoice, not the event
140 assert "evt_1" in row["reference"] and "cs_1" in row["reference"]
141
142
143def test_redelivery_never_records_money_twice(tmp_path, monkeypatch):
144 """Stripe redelivers for days on any non-2xx, and retries succeed
145 later -- so the SAME event arriving twice must be a no-op."""
146 data_dir = setup_env(tmp_path, monkeypatch)
147 raw = event_bytes()
148 first = post_webhook(raw, signed(raw))
149 again = post_webhook(raw, signed(raw))
150 assert first["status"] == 200 and again["status"] == 200
151 assert again.get("duplicate") == "evt_1"
152 assert len(payments(data_dir)) == 1
153
154
155def test_events_we_do_not_handle_are_acknowledged_not_rejected(tmp_path, monkeypatch):
156 """A 4xx would make Stripe redeliver an event we will never want."""
157 data_dir = setup_env(tmp_path, monkeypatch)
158 raw = event_bytes(event_type="customer.subscription.updated")
159 result = post_webhook(raw, signed(raw))
160 assert result["status"] == 200 and result["ignored"]
161 assert payments(data_dir) == []
162
163
164def test_a_session_we_did_not_mint_books_nothing(tmp_path, monkeypatch):
165 """No invoice_id in metadata means this payment belongs to some other
166 integration on the same Stripe account -- acknowledge, record nothing."""
167 data_dir = setup_env(tmp_path, monkeypatch)
168 raw = event_bytes(invoice_id=None)
169 result = post_webhook(raw, signed(raw))
170 assert result["status"] == 200
171 assert payments(data_dir) == []
172
173
174# --- checkout: the amount is ours to decide -----------------------------------
175
176def checkout(payload, monkeypatch, *, url="https://checkout.stripe.com/pay/x"):
177 calls = []
178
179 def fake_transport(u, data, headers, method):
180 calls.append({"url": u, "data": data})
181 return 200, json.dumps({"id": "cs_new", "url": url}).encode()
182
183 monkeypatch.setattr(object_stripe, "_default_transport", fake_transport, raising=False)
184 original = object_stripe.create_checkout_session
185
186 def patched(config, **kwargs):
187 return original(config, transport=fake_transport, **kwargs)
188
189 monkeypatch.setattr(object_stripe, "create_checkout_session", patched)
190 result = object_execution.execute_object(
191 RUNTIME,
192 object_execution.ObjectExecutionRequest(
193 "action_stripe_checkout", method="POST", payload=payload),
194 roots=[PAYMENTS_OBJECTS]).result
195 return result, calls
196
197
198def test_checkout_charges_the_open_balance_not_a_client_number(tmp_path, monkeypatch):
199 data_dir = setup_env(tmp_path, monkeypatch)
200 object_records.create_collection_record(
201 "app_settings", {"id": "s1", "key": "portal.base_url",
202 "value": "https://books.example"}, base_dir=data_dir)
203 # Half already paid: checkout must ask for the REMAINDER.
204 object_records.create_collection_record(
205 "payments", {"id": "p-part", "invoice_id": "inv-1", "amount_cents": "100000",
206 "method": "card", "received_on": "2026-07-10",
207 "status": "received", "owner_id": "dan"}, base_dir=data_dir)
208 result, calls = checkout({"token": "tok-abcdefghijklmnop", "amount_cents": 1},
209 monkeypatch)
210 assert result["status"] == 200
211 assert result["amount_cents"] == 150000 # NOT the client's 1
212 assert result["url"].startswith("https://checkout.stripe.com/")
213
214
215def test_checkout_refuses_bad_tokens_paid_and_void_invoices(tmp_path, monkeypatch):
216 data_dir = setup_env(tmp_path, monkeypatch)
217 object_records.create_collection_record(
218 "app_settings", {"id": "s1", "key": "portal.base_url",
219 "value": "https://books.example"}, base_dir=data_dir)
220 missing, _ = checkout({"token": "not-a-real-token"}, monkeypatch)
221 assert missing["status"] == 404 # never "bad token"
222
223 object_records.create_collection_record(
224 "payments", {"id": "p-full", "invoice_id": "inv-1", "amount_cents": "250000",
225 "method": "card", "received_on": "2026-07-10",
226 "status": "received", "owner_id": "dan"}, base_dir=data_dir)
227 paid, calls = checkout({"token": "tok-abcdefghijklmnop"}, monkeypatch)
228 assert paid["status"] == 409 and calls == [] # no Stripe call at all
229
230
231def test_checkout_without_stripe_configured_says_so_plainly(tmp_path, monkeypatch):
232 setup_env(tmp_path, monkeypatch, configured=False)
233 result, calls = checkout({"token": "tok-abcdefghijklmnop"}, monkeypatch)
234 assert result["status"] == 409
235 assert "not configured" in result["error"]
236 assert calls == []
237
238
239def test_checkout_refuses_to_guess_a_return_host(tmp_path, monkeypatch):
240 """Stripe needs absolute return URLs; guessing one would send a paying
241 customer to a hostname this server does not control."""
242 setup_env(tmp_path, monkeypatch)
243 result, calls = checkout({"token": "tok-abcdefghijklmnop"}, monkeypatch)
244 assert result["status"] == 409 and "portal.base_url" in result["error"]
245 assert calls == []