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_pre_write_hooks.py · 13.5 KB · 388 lines
| 1 | """Pre-write hooks (plan/pre-write-hook-spec.md): a collection declares |
| 2 | `hooks: {"before_write": "<object_id>"}` and that object runs synchronously |
| 3 | inside the generic HTTP write path -- after permission checks, before persist. |
| 4 | It can reject (4xx with its own message) or transform the record. Fail CLOSED: |
| 5 | a declared hook that is missing, raises, or returns a non-contract shape |
| 6 | rejects the write. Trusted server-side writes (object_records called directly) |
| 7 | bypass hooks deliberately. |
| 8 | |
| 9 | This is the escape hatch for logic the schema can't express (cross-field / |
| 10 | cross-collection validation) that keeps the generative form working -- the |
| 11 | form still POSTs to /collections/{c}/records; the hook lives server-side. |
| 12 | """ |
| 13 | |
| 14 | import json |
| 15 | |
| 16 | import pytest |
| 17 | |
| 18 | import object_records |
| 19 | import object_server |
| 20 | from test_object_server import ( |
| 21 | TEST_ADMIN_TOKEN, |
| 22 | enable_admin_token, |
| 23 | request, |
| 24 | write_records, |
| 25 | ) |
| 26 | |
| 27 | AUTH = [("authorization", f"Token {TEST_ADMIN_TOKEN}")] |
| 28 | |
| 29 | SCHEMA = { |
| 30 | "name": "gadgets", |
| 31 | "version": 1, |
| 32 | "fields": [ |
| 33 | {"name": "id"}, |
| 34 | {"name": "name", "type": "text", "required": True}, |
| 35 | {"name": "qty", "type": "integer"}, |
| 36 | {"name": "created_at", "type": "datetime", "read_only": True}, |
| 37 | {"name": "owner_id", "type": "text"}, |
| 38 | ], |
| 39 | } |
| 40 | |
| 41 | |
| 42 | def setup_env(tmp_path, monkeypatch, hook_source=None, declare_hook=True): |
| 43 | data_dir = tmp_path / "data" |
| 44 | objects_root = tmp_path / "objects" |
| 45 | objects_root.mkdir(parents=True, exist_ok=True) |
| 46 | write_records(data_dir, "gadgets", "id\tname\tqty\tcreated_at\towner_id\n") |
| 47 | schema = dict(SCHEMA) |
| 48 | if declare_hook: |
| 49 | schema["hooks"] = {"before_write": "hook_gadgets"} |
| 50 | schema_dir = data_dir / "schemas" |
| 51 | schema_dir.mkdir(parents=True, exist_ok=True) |
| 52 | (schema_dir / "gadgets.json").write_text(json.dumps(schema)) |
| 53 | if hook_source is not None: |
| 54 | hook_dir = objects_root / "hook" |
| 55 | hook_dir.mkdir(parents=True, exist_ok=True) |
| 56 | (hook_dir / "gadgets.py").write_text(hook_source) |
| 57 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 58 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root)) |
| 59 | enable_admin_token(monkeypatch) |
| 60 | return data_dir |
| 61 | |
| 62 | |
| 63 | def create_gadget(record): |
| 64 | return request( |
| 65 | "/collections/gadgets/records", |
| 66 | method="POST", |
| 67 | body=json.dumps(record).encode("utf-8"), |
| 68 | headers=AUTH, |
| 69 | ) |
| 70 | |
| 71 | |
| 72 | def list_gadgets(): |
| 73 | status, _, payload = request("/collections/gadgets/records", headers=AUTH) |
| 74 | assert status == 200 |
| 75 | return payload["records"] |
| 76 | |
| 77 | |
| 78 | def test_collection_without_hook_writes_unchanged(tmp_path, monkeypatch): |
| 79 | setup_env(tmp_path, monkeypatch, declare_hook=False) |
| 80 | status, _, payload = create_gadget({"id": "g1", "name": "widget", "qty": "3"}) |
| 81 | assert status in (200, 201), payload |
| 82 | assert [r["id"] for r in list_gadgets()] == ["g1"] |
| 83 | |
| 84 | |
| 85 | def test_hook_rejects_with_its_own_message_and_status(tmp_path, monkeypatch): |
| 86 | setup_env( |
| 87 | tmp_path, |
| 88 | monkeypatch, |
| 89 | hook_source=( |
| 90 | "def BEFORE_WRITE(request):\n" |
| 91 | " if int(request['record'].get('qty') or 0) > 100:\n" |
| 92 | " return {'error': 'Quantity over 100 needs approval', 'status': 422}\n" |
| 93 | " return None\n" |
| 94 | ), |
| 95 | ) |
| 96 | status, _, payload = create_gadget({"id": "g1", "name": "widget", "qty": "500"}) |
| 97 | assert status == 422 |
| 98 | assert payload["code"] == "hook_rejected" |
| 99 | assert payload["error"] == "Quantity over 100 needs approval" |
| 100 | assert list_gadgets() == [] |
| 101 | |
| 102 | # Under the limit passes through the same hook. |
| 103 | status, _, _ = create_gadget({"id": "g2", "name": "widget", "qty": "5"}) |
| 104 | assert status in (200, 201) |
| 105 | assert [r["id"] for r in list_gadgets()] == ["g2"] |
| 106 | |
| 107 | |
| 108 | @pytest.mark.parametrize("returned,relayed", [ |
| 109 | (409, 409), (422, 422), (499, 499), |
| 110 | # "I could not read what I gate on": something to retry, not a bad request. |
| 111 | (503, 503), |
| 112 | # Anything else a refusing hook says is clamped: it may not call a |
| 113 | # refused write a success, a redirect, or a server fault of its own. |
| 114 | (200, 400), (201, 400), (302, 400), (399, 400), (500, 400), (502, 400), |
| 115 | (504, 400), ("nonsense", 400), (None, 400), |
| 116 | ]) |
| 117 | def test_hook_reject_status_is_a_4xx_or_503(tmp_path, monkeypatch, returned, relayed): |
| 118 | """A gate that could not read its collection answers 503. Relaying only |
| 119 | 4xx turned that into a 400, which tells a client its input was wrong |
| 120 | when the right move is to retry. 503 is the one 5xx a hook may give.""" |
| 121 | setup_env( |
| 122 | tmp_path, |
| 123 | monkeypatch, |
| 124 | hook_source=( |
| 125 | "def BEFORE_WRITE(request):\n" |
| 126 | f" return {{'error': 'no', 'status': {returned!r}}}\n" |
| 127 | ), |
| 128 | ) |
| 129 | status, _, payload = create_gadget({"id": "g1", "name": "widget", "qty": "1"}) |
| 130 | assert status == relayed |
| 131 | assert payload["code"] == "hook_rejected" |
| 132 | assert list_gadgets() == [] |
| 133 | |
| 134 | |
| 135 | def test_hook_transform_persists_and_still_schema_validates(tmp_path, monkeypatch): |
| 136 | setup_env( |
| 137 | tmp_path, |
| 138 | monkeypatch, |
| 139 | hook_source=( |
| 140 | "def BEFORE_WRITE(request):\n" |
| 141 | " record = dict(request['record'])\n" |
| 142 | " record['name'] = record.get('name', '').upper()\n" |
| 143 | " if record.get('qty') == '13':\n" |
| 144 | " record['qty'] = 'thirteen' # invalid for integer field\n" |
| 145 | " return {'record': record}\n" |
| 146 | ), |
| 147 | ) |
| 148 | status, _, _ = create_gadget({"id": "g1", "name": "widget", "qty": "2"}) |
| 149 | assert status in (200, 201) |
| 150 | assert list_gadgets()[0]["name"] == "WIDGET" |
| 151 | |
| 152 | # A transform that violates the schema is still caught by validation. |
| 153 | status, _, payload = create_gadget({"id": "g2", "name": "widget", "qty": "13"}) |
| 154 | assert status == 400 |
| 155 | assert "qty" in payload["error"] |
| 156 | |
| 157 | |
| 158 | def test_hook_cannot_touch_id_owner_or_read_only_fields(tmp_path, monkeypatch): |
| 159 | setup_env( |
| 160 | tmp_path, |
| 161 | monkeypatch, |
| 162 | hook_source=( |
| 163 | "def BEFORE_WRITE(request):\n" |
| 164 | " record = dict(request['record'])\n" |
| 165 | " record['id'] = 'hijacked'\n" |
| 166 | " record['owner_id'] = 'attacker'\n" |
| 167 | " record['created_at'] = '1999-01-01T00:00:00Z'\n" |
| 168 | " return {'record': record}\n" |
| 169 | ), |
| 170 | ) |
| 171 | status, _, _ = create_gadget({"id": "g1", "name": "widget", "qty": "1", "owner_id": "dan"}) |
| 172 | assert status in (200, 201) |
| 173 | rows = list_gadgets() |
| 174 | assert [r["id"] for r in rows] == ["g1"] |
| 175 | assert rows[0]["owner_id"] == "dan" |
| 176 | assert rows[0]["created_at"] != "1999-01-01T00:00:00Z" |
| 177 | |
| 178 | |
| 179 | def test_declared_but_missing_or_raising_hook_fails_closed(tmp_path, monkeypatch): |
| 180 | # Declared, object file absent -> reject, nothing persisted. |
| 181 | setup_env(tmp_path, monkeypatch, hook_source=None) |
| 182 | status, _, payload = create_gadget({"id": "g1", "name": "widget", "qty": "1"}) |
| 183 | assert status == 500 |
| 184 | assert payload["code"] == "hook_failed" |
| 185 | assert list_gadgets() == [] |
| 186 | |
| 187 | |
| 188 | def test_raising_hook_fails_closed(tmp_path, monkeypatch): |
| 189 | setup_env( |
| 190 | tmp_path, |
| 191 | monkeypatch, |
| 192 | hook_source="def BEFORE_WRITE(request):\n raise RuntimeError('boom')\n", |
| 193 | ) |
| 194 | status, _, payload = create_gadget({"id": "g1", "name": "widget", "qty": "1"}) |
| 195 | assert status == 500 |
| 196 | assert payload["code"] == "hook_failed" |
| 197 | assert list_gadgets() == [] |
| 198 | |
| 199 | |
| 200 | def test_non_contract_return_fails_closed(tmp_path, monkeypatch): |
| 201 | setup_env( |
| 202 | tmp_path, |
| 203 | monkeypatch, |
| 204 | hook_source="def BEFORE_WRITE(request):\n return 'nope'\n", |
| 205 | ) |
| 206 | status, _, payload = create_gadget({"id": "g1", "name": "widget", "qty": "1"}) |
| 207 | assert status == 500 |
| 208 | assert payload["code"] == "hook_failed" |
| 209 | |
| 210 | |
| 211 | def test_denied_write_never_reaches_the_hook(tmp_path, monkeypatch): |
| 212 | marker = tmp_path / "hook-ran" |
| 213 | setup_env( |
| 214 | tmp_path, |
| 215 | monkeypatch, |
| 216 | hook_source=( |
| 217 | "def BEFORE_WRITE(request):\n" |
| 218 | f" open({str(marker)!r}, 'w').write('ran')\n" |
| 219 | " return None\n" |
| 220 | ), |
| 221 | ) |
| 222 | # No admin token header -> the write is denied before any hook runs. |
| 223 | status, _, _ = request( |
| 224 | "/collections/gadgets/records", |
| 225 | method="POST", |
| 226 | body=json.dumps({"id": "g1", "name": "widget"}).encode("utf-8"), |
| 227 | ) |
| 228 | assert status in (401, 403) |
| 229 | assert not marker.exists() |
| 230 | |
| 231 | |
| 232 | def test_trusted_server_side_writes_bypass_hooks(tmp_path, monkeypatch): |
| 233 | marker = tmp_path / "hook-ran" |
| 234 | data_dir = setup_env( |
| 235 | tmp_path, |
| 236 | monkeypatch, |
| 237 | hook_source=( |
| 238 | "def BEFORE_WRITE(request):\n" |
| 239 | f" open({str(marker)!r}, 'w').write('ran')\n" |
| 240 | " return {'error': 'would reject'}\n" |
| 241 | ), |
| 242 | ) |
| 243 | stored = object_records.create_collection_record( |
| 244 | "gadgets", |
| 245 | {"id": "sys1", "name": "seeded", "qty": "1"}, |
| 246 | base_dir=data_dir, |
| 247 | ) |
| 248 | assert stored["id"] == "sys1" |
| 249 | assert not marker.exists() |
| 250 | |
| 251 | |
| 252 | def test_update_path_runs_hook_with_existing_and_action(tmp_path, monkeypatch): |
| 253 | setup_env( |
| 254 | tmp_path, |
| 255 | monkeypatch, |
| 256 | hook_source=( |
| 257 | "def BEFORE_WRITE(request):\n" |
| 258 | " if request['action'] != 'update':\n" |
| 259 | " return None\n" |
| 260 | " before = int(request['existing'].get('qty') or 0)\n" |
| 261 | " after = int(request['record'].get('qty') or 0)\n" |
| 262 | " if after < before:\n" |
| 263 | " return {'error': 'Quantity can only grow', 'status': 409}\n" |
| 264 | " record = dict(request['record'])\n" |
| 265 | " record['name'] = record.get('name', '') + '-checked'\n" |
| 266 | " return {'record': record}\n" |
| 267 | ), |
| 268 | ) |
| 269 | status, _, _ = create_gadget({"id": "g1", "name": "widget", "qty": "5"}) |
| 270 | assert status in (200, 201) |
| 271 | |
| 272 | # Shrinking qty is rejected by the hook with its own status. |
| 273 | status, _, payload = request( |
| 274 | "/collections/gadgets/records/g1", |
| 275 | method="PUT", |
| 276 | body=json.dumps({"qty": "2"}).encode("utf-8"), |
| 277 | headers=AUTH, |
| 278 | ) |
| 279 | assert status == 409 |
| 280 | assert payload["code"] == "hook_rejected" |
| 281 | assert list_gadgets()[0]["qty"] == "5" |
| 282 | |
| 283 | # Growing qty passes and the hook's transform lands on the stored row. |
| 284 | status, _, _ = request( |
| 285 | "/collections/gadgets/records/g1", |
| 286 | method="PUT", |
| 287 | body=json.dumps({"qty": "9"}).encode("utf-8"), |
| 288 | headers=AUTH, |
| 289 | ) |
| 290 | assert status == 200 |
| 291 | row = list_gadgets()[0] |
| 292 | assert row["qty"] == "9" |
| 293 | assert row["name"] == "widget-checked" |
| 294 | |
| 295 | |
| 296 | # --------------------------------------------------------------------- |
| 297 | # First adopter: fin_journals balance enforcement (packages/app-finance). |
| 298 | # Cross-collection validation the schema can't express -- the canonical |
| 299 | # reason this primitive exists. |
| 300 | # --------------------------------------------------------------------- |
| 301 | |
| 302 | import pathlib |
| 303 | |
| 304 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 305 | FINANCE = REPO_ROOT / "packages" / "app-finance" |
| 306 | |
| 307 | |
| 308 | def setup_finance(tmp_path, monkeypatch): |
| 309 | data_dir = tmp_path / "data" |
| 310 | write_records( |
| 311 | data_dir, |
| 312 | "fin_journals", |
| 313 | "id\tdate\tdescription\tstatus\towner_id\tcreated_at\n" |
| 314 | "j1\t2026-07-01\tOpening entry\tdraft\tadmin\t\n", |
| 315 | ) |
| 316 | write_records( |
| 317 | data_dir, |
| 318 | "fin_journal_lines", |
| 319 | "id\tjournal_id\taccount_id\tdebit_cents\tcredit_cents\towner_id\n", |
| 320 | ) |
| 321 | # account_id is a validated relation -> the target record must exist. |
| 322 | write_records(data_dir, "fin_accounts", "id\tname\na1\tCash\n") |
| 323 | schema_dir = data_dir / "schemas" |
| 324 | schema_dir.mkdir(parents=True, exist_ok=True) |
| 325 | for name in ("fin_journals", "fin_journal_lines"): |
| 326 | (schema_dir / f"{name}.json").write_text( |
| 327 | (FINANCE / "schemas" / f"{name}.json").read_text() |
| 328 | ) |
| 329 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 330 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(FINANCE / "objects")) |
| 331 | enable_admin_token(monkeypatch) |
| 332 | return data_dir |
| 333 | |
| 334 | |
| 335 | def post_journal(): |
| 336 | return request( |
| 337 | "/collections/fin_journals/records/j1", |
| 338 | method="PUT", |
| 339 | body=json.dumps({"status": "posted"}).encode("utf-8"), |
| 340 | headers=AUTH, |
| 341 | ) |
| 342 | |
| 343 | |
| 344 | def add_line(data_dir, line_id, debit, credit): |
| 345 | object_records.create_collection_record( |
| 346 | "fin_journal_lines", |
| 347 | {"id": line_id, "journal_id": "j1", "account_id": "a1", |
| 348 | "debit_cents": str(debit), "credit_cents": str(credit)}, |
| 349 | base_dir=data_dir, |
| 350 | ) |
| 351 | |
| 352 | |
| 353 | def test_fin_journal_cannot_post_empty(tmp_path, monkeypatch): |
| 354 | setup_finance(tmp_path, monkeypatch) |
| 355 | status, _, payload = post_journal() |
| 356 | assert status == 409 |
| 357 | assert payload["code"] == "hook_rejected" |
| 358 | assert "empty journal" in payload["error"] |
| 359 | |
| 360 | |
| 361 | def test_fin_journal_cannot_post_unbalanced_but_posts_balanced(tmp_path, monkeypatch): |
| 362 | data_dir = setup_finance(tmp_path, monkeypatch) |
| 363 | add_line(data_dir, "l1", 1000, 0) |
| 364 | add_line(data_dir, "l2", 0, 900) |
| 365 | |
| 366 | status, _, payload = post_journal() |
| 367 | assert status == 409 |
| 368 | assert "debits 1000 != credits 900" in payload["error"] |
| 369 | # still draft |
| 370 | status, _, row = request("/collections/fin_journals/records/j1", headers=AUTH) |
| 371 | assert row["record"]["status"] == "draft" |
| 372 | |
| 373 | add_line(data_dir, "l3", 0, 100) |
| 374 | status, _, _ = post_journal() |
| 375 | assert status == 200 |
| 376 | status, _, row = request("/collections/fin_journals/records/j1", headers=AUTH) |
| 377 | assert row["record"]["status"] == "posted" |
| 378 | |
| 379 | |
| 380 | def test_fin_journal_draft_edits_pass_the_hook_untouched(tmp_path, monkeypatch): |
| 381 | setup_finance(tmp_path, monkeypatch) |
| 382 | status, _, _ = request( |
| 383 | "/collections/fin_journals/records/j1", |
| 384 | method="PUT", |
| 385 | body=json.dumps({"description": "renamed"}).encode("utf-8"), |
| 386 | headers=AUTH, |
| 387 | ) |
| 388 | assert status == 200 |