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_money_gates_payments_refunds.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_money_gates_payments_refunds.py · 21.4 KB · 457 lines
1"""Payments and refunds after they are recorded: what is frozen, for whom,
2and that the legitimate paths still work.
3
4tests/test_findings_money_gates.py holds the reproductions (a payment
5raised past its invoice by an edit, a refund deleted and issued again...).
6Those say what must be refused. This file is the other half of the same
7change: the position hook_payments and hook_refunds now take, stated as
8behaviour, so that loosening or tightening it is a visible edit here.
9
10The position (conservative, because the owner had not decided otherwise):
11
12 * somebody who is not an admin may change `status` and `notes` on a
13 payment and `reason` on a refund, and nothing else; and may delete
14 neither;
15 * an admin may edit and delete both, through the same invariants a
16 create faces;
17 * trusted server-side writers (the Stripe webhook, checkout,
18 resolve_bank_line) go through object_records and are not gated by
19 the hooks -- only by the schema.
20
21Driven like the findings file: the real ASGI app, real packages, permission
22enforcement on, a signed-in non-admin (`ann`); `admin` is the admin token.
23"""
24
25import sys
26
27import pytest
28
29import object_handlers
30import object_records
31from test_findings_money_gates import ( # noqa: F401 (fresh_handler_index is autouse)
32 build_site, failing_reads, fresh_handler_index, must, ok, pay, payments_site, refund,
33)
34
35
36def hook_refused(result, status=409):
37 got, body = result
38 assert got == status and body.get("code") == "hook_rejected", (got, body)
39 return body["error"]
40
41
42def check_refused(result, status=409):
43 """The ceiling and the ledger invariants are a `locked_checks` entry now,
44 decided inside the write lock: 409 check_refused with the sentence the
45 hook used to give a moment earlier as 409 hook_rejected."""
46 got, body = result
47 assert got == status and body.get("code") == "check_refused", (got, body)
48 return body["error"]
49
50
51def forbidden(result):
52 """Deleting recorded money is a permission rule now (no delete grant and
53 the owner fallback denied), not a hook refusal."""
54 got, body = result
55 assert got == 403 and body.get("code") == "forbidden", (got, body)
56
57
58def refused_as_unreadable(result):
59 """The hook answers 503 for a read it could not make, and the server
60 relays it (object_server._apply_before_write_hook), so the client sees
61 something to retry rather than a bad request."""
62 got, body = result
63 assert got == 503 and body.get("code") == "hook_rejected", (got, body)
64 assert "could not be read" in body["error"], body
65
66
67# --- payments: the person who recorded it --------------------------------------
68
69
70def test_the_owner_can_still_bounce_a_payment_and_annotate_it(tmp_path, monkeypatch):
71 """The two things a payment's owner legitimately does to it afterwards:
72 a cheque bounces (the schema's one transition), and a note is added."""
73 site = payments_site(tmp_path, monkeypatch)
74 ok(pay(site, "p1", 4000), "payment")
75
76 ok(site.put("payments", "p1", "ann", {"notes": "cheque 1042, second presentation"}), "note")
77 ok(site.put("payments", "p1", "ann", {"status": "bounced"}), "bounce")
78
79 stored = site.get("payments", "p1")
80 assert (stored["status"], stored["notes"]) == ("bounced", "cheque 1042, second presentation")
81 assert stored["amount_cents"] == "4000"
82 assert site.get("invoices", "inv1")["payments_received_cents"] == "0"
83
84
85@pytest.mark.parametrize("change", [
86 {"amount_cents": "3999"}, # lowering is an edit too: that is a refund
87 {"amount_cents": "-5"},
88 {"invoice_id": "inv2"},
89 {"received_on": "2026-01-01"},
90 {"method": "cash"},
91 {"reference": "something else"},
92], ids=lambda change: next(iter(change)) + "=" + next(iter(change.values())))
93def test_the_owner_cannot_edit_what_a_payment_records(tmp_path, monkeypatch, change):
94 site = payments_site(tmp_path, monkeypatch)
95 ok(site.post("invoices", "ann", {"id": "inv2", "number": "INV-2", "customer_name": "Other"}),
96 "second invoice")
97 ok(pay(site, "p1", 4000), "payment")
98 before = site.get("payments", "p1")
99
100 error = hook_refused(site.put("payments", "p1", "ann", change))
101
102 assert "not edited" in error and next(iter(change)) in error
103 assert site.get("payments", "p1") == before
104
105
106def test_a_form_that_posts_every_field_back_unchanged_is_not_an_edit(tmp_path, monkeypatch):
107 """The generated form submits everything it shows. Sending the amount
108 back as it is must not read as an attempt to change it -- only the
109 note changed."""
110 site = payments_site(tmp_path, monkeypatch)
111 ok(pay(site, "p1", 4000), "payment")
112 stored = site.get("payments", "p1")
113
114 ok(site.put("payments", "p1", "ann", {
115 "invoice_id": stored["invoice_id"], "amount_cents": stored["amount_cents"],
116 "method": stored["method"], "received_on": stored["received_on"],
117 "reference": stored["reference"], "notes": "paid at the counter"}), "form post")
118
119 assert site.get("payments", "p1")["notes"] == "paid at the counter"
120
121
122def test_the_owner_cannot_delete_a_payment_even_one_with_no_refunds(tmp_path, monkeypatch):
123 site = payments_site(tmp_path, monkeypatch)
124 ok(pay(site, "p1", 4000), "payment")
125
126 forbidden(site.delete("payments", "p1", "ann"))
127
128 assert site.exists("payments", "p1")
129 assert site.get("invoices", "inv1")["payments_received_cents"] == "4000"
130
131
132def test_the_freeze_holds_when_overpayment_is_allowed(tmp_path, monkeypatch):
133 """payments.overpayment_policy=allow lifts the CEILING (shops that keep
134 customer credit). It says nothing about editing recorded money."""
135 site = payments_site(tmp_path, monkeypatch)
136 ok(site.post("app_settings", "admin", {"id": "s1", "key": "payments.overpayment_policy",
137 "value": "allow"}), "policy")
138 ok(pay(site, "p1", 15000), "overpayment under the allow policy")
139
140 hook_refused(site.put("payments", "p1", "ann", {"amount_cents": "20000"}))
141 forbidden(site.delete("payments", "p1", "ann"))
142 assert site.get("payments", "p1")["amount_cents"] == "15000"
143
144
145# --- payments: an admin ----------------------------------------------------------
146
147
148def test_an_admin_can_correct_a_payment_amount_within_the_same_ceiling(tmp_path, monkeypatch):
149 """Somebody has to be able to repair a mistyped ledger. An admin's edit
150 is allowed -- and faces the same arithmetic as a create, counting every
151 OTHER payment on the invoice."""
152 site = payments_site(tmp_path, monkeypatch)
153 ok(pay(site, "p1", 4000), "first payment")
154 ok(pay(site, "p2", 1000), "second payment")
155
156 ok(site.put("payments", "p1", "admin", {"amount_cents": "9000"}), "raise to the ceiling")
157 assert site.get("invoices", "inv1")["balance_due_cents"] == "0"
158
159 error = check_refused(site.put("payments", "p1", "admin", {"amount_cents": "9001"}))
160 assert "remaining balance of 9000" in error
161 got, body = site.put("payments", "p1", "admin", {"amount_cents": "0"})
162 assert got == 400 and "below min" in body["error"], (got, body)
163 assert site.get("payments", "p1")["amount_cents"] == "9000"
164
165
166def test_an_admin_with_a_session_rather_than_the_token_is_an_admin_too(tmp_path, monkeypatch):
167 site = build_site(tmp_path, monkeypatch,
168 ["app-views", "app-settings", "app-invoices", "app-payments"],
169 users=("ann", "root"), roles={"ann": ["manager"], "root": ["admin"]},
170 handlers=True)
171 ok(site.post("invoices", "ann", {"id": "inv1", "number": "INV-1", "customer_name": "Acme"}),
172 "invoice")
173 ok(site.post("invoice_lines", "ann", {"id": "l1", "invoice_id": "inv1", "description": "work",
174 "quantity": "1", "unit_price_cents": "10000"}), "line")
175 ok(pay(site, "p1", 4000), "payment")
176
177 ok(site.put("payments", "p1", "root", {"amount_cents": "4500"}), "admin session edit")
178 ok(site.delete("payments", "p1", "root"), "admin session delete")
179 assert not site.exists("payments", "p1")
180
181
182def test_an_admin_cannot_lower_a_payment_below_its_refunds_or_move_it_from_under_them(
183 tmp_path, monkeypatch):
184 site = payments_site(tmp_path, monkeypatch)
185 ok(site.post("invoices", "ann", {"id": "inv2", "number": "INV-2", "customer_name": "Other",
186 "total_cents": "10000"}), "second invoice")
187 ok(pay(site, "p1", 10000), "payment")
188 ok(refund(site, "r1", "p1", 4000), "refund")
189
190 error = check_refused(site.put("payments", "p1", "admin", {"amount_cents": "3999"}))
191 assert "4000 cents refunded" in error
192 ok(site.put("payments", "p1", "admin", {"amount_cents": "4000"}), "down to what was refunded")
193
194 error = check_refused(site.put("payments", "p1", "admin", {"invoice_id": "inv2"}))
195 assert "has refunds" in error
196 assert site.get("payments", "p1")["invoice_id"] == "inv1"
197
198
199def test_an_admin_deletes_a_refunded_payment_only_after_its_refunds(tmp_path, monkeypatch):
200 """Two deliberate acts, each attributed in the change log, rather than
201 one that leaves a refund pointing at nothing."""
202 site = payments_site(tmp_path, monkeypatch)
203 ok(pay(site, "p1", 10000), "payment")
204 ok(refund(site, "r1", "p1", 4000), "refund")
205
206 error = check_refused(site.delete("payments", "p1", "admin"))
207 assert "delete the refunds first" in error and site.exists("payments", "p1")
208
209 ok(site.delete("refunds", "r1", "admin"), "admin deletes the refund")
210 ok(site.delete("payments", "p1", "admin"), "then the payment")
211 invoice = site.get("invoices", "inv1")
212 assert (invoice["payments_received_cents"], invoice["refunded_cents"]) == ("0", "0")
213
214
215# --- payments: trusted writers ---------------------------------------------------
216
217
218def test_storage_level_writers_still_record_and_bounce_payments(tmp_path, monkeypatch):
219 """The Stripe webhook and checkout create payments, and
220 resolve_bank_line bounces one, through object_records: no hook, by
221 design. The freeze must not have reached them."""
222 site = payments_site(tmp_path, monkeypatch)
223 created = object_records.create_collection_record(
224 "payments", {"id": "p-stripe", "invoice_id": "inv1", "amount_cents": "10000",
225 "method": "card", "received_on": "2026-07-24", "status": "received",
226 "reference": "evt_1 cs_1", "owner_id": "ann"},
227 base_dir=site.data, actor="webhook_stripe")
228 assert created["amount_cents"] == "10000"
229
230 bounced = object_records.update_collection_record(
231 "payments", "p-stripe", {"status": "bounced"}, base_dir=site.data,
232 actor="action_resolve_bank_line")
233 assert bounced["status"] == "bounced"
234
235
236@pytest.mark.parametrize("collection,record", [
237 ("payments", {"id": "p0", "invoice_id": "inv1", "amount_cents": "0",
238 "received_on": "2026-07-24", "owner_id": "ann"}),
239 ("payments", {"id": "p0", "invoice_id": "inv1", "amount_cents": "-500",
240 "received_on": "2026-07-24", "owner_id": "ann"}),
241 ("refunds", {"id": "r0", "payment_id": "p1", "amount_cents": "-500",
242 "refunded_on": "2026-07-24", "owner_id": "ann"}),
243], ids=["zero payment", "negative payment", "negative refund"])
244def test_no_writer_can_store_a_non_positive_amount(tmp_path, monkeypatch, collection, record):
245 """The hook refuses these over HTTP. The schema's validation.min says
246 the same thing to the writers that never reach a hook."""
247 site = payments_site(tmp_path, monkeypatch)
248 ok(pay(site, "p1", 1000), "payment")
249
250 with pytest.raises(object_records.InvalidRecordPayloadError, match="below min"):
251 object_records.create_collection_record(collection, record, base_dir=site.data,
252 actor="some_handler")
253 assert not site.exists(collection, record["id"])
254
255
256# --- the ceiling -----------------------------------------------------------------
257
258
259def test_an_invoice_taxed_on_the_document_can_be_paid_in_full(tmp_path, monkeypatch):
260 """Checkout computes tax once over the whole sale and stamps it on the
261 DOCUMENT; no line states a rate. The lines alone come to 2000 and the
262 customer was quoted 2116. A ceiling of "what the lines sum to" would
263 refuse the last 116 of a price already agreed."""
264 site = payments_site(tmp_path, monkeypatch)
265 object_records.create_collection_record(
266 "invoices", {"id": "inv2", "number": "INV-2", "customer_name": "Shopper",
267 "subtotal_cents": "2000", "tax_cents": "116", "total_cents": "2116",
268 "owner_id": "ann"}, base_dir=site.data, actor="action_checkout")
269 for line_id, price in (("g1", "1400"), ("post", "600")):
270 object_records.create_collection_record(
271 "invoice_lines", {"id": line_id, "invoice_id": "inv2", "description": line_id,
272 "quantity": "1", "unit_price_cents": price, "owner_id": "ann"},
273 base_dir=site.data, actor="action_checkout")
274
275 check_refused(pay(site, "p0", 2117, invoice_id="inv2"))
276 ok(pay(site, "p1", 2116, invoice_id="inv2"), "the quoted total")
277
278
279def test_the_ceiling_takes_no_side_between_line_tax_and_document_tax(tmp_path, monkeypatch):
280 """Postage states a rate (15% of 600 = 90) while the document carries
281 the tax the customer was quoted (300). Which is authoritative is an
282 open decision; until it is made the gate allows the larger, bounded by
283 the stamped total, so it cannot refuse the agreed 2300."""
284 site = payments_site(tmp_path, monkeypatch)
285 object_records.create_collection_record(
286 "invoices", {"id": "inv2", "number": "INV-2", "customer_name": "Shopper",
287 "subtotal_cents": "2000", "tax_cents": "300", "total_cents": "2300",
288 "owner_id": "ann"}, base_dir=site.data, actor="action_checkout")
289 for line_id, price, rate in (("g1", "1400", ""), ("post", "600", "1500")):
290 object_records.create_collection_record(
291 "invoice_lines", {"id": line_id, "invoice_id": "inv2", "description": line_id,
292 "quantity": "1", "unit_price_cents": price, "tax_rate_bps": rate,
293 "owner_id": "ann"},
294 base_dir=site.data, actor="action_checkout")
295
296 check_refused(pay(site, "p0", 2301, invoice_id="inv2"))
297 ok(pay(site, "p1", 2300, invoice_id="inv2"), "the quoted total")
298
299
300def test_an_invoice_with_no_lines_is_capped_by_its_stamped_total(tmp_path, monkeypatch):
301 """With no lines there is nothing to sum: the total is the only
302 statement of what is owed (a billing-run or imported invoice)."""
303 site = payments_site(tmp_path, monkeypatch)
304 object_records.create_collection_record(
305 "invoices", {"id": "inv2", "number": "INV-2", "customer_name": "Subscriber",
306 "total_cents": "5000", "owner_id": "ann"},
307 base_dir=site.data, actor="billing_runner")
308
309 check_refused(pay(site, "p0", 5001, invoice_id="inv2"))
310 ok(pay(site, "p1", 5000, invoice_id="inv2"), "the stamped total")
311
312
313def test_a_stamped_total_lower_than_the_lines_still_bounds_the_payment(tmp_path, monkeypatch):
314 """The other direction of stale. The lines say 10000 and the stamp says
315 6000 (a line was raised while the handler was not running). The gate
316 takes the SMALLER: it never authorises more than either the document or
317 its lines say is owed."""
318 site = payments_site(tmp_path, monkeypatch)
319 monkeypatch.delenv(object_handlers.HANDLERS_ENABLED_ENV)
320 ok(site.put("invoices", "inv1", "ann", {"total_cents": "6000"}), "stale-low total")
321
322 error = check_refused(pay(site, "p0", 6001))
323 assert "remaining balance of 6000" in error
324 ok(pay(site, "p1", 6000), "up to the stamped total")
325
326
327@pytest.mark.parametrize("collection", ["invoice_lines", "payments", "refunds"])
328def test_the_overpayment_gate_refuses_when_one_of_its_reads_fails(tmp_path, monkeypatch, collection):
329 """Each read the ceiling depends on: unreadable is a 503 and nothing is
330 recorded, never 'no lines', 'nothing received' or 'nothing refunded'.
331 The ceiling is decided in LOCKED_CHECK (inside the write lock), so that
332 is where the simulated failure must land; the answer is the platform's
333 503 check_unavailable."""
334 site = payments_site(tmp_path, monkeypatch)
335 ok(pay(site, "p1", 4000), "payment")
336
337 real = object_records.read_collection_records_where
338 fired = []
339
340 def read(name, *args, **kwargs):
341 frame = sys._getframe(1)
342 if name == collection and frame.f_code.co_filename.endswith("hook/payments.py"):
343 fired.append(frame.f_code.co_name)
344 raise OSError(f"simulated: {collection} is unreadable")
345 return real(name, *args, **kwargs)
346
347 object_records.read_collection_records_where = read
348 try:
349 got, body = pay(site, "p2", 1000)
350 finally:
351 object_records.read_collection_records_where = real
352 must(fired, f"the simulated failure of {collection} never fired in the check")
353
354 assert got == 503 and body.get("code") == "check_unavailable", (got, body)
355 assert not site.exists("payments", "p2")
356
357
358# --- refunds ---------------------------------------------------------------------
359
360
361def test_the_owner_can_reword_a_refund_reason_and_nothing_else(tmp_path, monkeypatch):
362 site = payments_site(tmp_path, monkeypatch)
363 ok(site.post("invoices", "ann", {"id": "inv2", "number": "INV-2", "customer_name": "Other"}),
364 "second invoice")
365 ok(pay(site, "p1", 10000), "payment")
366 ok(refund(site, "r1", "p1", 4000), "refund")
367
368 ok(site.put("refunds", "r1", "ann", {"reason": "damaged in transit"}), "reason")
369 assert site.get("refunds", "r1")["reason"] == "damaged in transit"
370
371 before = site.get("refunds", "r1")
372 for change in ({"amount_cents": "3999"}, {"amount_cents": "6000"}, {"payment_id": "p9"},
373 {"invoice_id": "inv2"}, {"refunded_on": "2026-01-01"}):
374 error = hook_refused(site.put("refunds", "r1", "ann", change))
375 assert "not edited" in error and next(iter(change)) in error
376 assert site.get("refunds", "r1") == before
377
378
379def test_the_owner_cannot_delete_a_refund(tmp_path, monkeypatch):
380 site = payments_site(tmp_path, monkeypatch)
381 ok(pay(site, "p1", 10000), "payment")
382 ok(refund(site, "r1", "p1", 4000), "refund")
383
384 forbidden(site.delete("refunds", "r1", "ann"))
385
386 assert site.exists("refunds", "r1")
387 assert site.get("invoices", "inv1")["refunded_cents"] == "4000"
388
389
390def test_an_admin_can_correct_a_refund_within_the_payment(tmp_path, monkeypatch):
391 """The same gate as a create, counting every OTHER refund of the
392 payment."""
393 site = payments_site(tmp_path, monkeypatch)
394 ok(pay(site, "p1", 10000), "payment")
395 ok(refund(site, "r1", "p1", 4000), "first refund")
396 ok(refund(site, "r2", "p1", 1000), "second refund")
397
398 ok(site.put("refunds", "r1", "admin", {"amount_cents": "9000"}), "raise to the headroom")
399 error = hook_refused(site.put("refunds", "r1", "admin", {"amount_cents": "9001"}))
400 assert "exceeds the refundable 9000" in error
401 got, body = site.put("refunds", "r1", "admin", {"amount_cents": "-1"})
402 assert got == 400 and "below min" in body["error"], (got, body)
403 ok(site.put("refunds", "r1", "admin", {"amount_cents": "2000"}), "lower")
404
405 assert site.get("refunds", "r1")["amount_cents"] == "2000"
406 assert site.get("payments", "p1")["refunded_cents"] == "3000"
407
408
409def test_an_admin_repointing_a_refund_carries_the_new_payments_invoice(tmp_path, monkeypatch):
410 """invoice_id always comes from the payment. Moving a refund to another
411 payment re-stamps it; setting invoice_id to something the payment does
412 not say is refused rather than silently corrected."""
413 site = payments_site(tmp_path, monkeypatch)
414 ok(site.post("invoices", "ann", {"id": "inv2", "number": "INV-2", "customer_name": "Other",
415 "total_cents": "8000"}), "second invoice")
416 ok(pay(site, "p1", 10000), "payment on inv1")
417 ok(pay(site, "p2", 8000, invoice_id="inv2"), "payment on inv2")
418 ok(refund(site, "r1", "p1", 4000), "refund of p1")
419
420 error = hook_refused(site.put("refunds", "r1", "admin", {"invoice_id": "inv2"}))
421 assert "its payment's invoice" in error
422
423 ok(site.put("refunds", "r1", "admin", {"payment_id": "p2"}), "re-point")
424 stored = site.get("refunds", "r1")
425 assert (stored["payment_id"], stored["invoice_id"]) == ("p2", "inv2")
426 assert site.get("invoices", "inv1")["refunded_cents"] == "0"
427 assert site.get("invoices", "inv2")["refunded_cents"] == "4000"
428
429 error = hook_refused(site.put("refunds", "r1", "admin", {"payment_id": "p1",
430 "amount_cents": "10001"}))
431 assert "exceeds the refundable 10000" in error
432
433
434def test_an_admin_deleting_a_refund_reopens_its_headroom_deliberately(tmp_path, monkeypatch):
435 """The thing the owner can no longer do by accident, an admin can do on
436 purpose -- and the change log says who."""
437 site = payments_site(tmp_path, monkeypatch)
438 ok(pay(site, "p1", 10000), "payment")
439 ok(refund(site, "r1", "p1", 10000), "full refund")
440
441 ok(site.delete("refunds", "r1", "admin"), "admin delete")
442 ok(refund(site, "r2", "p1", 10000), "refund again")
443 assert [row["id"] for row in site.rows("refunds")] == ["r2"]
444
445
446def test_the_refund_gate_refuses_when_its_read_fails(tmp_path, monkeypatch):
447 """Unreadable refund history is a 503, never 'nothing refunded yet'."""
448 site = payments_site(tmp_path, monkeypatch)
449 ok(pay(site, "p1", 10000), "payment")
450 ok(refund(site, "r1", "p1", 4000), "refund")
451
452 with failing_reads("refunds", "hook/refunds.py") as fired:
453 result = refund(site, "r2", "p1", 1000)
454 must(fired, "the simulated failure never fired in the hook")
455
456 refused_as_unreadable(result)
457 assert not site.exists("refunds", "r2")