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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
test_invoice_portal.py · 17.3 KB · 424 lines
| 1 | """Customer payment portal (plan/customer-payment-portal-spec.md): the door |
| 2 | a dunning email currently has no way to point at. |
| 3 | |
| 4 | Fixture style mirrors tests/test_payments_slice2.py -- direct |
| 5 | object_execution.execute_object calls against the real package objects, |
| 6 | schemas copied straight from packages/app-invoices/schemas/*.json (so a |
| 7 | future schema edit can't silently drift out of sync with what this test |
| 8 | exercises), and app-payments' own system_invoice_status object reused |
| 9 | (read-only, never edited here) to produce a realistic partial/paid state |
| 10 | the same way a live deployment would, rather than hand-faking the |
| 11 | computed amount_paid_cents/balance_due_cents fields. |
| 12 | |
| 13 | Security posture under test, per the spec's own sketch: portal_token |
| 14 | never surfaces in a list/search response for a non-owner (guaranteed by |
| 15 | the pre-existing row_filter on the invoices collection, unrelated to |
| 16 | anything this feature adds -- proven directly against |
| 17 | packages/app-invoices/permissions/rules.json); the portal page 404s on a |
| 18 | bad or blank token, never 403 (never confirm the token space exists); |
| 19 | void invoices refuse the portal's financial content; and regenerating a |
| 20 | link invalidates whatever token was live before. |
| 21 | """ |
| 22 | |
| 23 | import json |
| 24 | import pathlib |
| 25 | |
| 26 | import object_execution |
| 27 | import object_permissions |
| 28 | import object_records |
| 29 | import python_object_runtime |
| 30 | from conftest import stage_collection |
| 31 | |
| 32 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 33 | PACKAGES = REPO_ROOT / "packages" |
| 34 | APP_INVOICES = PACKAGES / "app-invoices" |
| 35 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 36 | |
| 37 | |
| 38 | def setup_env(tmp_path, monkeypatch, *, settings=(), with_invoice_lines=False): |
| 39 | data_dir = tmp_path / "data" |
| 40 | |
| 41 | # invoices: header is the real seed file's own header line -- kept in |
| 42 | # sync with the schema by construction (the seed IS real invoice data), |
| 43 | # rather than a second hand-typed field list that could drift. Not |
| 44 | # schema_header(): deliberately verbatim, per this module's docstring. |
| 45 | schema_dir = data_dir / "schemas" |
| 46 | schema_dir.mkdir(parents=True, exist_ok=True) |
| 47 | (schema_dir / "invoices.json").write_text( |
| 48 | (APP_INVOICES / "schemas" / "invoices.json").read_text()) |
| 49 | invoices_header = (APP_INVOICES / "seed" / "invoices.tsv").read_text().splitlines()[0] + "\n" |
| 50 | invoices_coll = data_dir / "collections" / "invoices" |
| 51 | invoices_coll.mkdir(parents=True, exist_ok=True) |
| 52 | (invoices_coll / "records.tsv").write_text(invoices_header) |
| 53 | |
| 54 | stage_collection(data_dir, "app-payments", "payments") |
| 55 | stage_collection(data_dir, "app-payments", "refunds") |
| 56 | stage_collection(data_dir, "app-email", "email_outbox") |
| 57 | if with_invoice_lines: |
| 58 | stage_collection(data_dir, "app-invoices", "invoice_lines") |
| 59 | |
| 60 | rows = "" |
| 61 | for i, (k, v) in enumerate(settings): |
| 62 | rows += f"s{i}\t{k}\t{v}\t\n" |
| 63 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 64 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 65 | return data_dir |
| 66 | |
| 67 | |
| 68 | def make_invoice(data_dir, iid="inv1", status="sent", total="10000", |
| 69 | due="2026-07-10", email="grace@acme.test", owner="dan", **extra): |
| 70 | rec = {"id": iid, "number": f"N-{iid}", "customer_name": "Grace Hopper", |
| 71 | "customer_email": email, "status": status, "due_date": due, |
| 72 | "issue_date": "2026-06-10", "total_cents": total, "owner_id": owner} |
| 73 | rec.update(extra) |
| 74 | return object_records.create_collection_record("invoices", rec, base_dir=data_dir) |
| 75 | |
| 76 | |
| 77 | def pay(data_dir, pid, invoice_id, cents, status="received"): |
| 78 | return object_records.create_collection_record( |
| 79 | "payments", |
| 80 | {"id": pid, "invoice_id": invoice_id, "amount_cents": cents, |
| 81 | "method": "card", "received_on": "2026-07-09", "status": status, |
| 82 | "owner_id": "dan"}, |
| 83 | base_dir=data_dir) |
| 84 | |
| 85 | |
| 86 | def fire_status(collection, record_id, action_raw): |
| 87 | """Reuses app-payments' own system_invoice_status object (read-only |
| 88 | import, not edited by this task) to produce realistic partial/paid |
| 89 | invoice state -- amount_paid_cents/balance_due_cents/status all |
| 90 | genuinely computed, not hand-faked.""" |
| 91 | return object_execution.execute_object( |
| 92 | RUNTIME, |
| 93 | object_execution.ObjectExecutionRequest( |
| 94 | "system_invoice_status", method="EVENT", |
| 95 | payload={"event": f"{collection}.record.{action_raw}d", |
| 96 | "collection": collection, "record_id": record_id, |
| 97 | "action": action_raw}), |
| 98 | roots=[PACKAGES / "app-payments" / "objects"]) |
| 99 | |
| 100 | |
| 101 | def run_aging(today): |
| 102 | return object_execution.execute_object( |
| 103 | RUNTIME, |
| 104 | object_execution.ObjectExecutionRequest( |
| 105 | "system_invoice_aging", method="POST", payload={"today": today}), |
| 106 | roots=[APP_INVOICES / "objects"]) |
| 107 | |
| 108 | |
| 109 | def portal_get(token, query_extra=None): |
| 110 | payload = {"token": token} |
| 111 | if query_extra: |
| 112 | payload.update(query_extra) |
| 113 | return object_execution.execute_object( |
| 114 | RUNTIME, |
| 115 | object_execution.ObjectExecutionRequest( |
| 116 | "site_invoice_portal", method="GET", payload=payload), |
| 117 | roots=[APP_INVOICES / "objects"]) |
| 118 | |
| 119 | |
| 120 | def regenerate(invoice_id, user_id="dan", roles=None): |
| 121 | identity = {"user_id": user_id, "roles": roles or []} if user_id else {} |
| 122 | payload = {"invoice_id": invoice_id} |
| 123 | if identity: |
| 124 | payload["_identity"] = identity |
| 125 | return object_execution.execute_object( |
| 126 | RUNTIME, |
| 127 | object_execution.ObjectExecutionRequest( |
| 128 | "action_regenerate_portal_link", method="POST", payload=payload), |
| 129 | roots=[APP_INVOICES / "objects"]) |
| 130 | |
| 131 | |
| 132 | def invoice(data_dir, iid="inv1"): |
| 133 | return object_records.get_collection_record("invoices", iid, base_dir=data_dir) |
| 134 | |
| 135 | |
| 136 | def outbox(data_dir): |
| 137 | return object_records.read_collection_records("email_outbox", base_dir=data_dir) |
| 138 | |
| 139 | |
| 140 | def token_for(data_dir, iid="inv1", owner="dan"): |
| 141 | """Mint a portal link the way an owner would, and return the bare token.""" |
| 142 | result = regenerate(iid, user_id=owner) |
| 143 | assert result.ok, result.error |
| 144 | path = result.result["path"] |
| 145 | assert path.startswith("/pay/") |
| 146 | return path[len("/pay/"):] |
| 147 | |
| 148 | |
| 149 | # --- states ----------------------------------------------------------------- |
| 150 | |
| 151 | def test_unpaid_state_shows_amount_due_and_instructions_with_no_pay_button(tmp_path, monkeypatch): |
| 152 | data_dir = setup_env(tmp_path, monkeypatch, |
| 153 | settings=(("portal.payment_instructions", |
| 154 | "Wire to Acme Bank, account 000123"),)) |
| 155 | make_invoice(data_dir, total="10000") |
| 156 | token = token_for(data_dir) |
| 157 | |
| 158 | result = portal_get(token) |
| 159 | assert result.ok, result.error |
| 160 | body = result.result["body"] |
| 161 | assert result.result.get("status", 200) == 200 |
| 162 | assert "Payment due" in body |
| 163 | assert "100.00 USD" in body # balance_due_cents=10000 |
| 164 | assert "Wire to Acme Bank, account 000123" in body |
| 165 | # No fake Pay button: there is no card-processing rail wired up yet, and |
| 166 | # a button that posts nowhere is worse than no button at all. |
| 167 | assert "Pay now" not in body and "<button" not in body and "<form" not in body |
| 168 | |
| 169 | |
| 170 | def test_unpaid_state_without_instructions_says_so_plainly(tmp_path, monkeypatch): |
| 171 | data_dir = setup_env(tmp_path, monkeypatch) # no portal.payment_instructions set |
| 172 | make_invoice(data_dir, total="5000") |
| 173 | token = token_for(data_dir) |
| 174 | |
| 175 | body = portal_get(token).result["body"] |
| 176 | assert "has not published payment instructions" in body |
| 177 | # Never an empty box standing in for the missing setting. |
| 178 | assert '<div class="instructions"></div>' not in body |
| 179 | |
| 180 | |
| 181 | def test_partial_state_shows_received_and_remaining(tmp_path, monkeypatch): |
| 182 | data_dir = setup_env(tmp_path, monkeypatch) |
| 183 | make_invoice(data_dir, total="10000") |
| 184 | pay(data_dir, "p1", "inv1", "4000") |
| 185 | fire_status("payments", "p1", "create") |
| 186 | assert invoice(data_dir)["status"] == "partial" |
| 187 | token = token_for(data_dir) |
| 188 | |
| 189 | body = portal_get(token).result["body"] |
| 190 | assert "Partially paid" in body |
| 191 | assert "40.00 USD" in body # received so far |
| 192 | assert "60.00 USD" in body # still due |
| 193 | assert "How to pay" in body |
| 194 | |
| 195 | |
| 196 | def test_paid_state_renders_receipt_with_no_payment_instructions(tmp_path, monkeypatch): |
| 197 | data_dir = setup_env(tmp_path, monkeypatch, |
| 198 | settings=(("portal.payment_instructions", "Wire details here"),)) |
| 199 | make_invoice(data_dir, total="10000") |
| 200 | pay(data_dir, "p1", "inv1", "10000") |
| 201 | fire_status("payments", "p1", "create") |
| 202 | assert invoice(data_dir)["status"] == "paid" |
| 203 | token = token_for(data_dir) |
| 204 | |
| 205 | body = portal_get(token).result["body"] |
| 206 | assert "Paid in full" in body |
| 207 | assert "100.00 USD" in body |
| 208 | assert "No further payment is due" in body |
| 209 | assert "Wire details here" not in body # receipt view, not a pay ask |
| 210 | |
| 211 | |
| 212 | def test_void_invoice_refuses_the_portal(tmp_path, monkeypatch): |
| 213 | data_dir = setup_env(tmp_path, monkeypatch, |
| 214 | settings=(("portal.payment_instructions", "Wire details here"),)) |
| 215 | make_invoice(data_dir, status="void", total="10000") |
| 216 | token = token_for(data_dir) |
| 217 | |
| 218 | result = portal_get(token) |
| 219 | body = result.result["body"] |
| 220 | assert result.result.get("status", 200) == 200 # a real page, not a 404 -- it IS found |
| 221 | assert "cancelled" in body.lower() |
| 222 | # Refuses the financial content entirely: no balance, no instructions, |
| 223 | # no line items -- showing any of that on a cancelled document would |
| 224 | # invite paying a bill that no longer exists. |
| 225 | assert "Amount due" not in body |
| 226 | assert "Wire details here" not in body |
| 227 | |
| 228 | |
| 229 | # --- token lookup security ---------------------------------------------- |
| 230 | |
| 231 | def test_unknown_token_is_404_not_403(tmp_path, monkeypatch): |
| 232 | data_dir = setup_env(tmp_path, monkeypatch) |
| 233 | make_invoice(data_dir) |
| 234 | token_for(data_dir) # a real token exists in the system, just not this one |
| 235 | |
| 236 | result = portal_get("totally-made-up-token-value") |
| 237 | assert result.result["status"] == 404 |
| 238 | assert "not found" in result.result["body"].lower() |
| 239 | assert "403" not in str(result.result) |
| 240 | |
| 241 | |
| 242 | def test_blank_token_is_404_even_when_no_invoice_has_minted_one(tmp_path, monkeypatch): |
| 243 | """A blank submitted token must never match a blank stored portal_token |
| 244 | (an invoice that has never had a link generated) -- otherwise "no link |
| 245 | yet" would accidentally be an open door.""" |
| 246 | data_dir = setup_env(tmp_path, monkeypatch) |
| 247 | make_invoice(data_dir) # portal_token left at its default: blank |
| 248 | |
| 249 | result = portal_get("") |
| 250 | assert result.result["status"] == 404 |
| 251 | |
| 252 | |
| 253 | # --- view counters ------------------------------------------------------ |
| 254 | |
| 255 | def test_portal_view_stamps_counter_and_timestamp_on_every_view(tmp_path, monkeypatch): |
| 256 | data_dir = setup_env(tmp_path, monkeypatch) |
| 257 | make_invoice(data_dir) |
| 258 | token = token_for(data_dir) |
| 259 | |
| 260 | assert invoice(data_dir)["portal_views"] in ("0", "", None) |
| 261 | portal_get(token) |
| 262 | row = invoice(data_dir) |
| 263 | assert row["portal_views"] == "1" |
| 264 | assert row["last_viewed_at"] |
| 265 | |
| 266 | portal_get(token) |
| 267 | assert invoice(data_dir)["portal_views"] == "2" |
| 268 | |
| 269 | |
| 270 | # --- line items ----------------------------------------------------------- |
| 271 | |
| 272 | def test_line_items_render_when_invoice_lines_is_installed(tmp_path, monkeypatch): |
| 273 | data_dir = setup_env(tmp_path, monkeypatch, with_invoice_lines=True) |
| 274 | make_invoice(data_dir, total="10000") |
| 275 | object_records.create_collection_record( |
| 276 | "invoice_lines", |
| 277 | {"id": "l1", "invoice_id": "inv1", "description": "Consulting hours", |
| 278 | "quantity": "2", "unit_price_cents": "5000", "line_total_cents": "10000", |
| 279 | "owner_id": "dan"}, |
| 280 | base_dir=data_dir) |
| 281 | token = token_for(data_dir) |
| 282 | |
| 283 | body = portal_get(token).result["body"] |
| 284 | assert "Consulting hours" in body |
| 285 | assert "50.00 USD" in body # unit price |
| 286 | |
| 287 | |
| 288 | def test_line_items_skip_gracefully_when_invoice_lines_not_installed(tmp_path, monkeypatch): |
| 289 | data_dir = setup_env(tmp_path, monkeypatch, with_invoice_lines=False) |
| 290 | make_invoice(data_dir, total="10000") |
| 291 | token = token_for(data_dir) |
| 292 | |
| 293 | result = portal_get(token) |
| 294 | assert result.ok, result.error # must not crash just because the collection is absent |
| 295 | body = result.result["body"] |
| 296 | assert result.result.get("status", 200) == 200 |
| 297 | assert '<table class="lines">' not in body |
| 298 | |
| 299 | |
| 300 | # --- regeneration --------------------------------------------------------- |
| 301 | |
| 302 | def test_regenerate_invalidates_the_old_token(tmp_path, monkeypatch): |
| 303 | data_dir = setup_env(tmp_path, monkeypatch) |
| 304 | make_invoice(data_dir) |
| 305 | old_token = token_for(data_dir) |
| 306 | assert portal_get(old_token).result.get("status", 200) == 200 |
| 307 | |
| 308 | new_result = regenerate("inv1", user_id="dan") |
| 309 | new_token = new_result.result["path"][len("/pay/"):] |
| 310 | assert new_token != old_token |
| 311 | |
| 312 | assert portal_get(old_token).result["status"] == 404 |
| 313 | assert portal_get(new_token).result.get("status", 200) == 200 |
| 314 | |
| 315 | |
| 316 | def test_regenerate_requires_owner_or_admin(tmp_path, monkeypatch): |
| 317 | data_dir = setup_env(tmp_path, monkeypatch) |
| 318 | make_invoice(data_dir, owner="dan") |
| 319 | |
| 320 | stranger = regenerate("inv1", user_id="mallory") |
| 321 | assert stranger.result["status"] == 403 |
| 322 | |
| 323 | anonymous = regenerate("inv1", user_id=None) |
| 324 | assert anonymous.result["status"] == 403 |
| 325 | |
| 326 | owner = regenerate("inv1", user_id="dan") |
| 327 | assert owner.result["status"] == 200 |
| 328 | |
| 329 | admin = regenerate("inv1", user_id="ops", roles=["admin"]) |
| 330 | assert admin.result["status"] == 200 |
| 331 | |
| 332 | |
| 333 | def test_regenerate_missing_or_unknown_invoice(tmp_path, monkeypatch): |
| 334 | setup_env(tmp_path, monkeypatch) |
| 335 | assert regenerate("", user_id="dan").result["status"] == 400 |
| 336 | assert regenerate("does-not-exist", user_id="dan").result["status"] == 404 |
| 337 | |
| 338 | |
| 339 | # --- dunning email carries the door ---------------------------------------- |
| 340 | |
| 341 | def test_dunning_email_contains_the_pay_link_when_base_url_configured(tmp_path, monkeypatch): |
| 342 | data_dir = setup_env(tmp_path, monkeypatch, |
| 343 | settings=(("portal.base_url", "https://pay.example.test"),)) |
| 344 | make_invoice(data_dir) # due 2026-07-10, unpaid, no portal_token minted yet |
| 345 | |
| 346 | run_aging("2026-07-11") |
| 347 | mails = outbox(data_dir) |
| 348 | assert len(mails) == 1 |
| 349 | body = mails[0]["text_body"] |
| 350 | assert "https://pay.example.test/pay/" in body |
| 351 | |
| 352 | # The link must actually resolve -- proves aging minted a real token, |
| 353 | # not a placeholder. |
| 354 | token = body.split("https://pay.example.test/pay/", 1)[1].split()[0].strip() |
| 355 | assert invoice(data_dir)["portal_token"] == token |
| 356 | assert portal_get(token).result.get("status", 200) == 200 |
| 357 | |
| 358 | |
| 359 | def test_dunning_email_omits_link_cleanly_when_base_url_unset(tmp_path, monkeypatch): |
| 360 | data_dir = setup_env(tmp_path, monkeypatch) # portal.base_url never set |
| 361 | make_invoice(data_dir) |
| 362 | |
| 363 | run_aging("2026-07-11") |
| 364 | mails = outbox(data_dir) |
| 365 | assert len(mails) == 1 |
| 366 | body = mails[0]["text_body"] |
| 367 | assert "/pay/" not in body |
| 368 | assert "http" not in body |
| 369 | # No link was ever built, so no token needed to be minted to build one. |
| 370 | assert invoice(data_dir)["portal_token"] in ("", None) |
| 371 | |
| 372 | |
| 373 | # --- amounts in whole currency units --------------------------------------- |
| 374 | |
| 375 | def test_amounts_render_via_format_amount_in_whole_units_never_raw_cents(tmp_path, monkeypatch): |
| 376 | import object_money |
| 377 | data_dir = setup_env(tmp_path, monkeypatch) |
| 378 | make_invoice(data_dir, total="123456") # $1,234.56 |
| 379 | token = token_for(data_dir) |
| 380 | |
| 381 | body = portal_get(token).result["body"] |
| 382 | expected = object_money.format_amount("123456", "USD", base_dir=data_dir) |
| 383 | assert expected in body |
| 384 | assert "123456 cents" not in body |
| 385 | assert "123456" not in body.replace(expected, "") # raw minor units never leak elsewhere |
| 386 | |
| 387 | |
| 388 | # --- security: token cannot surface for a non-owner ------------------------ |
| 389 | |
| 390 | def _app_invoices_policy(): |
| 391 | payload = json.loads((APP_INVOICES / "permissions" / "rules.json").read_text()) |
| 392 | return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]}) |
| 393 | |
| 394 | |
| 395 | def test_portal_token_never_reaches_a_non_owner_via_list_or_search(): |
| 396 | """portal_token is not itself access-controlled field-by-field -- it |
| 397 | relies entirely on the invoices collection's existing row_filter |
| 398 | ({"owner_id": "$user_id"}), unmodified by this feature. Proving that |
| 399 | filter still denies READ to a non-owner is exactly proving the token |
| 400 | can never appear in a list/search response for anyone but the owner: |
| 401 | a row nobody may read is a row whose fields, portal_token included, |
| 402 | never leave the server for that caller.""" |
| 403 | policy = _app_invoices_policy() |
| 404 | stranger = object_permissions.PermissionSubject(user_id="mallory") |
| 405 | record = {"owner_id": "dan", "number": "N-inv1", "customer_name": "Grace Hopper", |
| 406 | "status": "sent", "portal_token": "super-secret-capability-token"} |
| 407 | |
| 408 | decision = object_permissions.check_permission( |
| 409 | stranger, object_permissions.READ, policy=policy, collection="invoices", record=record) |
| 410 | assert decision.allowed is False |
| 411 | |
| 412 | owner = object_permissions.PermissionSubject(user_id="dan") |
| 413 | decision = object_permissions.check_permission( |
| 414 | owner, object_permissions.READ, policy=policy, collection="invoices", record=record) |
| 415 | assert decision.allowed is True |
| 416 | |
| 417 | |
| 418 | def test_portal_token_excluded_from_generic_form_list_and_search_surfaces(): |
| 419 | schema = json.loads((APP_INVOICES / "schemas" / "invoices.json").read_text()) |
| 420 | assert "portal_token" not in schema["forms"]["default"]["fields"] |
| 421 | assert "portal_token" not in schema["views"]["list_fields"] |
| 422 | assert "portal_token" not in schema["search"]["fields"] |
| 423 | by_name = {f["name"]: f for f in schema["fields"]} |
| 424 | assert by_name["portal_token"]["read_only"] is True |