askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_relation_requires.py · 9.7 KB · 197 lines
| 1 | """A row that points at a record acts on it: refunds, payments and `relation.requires`. |
| 2 | |
| 3 | Found by a simulated-company trial, reproduced here through the real HTTP API |
| 4 | with enforcement on: any registered user could refund any customer's payment. |
| 5 | `POST /collections/refunds/records {"payment_id": <ann's payment>, "amount_cents": |
| 6 | 5000, "owner_id": <mallory>}` was 201. The create rule asks only that the new |
| 7 | row's owner_id be the caller's; hook_refunds and its locked check ask only that |
| 8 | the refund fits the payment's headroom; nothing asked whether the caller may act |
| 9 | on the payment. The same shape let anybody record a payment against anybody's |
| 10 | invoice, which moves that invoice's paid and balance amounts. |
| 11 | |
| 12 | The fix is the schema's: a relation may declare `"requires": "read" | "update"`, |
| 13 | and the record API then lets a subject write that pointer only if the engine |
| 14 | would let the same subject read (and, for update, update) the target row. These |
| 15 | tests pin both the refund and the payment hole closed and the mechanism's edges: |
| 16 | the parent's owner, an admin and a granted role still get through; a reader who |
| 17 | may not update gets a 403 that says why; a target the writer may not see at all |
| 18 | is answered exactly like one that does not exist. |
| 19 | """ |
| 20 | |
| 21 | import json |
| 22 | |
| 23 | import pytest |
| 24 | |
| 25 | import object_permission_store |
| 26 | import object_permissions |
| 27 | import object_schemas |
| 28 | from scripts.try_package import Sandbox |
| 29 | |
| 30 | INVOICES = "/collections/invoices/records" |
| 31 | PAYMENTS = "/collections/payments/records" |
| 32 | REFUNDS = "/collections/refunds/records" |
| 33 | |
| 34 | |
| 35 | def _grant(box, rule): |
| 36 | """Append one rule to the sandbox's live policy (an operator's edit).""" |
| 37 | policy = object_permission_store.load_policy(box.data_dir) |
| 38 | payload = object_permissions.policy_to_dict(policy) |
| 39 | payload["rules"].append(rule) |
| 40 | object_permission_store.replace_policy(payload, base_dir=box.data_dir) |
| 41 | |
| 42 | |
| 43 | @pytest.fixture |
| 44 | def box(): |
| 45 | with Sandbox(["app-payments"]) as sandbox: |
| 46 | # ann runs the books: an invoice's status and total are staff fields |
| 47 | # since app-invoices 0.15.0 (a machine-raised invoice's owner is the |
| 48 | # customer it bills), so the clerk who issues one holds role:manager. |
| 49 | sandbox.add_user("ann", roles=["manager"]) |
| 50 | # Since app-payments 0.7.0 no plain registered user may file a refund |
| 51 | # at all (a payment's owner is the payer), nor since 0.8.0 record a |
| 52 | # payment. mallory holds a role that files refunds and payments of |
| 53 | # her own and nothing else, which is the shape the |
| 54 | # pointer check below has to hold against: a writer allowed to create |
| 55 | # the row, pointing it at a payment she has nothing to do with. |
| 56 | sandbox.add_user("mallory", roles=["clerk"]) |
| 57 | sandbox.add_user("carol", roles=["auditor"]) |
| 58 | sandbox.add_user("bea", roles=["bookkeeper"]) |
| 59 | _grant(sandbox, {"effect": "allow", "principal": "role:auditor", "actions": ["read"], |
| 60 | "collection": "payments", "reason": "auditors read every payment"}) |
| 61 | _grant(sandbox, {"effect": "allow", "principal": "role:bookkeeper", |
| 62 | "actions": ["read", "update"], "collection": "payments", |
| 63 | "reason": "bookkeepers work every payment"}) |
| 64 | _grant(sandbox, {"effect": "allow", "principal": "role:auditor", "actions": ["create"], |
| 65 | "collection": "refunds", "row_filter": {"owner_id": "$user_id"}, |
| 66 | "reason": "test: an auditor may file refunds of their own"}) |
| 67 | _grant(sandbox, {"effect": "allow", "principal": "role:clerk", "actions": ["create"], |
| 68 | "collection": "refunds", "row_filter": {"owner_id": "$user_id"}, |
| 69 | "reason": "test: a clerk may file refunds of their own"}) |
| 70 | # Likewise payments (staff-only since app-payments 0.8.0). |
| 71 | _grant(sandbox, {"effect": "allow", "principal": "role:clerk", "actions": ["create"], |
| 72 | "collection": "payments", "row_filter": {"owner_id": "$user_id"}, |
| 73 | "reason": "test: a clerk may record payments of their own"}) |
| 74 | yield sandbox |
| 75 | |
| 76 | |
| 77 | def _ann_paid_invoice(box, total=10000): |
| 78 | status, body = box.call("ann", "POST", INVOICES, { |
| 79 | "number": "INV-1", "customer_name": "Acme", "status": "sent", |
| 80 | "total_cents": total, "owner_id": "ann"}) |
| 81 | assert status == 201, body |
| 82 | invoice_id = body["record"]["id"] |
| 83 | status, body = box.call("ann", "POST", PAYMENTS, { |
| 84 | "invoice_id": invoice_id, "amount_cents": total, "received_on": "2026-11-02", |
| 85 | "owner_id": "ann"}) |
| 86 | assert status == 201, body |
| 87 | return invoice_id, body["record"]["id"] |
| 88 | |
| 89 | |
| 90 | def _refund(box, user, payment_id, amount=5000): |
| 91 | return box.call(user, "POST", REFUNDS, { |
| 92 | "payment_id": payment_id, "amount_cents": amount, "refunded_on": "2026-11-03", |
| 93 | "owner_id": user}) |
| 94 | |
| 95 | |
| 96 | def _refunded(box, payment_id): |
| 97 | status, body = box.call("admin", "GET", f"{PAYMENTS}/{payment_id}") |
| 98 | assert status == 200, body |
| 99 | return int(body["record"].get("refunded_cents") or 0) |
| 100 | |
| 101 | |
| 102 | def test_a_registered_user_cannot_refund_another_customers_payment(box): |
| 103 | """The reported hole: mallory refunded half of ann's payment and got 201. |
| 104 | Money left an account she has nothing to do with.""" |
| 105 | _, payment_id = _ann_paid_invoice(box) |
| 106 | status, body = _refund(box, "mallory", payment_id) |
| 107 | assert status == 400, body |
| 108 | assert body["error"] == f"Record field 'payment_id' references a missing record: payments/{payment_id}" |
| 109 | assert _refunded(box, payment_id) == 0 |
| 110 | status, body = box.call("admin", "GET", f"{REFUNDS}?payment_id={payment_id}") |
| 111 | assert status == 200 and body["records"] == [] |
| 112 | |
| 113 | |
| 114 | def test_the_refusal_is_the_same_answer_a_missing_payment_gets(box): |
| 115 | """A payment mallory may not see answers like one that does not exist, so |
| 116 | the refund form is no oracle for other people's payment ids.""" |
| 117 | _, payment_id = _ann_paid_invoice(box) |
| 118 | missing = "00000000-0000-4000-8000-000000000000" |
| 119 | hidden = _refund(box, "mallory", payment_id) |
| 120 | absent = _refund(box, "mallory", missing) |
| 121 | assert hidden[0] == absent[0] == 400 |
| 122 | assert hidden[1]["error"].replace(payment_id, "X") == absent[1]["error"].replace(missing, "X") |
| 123 | |
| 124 | |
| 125 | def test_a_registered_user_cannot_record_a_payment_against_another_users_invoice(box): |
| 126 | """Same shape one level up: a payment against ann's invoice marks it paid |
| 127 | (or part paid) whoever recorded it.""" |
| 128 | invoice_id, _ = _ann_paid_invoice(box, total=20000) |
| 129 | status, body = box.call("mallory", "POST", PAYMENTS, { |
| 130 | "invoice_id": invoice_id, "amount_cents": 1, "received_on": "2026-11-03", |
| 131 | "owner_id": "mallory"}) |
| 132 | assert status == 400, body |
| 133 | assert "references a missing record" in body["error"] |
| 134 | status, body = box.call("admin", "GET", f"{PAYMENTS}?invoice_id={invoice_id}") |
| 135 | assert [row["owner_id"] for row in body["records"]] == ["ann"] |
| 136 | |
| 137 | |
| 138 | def test_the_person_who_recorded_the_payment_still_refunds_it(box): |
| 139 | """The person who recorded the payment (staff: role:manager since |
| 140 | app-payments 0.7.0) refunds it, ceiling and all.""" |
| 141 | _, payment_id = _ann_paid_invoice(box) |
| 142 | status, body = _refund(box, "ann", payment_id, amount=4000) |
| 143 | assert status == 201, body |
| 144 | assert _refunded(box, payment_id) == 4000 |
| 145 | status, body = _refund(box, "ann", payment_id, amount=7000) |
| 146 | assert status == 409, body # the ceiling still holds |
| 147 | |
| 148 | |
| 149 | def test_an_admin_refunds_any_payment(box): |
| 150 | _, payment_id = _ann_paid_invoice(box) |
| 151 | status, body = box.call("admin", "POST", REFUNDS, { |
| 152 | "payment_id": payment_id, "amount_cents": 100, "refunded_on": "2026-11-03", |
| 153 | "owner_id": "ann"}) |
| 154 | assert status == 201, body |
| 155 | |
| 156 | |
| 157 | def test_a_role_that_may_read_the_payment_but_not_update_it_gets_a_403_saying_why(box): |
| 158 | """carol (auditor) may read every payment and file refunds of her own, but |
| 159 | may not update the payment, so she may not refund it. She can see it, so |
| 160 | the answer can say so.""" |
| 161 | _, payment_id = _ann_paid_invoice(box) |
| 162 | status, body = _refund(box, "carol", payment_id) |
| 163 | assert status == 403, body |
| 164 | assert body["code"] == "forbidden" and body["field"] == "payment_id" |
| 165 | assert "may not update" in body["error"] |
| 166 | assert _refunded(box, payment_id) == 0 |
| 167 | |
| 168 | |
| 169 | def test_a_role_granted_update_on_payments_may_record_a_payment_and_refund_on_them(box): |
| 170 | """A grant on the parent is what the check reads: bea's role may update |
| 171 | every payment, and refunds are hers to file once she may create them.""" |
| 172 | _grant(box, {"effect": "allow", "principal": "role:bookkeeper", "actions": ["create", "read"], |
| 173 | "collection": "refunds", "row_filter": {"owner_id": "$user_id"}, |
| 174 | "reason": "test: bookkeepers file refunds"}) |
| 175 | _, payment_id = _ann_paid_invoice(box) |
| 176 | status, body = _refund(box, "bea", payment_id, amount=250) |
| 177 | assert status == 201, body |
| 178 | assert _refunded(box, payment_id) == 250 |
| 179 | |
| 180 | |
| 181 | def test_the_shipped_schemas_declare_the_requirement(): |
| 182 | """The check is wired by the schema: a refunds.json without `requires` on |
| 183 | payment_id passes every hook test and reopens the hole.""" |
| 184 | refunds = json.loads(open("packages/app-payments/schemas/refunds.json").read()) |
| 185 | payments = json.loads(open("packages/app-payments/schemas/payments.json").read()) |
| 186 | by_name = {field["name"]: field for field in refunds["fields"]} |
| 187 | assert by_name["payment_id"]["relation"]["requires"] == "update" |
| 188 | by_name = {field["name"]: field for field in payments["fields"]} |
| 189 | assert by_name["invoice_id"]["relation"]["requires"] == "update" |
| 190 | |
| 191 | |
| 192 | def test_an_unknown_requires_value_is_refused_at_install(): |
| 193 | """A typo ("updtae") would check nothing while reading as if it did.""" |
| 194 | with pytest.raises(ValueError, match="requires"): |
| 195 | object_schemas._normalize_field( |
| 196 | {"name": "payment_id", "relation": {"collection": "payments", "requires": "updtae"}}, |
| 197 | schema="refunds") |