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_field_findings.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_field_findings.py · 22.5 KB · 466 lines
1"""Findings from simulations run with permission enforcement on: ordinary
2signed-in users could write money and access fields on rows they own or on
3shared rows.
4
5Every test here calls the app the way such a user would -- the real ASGI app
6in this process, enforcement ON, scripts/try_package.py's Sandbox -- because
7the in-process tests call the reactions that legitimately write these fields
8and so could never see who else could. The fixes are declarations (field
9permissions, rules, retractions); the tests assert both halves: the person
10who must not is refused, and the staff role or reaction who must still can.
11"""
12
13from __future__ import annotations
14
15import json
16from pathlib import Path
17
18import pytest
19
20import object_ids
21import object_records
22from scripts.try_package import Sandbox
23
24ROOT = Path(__file__).resolve().parents[1]
25
26
27def _fragment(package):
28 return json.loads((ROOT / "packages" / package / "permissions/rules.json").read_text())
29
30
31def _retracted(package):
32 return [{k: v for k, v in rule.items() if k != "reason"}
33 for rule in _fragment(package).get("retracted", [])]
34
35
36# -- 1. app-invoices: the payer owns the invoice ------------------------------
37
38@pytest.fixture()
39def billing_desk():
40 with Sandbox(["app-invoices"]) as box:
41 box.add_user("cust")
42 box.add_user("maria", roles=["manager"])
43 status, body = box.call("admin", "POST", "/collections/invoices/records",
44 {"number": "INV-1", "customer_name": "Cust",
45 "status": "sent", "owner_id": "cust"})
46 assert status == 201
47 invoice = body["record"]["id"]
48 status, body = box.call("admin", "POST", "/collections/invoice_lines/records",
49 {"invoice_id": invoice, "description": "work",
50 "quantity": "1", "unit_price_cents": "5000",
51 "owner_id": "cust"})
52 assert status == 201
53 box.invoice, box.line = invoice, body["record"]["id"]
54 yield box
55
56
57def test_the_customer_who_owns_an_invoice_cannot_mark_it_paid(billing_desk):
58 """Checkout and the subscription biller make the CUSTOMER the invoice's
59 owner. PUT status=paid answered 200: dunning stopped with the balance
60 unchanged, and app-shop's fulfillment ships on status=paid."""
61 box = billing_desk
62 for change in ({"status": "paid"}, {"status": "void"}, {"total_cents": "0"},
63 {"due_date": "2099-01-01"}, {"doc_type": "quote"},
64 {"dunning_level": "9"}, {"paid_at": "2026-01-01T00:00:00Z"}):
65 status, body = box.call("cust", "PUT",
66 f"/collections/invoices/records/{box.invoice}", change)
67 assert status == 403, (change, body)
68 status, body = box.call("admin", "GET", f"/collections/invoices/records/{box.invoice}")
69 assert body["record"]["status"] == "sent"
70
71
72def test_the_customer_cannot_reprice_or_delete_what_they_were_billed(billing_desk):
73 """A line's price restates the bill once the totals handler runs; deleting
74 the invoice or a line erases it."""
75 box = billing_desk
76 status, _ = box.call("cust", "PUT", f"/collections/invoice_lines/records/{box.line}",
77 {"unit_price_cents": "0"})
78 assert status == 403
79 status, _ = box.call("cust", "POST", "/collections/invoice_lines/records",
80 {"invoice_id": box.invoice, "description": "credit",
81 "quantity": "1", "unit_price_cents": "-5000"})
82 assert status == 403
83 status, _ = box.call("cust", "DELETE", f"/collections/invoice_lines/records/{box.line}")
84 assert status == 403
85 status, _ = box.call("cust", "DELETE", f"/collections/invoices/records/{box.invoice}")
86 assert status == 403
87 status, body = box.call("cust", "GET", f"/collections/invoices/records/{box.invoice}")
88 assert status == 200 and body["record"]["status"] == "sent"
89
90
91def test_billing_staff_still_move_a_customers_invoice(billing_desk):
92 """The staff role is the one that sends, settles and voids, on invoices
93 owned by the customer (which the old owner_id transition guards refused)."""
94 box = billing_desk
95 status, body = box.call("maria", "PUT",
96 f"/collections/invoices/records/{box.invoice}",
97 {"status": "paid"})
98 assert status == 200 and body["record"]["status"] == "paid", body
99 # Repricing a line of an issued bill in place is no longer anyone's
100 # (object_corrections, the Corner Cup finding): the line is voided with
101 # a reason and the right one added, or a paid bill is corrected by a
102 # new record citing the line.
103 status, body = box.call("maria", "PUT",
104 f"/collections/invoice_lines/records/{box.line}",
105 {"unit_price_cents": "4500"})
106 assert status == 409 and body["check"] == "settled_line", body
107
108
109def test_the_withdrawn_invoice_grants_are_retracted():
110 retracted = _retracted("app-invoices")
111 for collection in ("invoices", "invoice_lines"):
112 assert {"effect": "allow", "principal": "registered",
113 "actions": ["create", "read", "update", "delete"],
114 "collection": collection,
115 "row_filter": {"owner_id": "$user_id"}} in retracted
116
117
118# -- 2. app-payments: refunds are staff work ----------------------------------
119
120@pytest.fixture()
121def paid_customer():
122 with Sandbox(["app-payments"]) as box:
123 box.add_user("cust")
124 box.add_user("maria", roles=["manager"])
125 status, body = box.call("admin", "POST", "/collections/invoices/records",
126 {"number": "INV-1", "customer_name": "Cust",
127 "status": "sent", "total_cents": "5000",
128 "owner_id": "cust"})
129 assert status == 201
130 box.invoice = body["record"]["id"]
131 status, body = box.call("admin", "POST", "/collections/payments/records",
132 {"invoice_id": box.invoice, "amount_cents": "5000",
133 "received_on": "2026-11-01", "owner_id": "cust"})
134 assert status == 201, body
135 box.payment = body["record"]["id"]
136 yield box
137
138
139def test_a_customer_cannot_refund_their_own_payment(paid_customer):
140 """POST /collections/refunds as the payment's owner answered 201 and the
141 books journalled it: money out, decided by the person receiving it.
142 Customer-initiated refunds go through returns and disputes, which a
143 member of staff decides."""
144 box = paid_customer
145 status, body = box.call("cust", "POST", "/collections/refunds/records",
146 {"payment_id": box.payment, "amount_cents": "5000",
147 "refunded_on": "2026-11-02"})
148 assert status == 403, body
149 status, body = box.call("admin", "GET",
150 f"/collections/refunds/records?payment_id={box.payment}")
151 assert body["records"] == []
152
153
154def test_staff_refund_and_the_customer_reads_it(paid_customer):
155 box = paid_customer
156 status, body = box.call("maria", "POST", "/collections/refunds/records",
157 {"payment_id": box.payment, "amount_cents": "2000",
158 "refunded_on": "2026-11-02", "owner_id": "maria"})
159 assert status == 201, body
160 refund = body["record"]["id"]
161 # the customer's refund rows are theirs to read, never to edit
162 status, body = box.call("admin", "PUT", f"/collections/refunds/records/{refund}",
163 {"owner_id": "cust"})
164 assert status == 200, body
165 status, body = box.call("cust", "GET", f"/collections/refunds/records/{refund}")
166 assert status == 200 and body["record"]["amount_cents"] == "2000"
167 status, body = box.call("cust", "PUT", f"/collections/refunds/records/{refund}",
168 {"reason": "changed my mind"})
169 assert status == 403, body
170
171
172def test_the_withdrawn_refund_grant_is_retracted():
173 retracted = _retracted("app-payments")
174 assert {"effect": "allow", "principal": "registered",
175 "actions": ["create", "read", "update"], "collection": "refunds",
176 "row_filter": {"owner_id": "$user_id"}} in retracted
177
178
179# -- 3. app-billing: the subscriber may cancel, not reprice -------------------
180
181@pytest.fixture()
182def subscriber():
183 with Sandbox(["app-billing"]) as box:
184 box.add_user("sub")
185 box.add_user("maria", roles=["manager"])
186 plans = {}
187 for code, base in (("pro", "5000"), ("free", "0")):
188 status, body = box.call("admin", "POST", "/collections/billing_plans/records",
189 {"name": code, "code": code, "period": "month",
190 "base_minor": base})
191 assert status == 201, body
192 plans[code] = body["record"]["id"]
193 status, body = box.call("admin", "POST", "/collections/subscriptions/records",
194 {"plan_id": plans["pro"], "status": "past_due",
195 "customer_name": "Sub", "current_period_start": "2026-11-01",
196 "current_period_end": "2026-12-01", "owner_id": "sub"})
197 assert status == 201, body
198 box.plans, box.subscription = plans, body["record"]["id"]
199 yield box
200
201
202def test_a_subscriber_cannot_restore_service_reprice_or_extend_their_own_subscription(subscriber):
203 """Every one of these answered 200: past_due -> active without paying, a
204 price cut to the free plan, and years of service before the biller next
205 closes a period."""
206 box = subscriber
207 path = f"/collections/subscriptions/records/{box.subscription}"
208 for change in ({"status": "active"}, {"plan_id": box.plans["free"]},
209 {"current_period_end": "2036-01-01"}, {"trial_ends_on": "2036-01-01"},
210 {"billing_mode": "wallet"}, {"current_period_start": "2030-01-01"}):
211 status, body = box.call("sub", "PUT", path, change)
212 assert status == 403, (change, body)
213 status, _ = box.call("sub", "DELETE", path)
214 assert status == 403
215 status, body = box.call("sub", "POST", "/collections/subscriptions/records",
216 {"plan_id": box.plans["pro"], "customer_name": "Sub"})
217 assert status == 403, body
218 record = box.call("admin", "GET", path)[1]["record"]
219 assert (record["status"], record["plan_id"], record["current_period_end"]) == (
220 "past_due", box.plans["pro"], "2026-12-01")
221
222
223def test_a_subscriber_may_still_cancel_and_staff_restore_service(subscriber):
224 box = subscriber
225 path = f"/collections/subscriptions/records/{box.subscription}"
226 status, body = box.call("sub", "PUT", path, {"cancel_at_period_end": "true",
227 "notes": "moving abroad"})
228 assert status == 200 and body["record"]["cancel_at_period_end"] == "true", body
229 status, body = box.call("sub", "GET", path)
230 assert status == 200
231 status, body = box.call("maria", "PUT", path, {"status": "active"})
232 assert status == 200 and body["record"]["status"] == "active", body
233
234
235def test_the_withdrawn_subscription_grant_is_retracted():
236 assert {"effect": "allow", "principal": "registered",
237 "actions": ["create", "read", "update", "delete"], "collection": "subscriptions",
238 "row_filter": {"owner_id": "$user_id"}} in _retracted("app-billing")
239
240
241# -- 4. app-promotions: codes are the shop's ----------------------------------
242
243@pytest.fixture()
244def promo_shop():
245 with Sandbox(["app-promotions"]) as box:
246 box.add_user("cust")
247 box.add_user("other")
248 box.add_user("maria", roles=["manager"])
249 status, body = box.call("admin", "POST", "/collections/promotions/records",
250 {"code": "TEN", "kind": "percent", "value": "10",
251 "owner_id": "shop"})
252 assert status == 201, body
253 box.promotion = body["record"]["id"]
254 status, body = box.call("admin", "POST", "/collections/orders/records",
255 {"number": "SO-1", "customer_name": "Other",
256 "owner_id": "other"})
257 assert status == 201, body
258 # Written the way action_checkout writes it: in process, under the
259 # basket's owner.
260 for owner, email in (("other", "other@example.com"), ("cust", "cust@example.com")):
261 object_records.create_collection_record(
262 "promotion_redemptions",
263 {"id": object_ids.new_uuid4(), "promotion_id": box.promotion,
264 "code_used": "TEN", "kind": "percent", "value": "10",
265 "order_id": body["record"]["id"], "customer_email": email,
266 "discount_cents": "100", "owner_id": owner},
267 base_dir=box.data_dir)
268 yield box
269
270
271def test_a_customer_cannot_create_or_raise_a_discount_code(promo_shop):
272 """Any signed-in customer POSTed a 100%-off code (201) or raised a live
273 code's value (200)."""
274 box = promo_shop
275 status, body = box.call("cust", "POST", "/collections/promotions/records",
276 {"code": "FREE", "kind": "percent", "value": "100"})
277 assert status == 403, body
278 status, body = box.call("cust", "PUT", f"/collections/promotions/records/{box.promotion}",
279 {"value": "100"})
280 assert status in (403, 404), body
281 assert box.call("admin", "GET",
282 f"/collections/promotions/records/{box.promotion}")[1]["record"]["value"] == "10"
283
284
285def test_a_customer_lists_no_codes_and_only_their_own_redemptions(promo_shop):
286 """Every redemption (other customers' emails and orders) and every code,
287 unpublished ones included, were readable by any signed-in user."""
288 box = promo_shop
289 status, body = box.call("cust", "GET", "/collections/promotions/records")
290 assert status == 403 or body.get("records") == [], body
291 status, body = box.call("cust", "GET", "/collections/promotion_redemptions/records")
292 assert status == 200, body
293 assert [row["customer_email"] for row in body["records"]] == ["cust@example.com"]
294
295
296def test_a_manager_runs_the_codes_and_reads_every_redemption(promo_shop):
297 box = promo_shop
298 status, body = box.call("maria", "POST", "/collections/promotions/records",
299 {"code": "SPRING", "kind": "percent", "value": "15"})
300 assert status == 201, body
301 status, body = box.call("maria", "PUT", f"/collections/promotions/records/{box.promotion}",
302 {"is_active": "false"})
303 assert status == 200, body
304 status, body = box.call("maria", "GET", "/collections/promotion_redemptions/records")
305 assert status == 200 and len(body["records"]) == 2, body
306
307
308def test_the_withdrawn_promotion_grants_are_retracted():
309 retracted = _retracted("app-promotions")
310 assert {"effect": "allow", "principal": "registered", "actions": ["create", "read", "update"],
311 "collection": "promotions"} in retracted
312 assert {"effect": "allow", "principal": "registered", "actions": ["read"],
313 "collection": "promotion_redemptions"} in retracted
314
315
316# -- 5. app-returns: a buyer's link is a guest's credential -------------------
317
318TRACK_TOKEN = "track-me-token-abcdefghijklmnop"
319
320
321@pytest.fixture()
322def shipped_order():
323 with Sandbox(["app-shop", "app-returns", "app-shipping"]) as box:
324 box.add_user("mallory")
325 box.add_user("maria", roles=["manager"])
326 base = box.data_dir
327 # A guest checkout's order: owned by the shop, opened by its token.
328 object_records.create_collection_record(
329 "orders", {"id": "ord-1", "number": "SO-1", "customer_name": "Ada",
330 "customer_email": "ada@example.test", "status": "shipped",
331 "portal_token": TRACK_TOKEN, "owner_id": "shop"},
332 base_dir=base, preserve_read_only=True)
333 object_records.create_collection_record(
334 "order_lines", {"id": "line-1", "order_id": "ord-1", "description": "Mug",
335 "quantity": "2", "unit_price_cents": "1200", "owner_id": "shop"},
336 base_dir=base)
337 object_records.create_collection_record(
338 "shipments", {"id": "shp-1", "order_id": "ord-1", "direction": "outbound",
339 "status": "delivered", "owner_id": "shop"}, base_dir=base)
340 object_records.create_collection_record(
341 "shipment_lines", {"id": "sl-1", "shipment_id": "shp-1",
342 "order_line_id": "line-1", "quantity": "2",
343 "owner_id": "shop"}, base_dir=base)
344 yield box
345
346
347def _authorize(box, user, **extra):
348 return box.call(user, "POST", "/objects/action_authorize_return",
349 {"order_id": "ord-1", "reason": "damaged",
350 "lines": [{"order_line_id": "line-1", "quantity": "1"}], **extra})
351
352
353def _rmas(box):
354 return object_records.read_collection_records("return_authorizations",
355 base_dir=box.data_dir)
356
357
358def test_a_signed_in_stranger_holding_the_buyers_link_cannot_authorize_a_return(shipped_order):
359 """mallory, signed in, with the buyer's tracking-link token: 200, an RMA
360 authorized, and authorized_by=mallory -- her name in the field that says
361 which human agreed to spend the shop's money."""
362 box = shipped_order
363 status, body = _authorize(box, "mallory", token=TRACK_TOKEN)
364 assert status == 404, body
365 assert _rmas(box) == []
366 # The page holds the same line, and says how the real buyer gets in.
367 status, page = box.call("mallory", "GET", f"/objects/site_return_form?order_id=ord-1&token={TRACK_TOKEN}")
368 assert "Mug" not in str(page) and "sign out" in str(page)
369
370
371def test_staff_authorize_and_a_guest_with_the_link_is_named_by_nobody(shipped_order):
372 """The guest path (the public form, signed out, with the link) still
373 authorizes, and leaves authorized_by blank rather than naming the
374 order's owner as if the shop had agreed; whoever may update the order
375 (here an admin) still authorizes signed in."""
376 box = shipped_order
377 status, page = box.call("anon", "POST", "/objects/site_return_form",
378 {"order_id": "ord-1", "token": TRACK_TOKEN,
379 "reason": "damaged", "qty_line-1": "1"})
380 assert status == 200, page
381 rmas = _rmas(box)
382 assert len(rmas) == 1 and rmas[0]["status"] == "authorized"
383 assert rmas[0]["authorized_by"] == ""
384 status, body = _authorize(box, "admin")
385 assert status == 200, body
386
387
388# -- survey: app-payments: a customer cannot pay their own bill by saying so ---
389
390def test_a_customer_cannot_record_a_payment_against_their_own_invoice(paid_customer):
391 """The invoice checkout or the biller raises is the customer's, so the
392 pointer check passed and a 'received' cash payment from the customer
393 was 201: the status handler marks the invoice paid and app-shop ships."""
394 box = paid_customer
395 status, body = box.call("admin", "POST", "/collections/invoices/records",
396 {"number": "INV-2", "customer_name": "Cust", "status": "sent",
397 "total_cents": "7000", "owner_id": "cust"})
398 assert status == 201
399 invoice = body["record"]["id"]
400 status, body = box.call("cust", "POST", "/collections/payments/records",
401 {"invoice_id": invoice, "amount_cents": "7000",
402 "received_on": "2026-11-01", "method": "cash"})
403 assert status == 403, body
404 status, body = box.call("cust", "PUT", f"/collections/payments/records/{box.payment}",
405 {"notes": "paid twice really"})
406 assert status == 403, body
407 status, body = box.call("cust", "GET", f"/collections/payments/records/{box.payment}")
408 assert status == 200 and body["record"]["amount_cents"] == "5000"
409
410
411def test_staff_record_and_bounce_a_customers_payment(paid_customer):
412 """The bounce was guarded on owner_id = $user_id, which refused staff on
413 a payment the customer owns."""
414 box = paid_customer
415 status, body = box.call("maria", "PUT", f"/collections/payments/records/{box.payment}",
416 {"status": "bounced"})
417 assert status == 200 and body["record"]["status"] == "bounced", body
418 status, body = box.call("admin", "POST", "/collections/invoices/records",
419 {"number": "INV-3", "customer_name": "Cust", "status": "sent",
420 "total_cents": "3000", "owner_id": "cust"})
421 status, body = box.call("maria", "POST", "/collections/payments/records",
422 {"invoice_id": body["record"]["id"], "amount_cents": "3000",
423 "received_on": "2026-11-03", "method": "cash"})
424 assert status == 201, body
425
426
427# -- survey: app-billing wallets: the holder sets their top-up, not the money --
428
429@pytest.fixture()
430def wallet_holder():
431 with Sandbox(["app-billing"]) as box:
432 box.add_user("cust")
433 status, body = box.call("admin", "POST", "/collections/wallets/records",
434 {"kind": "balance", "owner_id": "cust",
435 "stripe_customer_id": "cus_CUST",
436 "payment_method_ref": "pm_CUST"})
437 assert status == 201, body
438 box.wallet = body["record"]["id"]
439 yield box
440
441
442def test_a_wallet_holder_cannot_repoint_its_card_denomination_or_kind(wallet_holder):
443 """The registered update grant let the holder point stripe_customer_id and
444 payment_method_ref at another customer's saved card (which the replenish
445 handler charges off-session into THIS wallet), restate the balance in
446 another denomination, or make it a bearer gift card."""
447 box = wallet_holder
448 path = f"/collections/wallets/records/{box.wallet}"
449 for change in ({"stripe_customer_id": "cus_VICTIM"}, {"payment_method_ref": "pm_VICTIM"},
450 {"denomination_id": "anything"}, {"kind": "gift_card"},
451 {"code": "GIFT-1234"}):
452 status, body = box.call("cust", "PUT", path, change)
453 assert status == 403, (change, body)
454 record = box.call("admin", "GET", path)[1]["record"]
455 assert (record["stripe_customer_id"], record["payment_method_ref"], record["kind"]) == (
456 "cus_CUST", "pm_CUST", "balance")
457
458
459def test_a_wallet_holder_still_sets_their_own_auto_top_up(wallet_holder):
460 box = wallet_holder
461 status, body = box.call("cust", "PUT", f"/collections/wallets/records/{box.wallet}",
462 {"auto_replenish_enabled": "true",
463 "auto_replenish_threshold_minor": "500",
464 "auto_replenish_amount_minor": "2000",
465 "auto_replenish_monthly_cap_minor": "4000"})
466 assert status == 200, body