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_delete_hooks.py · 18.4 KB · 427 lines
| 1 | """The pre-write hook runs on DELETE too. |
| 2 | |
| 3 | Before this, `hooks.before_write` gated create and update only: the delete |
| 4 | path ran permissions and nothing else, so a hook's rule that "approved time |
| 5 | is frozen" or "a posted journal is final" simply did not apply to removing |
| 6 | the record. A gate that can be walked round by deleting the evidence is not |
| 7 | a gate. |
| 8 | |
| 9 | The contract a hook sees on delete (docs/validation-and-logic.md): |
| 10 | |
| 11 | {"collection": ..., "action": "delete", |
| 12 | "record": <the row being deleted>, "existing": <the same row>, |
| 13 | "changes": {}, "subject": {...}} |
| 14 | |
| 15 | It may allow (None / {}) or refuse ({"error", "status"}). It may NOT |
| 16 | transform: there is no record to persist, so a hook that answers a delete |
| 17 | with {"record": ...} did not understand the question, and the delete is |
| 18 | refused (fail closed, like every other non-contract answer). |
| 19 | |
| 20 | The second half of this file audits the hooks the packages ship. Every one |
| 21 | was written when only create and update reached it; none may start refusing |
| 22 | a delete by accident, crash on one, or answer one with a transform. |
| 23 | """ |
| 24 | |
| 25 | import importlib.util |
| 26 | import json |
| 27 | import pathlib |
| 28 | |
| 29 | import pytest |
| 30 | |
| 31 | import object_execution |
| 32 | import object_record_changes |
| 33 | import object_records |
| 34 | import object_user_files |
| 35 | import python_object_runtime |
| 36 | from test_object_server import create_identity_session, request |
| 37 | from test_object_user_files import files_env, multipart_body |
| 38 | from test_pre_write_hooks import AUTH, create_gadget, list_gadgets, setup_env |
| 39 | |
| 40 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 41 | PACKAGES = REPO_ROOT / "packages" |
| 42 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 43 | |
| 44 | |
| 45 | def delete_gadget(record_id, headers=AUTH): |
| 46 | return request(f"/collections/gadgets/records/{record_id}", method="DELETE", headers=headers) |
| 47 | |
| 48 | |
| 49 | def recording_hook(path, then="return None"): |
| 50 | """A hook that writes every request it is handed to `path` as JSON lines.""" |
| 51 | return ( |
| 52 | "import json\n" |
| 53 | "def BEFORE_WRITE(request):\n" |
| 54 | f" with open({str(path)!r}, 'a') as handle:\n" |
| 55 | " handle.write(json.dumps(request, sort_keys=True) + '\\n')\n" |
| 56 | f" {then}\n" |
| 57 | ) |
| 58 | |
| 59 | |
| 60 | def recorded(path): |
| 61 | return [json.loads(line) for line in path.read_text().splitlines()] |
| 62 | |
| 63 | |
| 64 | # --- the platform contract ---------------------------------------------------- |
| 65 | |
| 66 | |
| 67 | def test_delete_runs_the_hook_with_the_action_and_the_row_being_deleted(tmp_path, monkeypatch): |
| 68 | log = tmp_path / "hook-requests" |
| 69 | setup_env(tmp_path, monkeypatch, hook_source=recording_hook(log)) |
| 70 | status, _, _ = create_gadget({"id": "g1", "name": "widget", "qty": "5"}) |
| 71 | assert status in (200, 201) |
| 72 | |
| 73 | status, _, payload = delete_gadget("g1") |
| 74 | |
| 75 | assert status == 200 and payload["deleted"] is True |
| 76 | assert list_gadgets() == [] |
| 77 | seen = recorded(log) |
| 78 | assert [entry["action"] for entry in seen] == ["create", "delete"] |
| 79 | on_delete = seen[1] |
| 80 | assert on_delete["collection"] == "gadgets" |
| 81 | assert on_delete["existing"]["id"] == "g1" |
| 82 | assert on_delete["existing"]["name"] == "widget" |
| 83 | assert on_delete["existing"]["qty"] == "5" |
| 84 | # `record` is the row being acted on, which for a delete is the row that |
| 85 | # is about to go: a hook reading request["record"] reads real values. |
| 86 | assert on_delete["record"] == on_delete["existing"] |
| 87 | assert on_delete["changes"] == {} |
| 88 | assert set(on_delete["subject"]) == {"user_id", "roles"} |
| 89 | |
| 90 | |
| 91 | def test_a_hook_can_refuse_a_delete_with_its_own_message_and_status(tmp_path, monkeypatch): |
| 92 | setup_env( |
| 93 | tmp_path, |
| 94 | monkeypatch, |
| 95 | hook_source=( |
| 96 | "def BEFORE_WRITE(request):\n" |
| 97 | " if request['action'] == 'delete' and int(request['existing'].get('qty') or 0) > 0:\n" |
| 98 | " return {'error': 'Stocked gadgets cannot be deleted', 'status': 409}\n" |
| 99 | " return None\n" |
| 100 | ), |
| 101 | ) |
| 102 | assert create_gadget({"id": "g1", "name": "widget", "qty": "5"})[0] in (200, 201) |
| 103 | assert create_gadget({"id": "g2", "name": "spare", "qty": "0"})[0] in (200, 201) |
| 104 | |
| 105 | status, _, payload = delete_gadget("g1") |
| 106 | assert status == 409 |
| 107 | assert payload["code"] == "hook_rejected" |
| 108 | assert payload["error"] == "Stocked gadgets cannot be deleted" |
| 109 | assert [row["id"] for row in list_gadgets()] == ["g1", "g2"] |
| 110 | |
| 111 | # The same hook lets the unstocked one go. |
| 112 | status, _, _ = delete_gadget("g2") |
| 113 | assert status == 200 |
| 114 | assert [row["id"] for row in list_gadgets()] == ["g1"] |
| 115 | |
| 116 | |
| 117 | def test_a_refused_delete_writes_no_change_log_entry(tmp_path, monkeypatch): |
| 118 | data_dir = setup_env( |
| 119 | tmp_path, |
| 120 | monkeypatch, |
| 121 | hook_source=( |
| 122 | "def BEFORE_WRITE(request):\n" |
| 123 | " if request['action'] == 'delete':\n" |
| 124 | " return {'error': 'no', 'status': 409}\n" |
| 125 | ), |
| 126 | ) |
| 127 | assert create_gadget({"id": "g1", "name": "widget"})[0] in (200, 201) |
| 128 | assert delete_gadget("g1")[0] == 409 |
| 129 | changes = object_record_changes.list_record_changes("gadgets", base_dir=data_dir)["changes"] |
| 130 | assert [change["action"] for change in changes] == ["create"] |
| 131 | |
| 132 | |
| 133 | @pytest.mark.parametrize( |
| 134 | "hook_source", |
| 135 | [ |
| 136 | None, # declared, but the object does not exist |
| 137 | "def BEFORE_WRITE(request):\n if request['action'] == 'delete':\n raise RuntimeError('boom')\n", |
| 138 | "def BEFORE_WRITE(request):\n if request['action'] == 'delete':\n return 'nope'\n", |
| 139 | ], |
| 140 | ids=["missing", "raising", "non-contract"], |
| 141 | ) |
| 142 | def test_a_broken_hook_fails_closed_on_delete(tmp_path, monkeypatch, hook_source): |
| 143 | data_dir = setup_env(tmp_path, monkeypatch, hook_source=hook_source) |
| 144 | object_records.create_collection_record( |
| 145 | "gadgets", {"id": "g1", "name": "widget"}, base_dir=data_dir) |
| 146 | |
| 147 | status, _, payload = delete_gadget("g1") |
| 148 | |
| 149 | assert status == 500 |
| 150 | assert payload["code"] == "hook_failed" |
| 151 | assert [row["id"] for row in list_gadgets()] == ["g1"] |
| 152 | |
| 153 | |
| 154 | def test_a_transform_is_not_an_answer_to_a_delete(tmp_path, monkeypatch): |
| 155 | """A hook written for create/update that stamps the record and returns |
| 156 | it has not decided anything about the delete it was asked about. Letting |
| 157 | the delete through would be a gate passing on a misunderstanding.""" |
| 158 | data_dir = setup_env( |
| 159 | tmp_path, |
| 160 | monkeypatch, |
| 161 | hook_source=( |
| 162 | "def BEFORE_WRITE(request):\n" |
| 163 | " record = dict(request['record'])\n" |
| 164 | " record['name'] = record.get('name', '').upper()\n" |
| 165 | " return {'record': record}\n" |
| 166 | ), |
| 167 | ) |
| 168 | object_records.create_collection_record( |
| 169 | "gadgets", {"id": "g1", "name": "widget"}, base_dir=data_dir) |
| 170 | |
| 171 | status, _, payload = delete_gadget("g1") |
| 172 | |
| 173 | assert status == 500 |
| 174 | assert payload["code"] == "hook_failed" |
| 175 | assert [row["name"] for row in list_gadgets()] == ["widget"] |
| 176 | |
| 177 | |
| 178 | def test_a_denied_delete_never_reaches_the_hook(tmp_path, monkeypatch): |
| 179 | log = tmp_path / "hook-requests" |
| 180 | data_dir = setup_env(tmp_path, monkeypatch, hook_source=recording_hook(log)) |
| 181 | object_records.create_collection_record( |
| 182 | "gadgets", {"id": "g1", "name": "widget"}, base_dir=data_dir) |
| 183 | |
| 184 | status, _, _ = delete_gadget("g1", headers=[]) # no admin token |
| 185 | |
| 186 | assert status in (401, 403) |
| 187 | assert not log.exists() |
| 188 | assert [row["id"] for row in list_gadgets()] == ["g1"] |
| 189 | |
| 190 | |
| 191 | def test_deleting_a_missing_record_never_reaches_the_hook(tmp_path, monkeypatch): |
| 192 | log = tmp_path / "hook-requests" |
| 193 | setup_env(tmp_path, monkeypatch, hook_source=recording_hook(log)) |
| 194 | assert delete_gadget("nope")[0] == 404 |
| 195 | assert not log.exists() |
| 196 | |
| 197 | |
| 198 | def test_trusted_server_side_deletes_bypass_hooks(tmp_path, monkeypatch): |
| 199 | log = tmp_path / "hook-requests" |
| 200 | data_dir = setup_env( |
| 201 | tmp_path, monkeypatch, |
| 202 | hook_source=recording_hook(log, then="return {'error': 'would refuse', 'status': 409}")) |
| 203 | object_records.create_collection_record( |
| 204 | "gadgets", {"id": "g1", "name": "widget"}, base_dir=data_dir) |
| 205 | |
| 206 | removed = object_records.delete_collection_record("gadgets", "g1", base_dir=data_dir) |
| 207 | |
| 208 | assert removed["id"] == "g1" |
| 209 | assert not log.exists() |
| 210 | |
| 211 | |
| 212 | def test_a_collection_without_a_hook_deletes_unchanged(tmp_path, monkeypatch): |
| 213 | setup_env(tmp_path, monkeypatch, declare_hook=False) |
| 214 | assert create_gadget({"id": "g1", "name": "widget"})[0] in (200, 201) |
| 215 | status, _, payload = delete_gadget("g1") |
| 216 | assert status == 200 and payload["deleted"] is True |
| 217 | assert list_gadgets() == [] |
| 218 | |
| 219 | |
| 220 | def test_an_update_hook_sees_the_previous_record_beside_the_new_one(tmp_path, monkeypatch): |
| 221 | """`existing` is the stored row before the write, `record` the row as it |
| 222 | would be after, `changes` only what the caller sent -- so a hook can |
| 223 | freeze a field by comparing the two.""" |
| 224 | log = tmp_path / "hook-requests" |
| 225 | setup_env(tmp_path, monkeypatch, hook_source=recording_hook(log)) |
| 226 | assert create_gadget({"id": "g1", "name": "widget", "qty": "5"})[0] in (200, 201) |
| 227 | |
| 228 | status, _, _ = request( |
| 229 | "/collections/gadgets/records/g1", method="PUT", |
| 230 | body=json.dumps({"qty": "9"}).encode("utf-8"), headers=AUTH) |
| 231 | |
| 232 | assert status == 200 |
| 233 | on_update = recorded(log)[1] |
| 234 | assert on_update["action"] == "update" |
| 235 | assert (on_update["existing"]["qty"], on_update["existing"]["name"]) == ("5", "widget") |
| 236 | assert (on_update["record"]["qty"], on_update["record"]["name"]) == ("9", "widget") |
| 237 | assert on_update["changes"] == {"qty": "9"} |
| 238 | |
| 239 | |
| 240 | # --- the other way a record is deleted: a stored file -------------------------- |
| 241 | |
| 242 | |
| 243 | def files_with_hook(tmp_path, monkeypatch, hook_source): |
| 244 | data_dir = files_env(tmp_path, monkeypatch) |
| 245 | schema_file = data_dir / "schemas" / "files.json" |
| 246 | schema = json.loads(schema_file.read_text()) |
| 247 | schema["hooks"] = {"before_write": "hook_files"} |
| 248 | schema_file.write_text(json.dumps(schema)) |
| 249 | hook_dir = tmp_path / "objects" / "hook" |
| 250 | hook_dir.mkdir(parents=True) |
| 251 | (hook_dir / "files.py").write_text(hook_source) |
| 252 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects")) |
| 253 | return data_dir |
| 254 | |
| 255 | |
| 256 | def test_deleting_a_file_runs_the_files_hook_and_a_refusal_keeps_the_bytes(tmp_path, monkeypatch): |
| 257 | """/api/files and WebDAV delete a `files` record through their own |
| 258 | helper, not the collection route. A hook on `files` gates creates there |
| 259 | already; a delete that skipped it would be a second door.""" |
| 260 | data_dir = files_with_hook( |
| 261 | tmp_path, monkeypatch, |
| 262 | "def BEFORE_WRITE(request):\n" |
| 263 | " if request['action'] == 'delete' and request['existing'].get('description') == 'keep':\n" |
| 264 | " return {'error': 'This file is on legal hold', 'status': 409}\n" |
| 265 | " return None\n") |
| 266 | token, _ = create_identity_session({"user_id": "dan"}) |
| 267 | bearer = [("authorization", f"Bearer {token}")] |
| 268 | ids = {} |
| 269 | for name, description in (("held.txt", "keep"), ("loose.txt", "")): |
| 270 | body, content_type = multipart_body( |
| 271 | "file", name, b"file bytes here", extra=[("description", description)]) |
| 272 | status, _, uploaded = request( |
| 273 | "/api/files", method="POST", body=body, |
| 274 | headers=bearer + [("content-type", content_type)]) |
| 275 | assert status == 201, uploaded |
| 276 | ids[name] = uploaded["file"]["id"] |
| 277 | |
| 278 | status, _, payload = request(f"/api/files/{ids['held.txt']}", method="DELETE", headers=bearer) |
| 279 | assert status == 409 |
| 280 | assert payload["code"] == "hook_rejected" |
| 281 | assert object_user_files.read_file("dan", ids["held.txt"], base_dir=data_dir) == b"file bytes here" |
| 282 | assert object_records.get_collection_record("files", ids["held.txt"], base_dir=data_dir) |
| 283 | |
| 284 | status, _, payload = request(f"/api/files/{ids['loose.txt']}", method="DELETE", headers=bearer) |
| 285 | assert status == 200 and payload["deleted"] is True |
| 286 | with pytest.raises(object_user_files.UserFileNotFoundError): |
| 287 | object_user_files.read_file("dan", ids["loose.txt"], base_dir=data_dir) |
| 288 | |
| 289 | |
| 290 | # --- the shipped hooks, asked about a delete ----------------------------------- |
| 291 | # |
| 292 | # Every hook under packages/*/objects/hook/ predates this. Each is asked |
| 293 | # about deleting rows in every state its own gates care about, by the owner |
| 294 | # and by somebody else, with no data directory to read from. The lasting |
| 295 | # invariant is NOT "always allows" -- a later change may teach a hook to |
| 296 | # refuse deleting settled evidence, or any row of an append-only ledger, and |
| 297 | # should -- but that a hook never answers a delete with a crash, a |
| 298 | # transform, or a refusal that was written about something else. |
| 299 | |
| 300 | HOOKS = sorted(PACKAGES.glob("*/objects/hook/*.py")) |
| 301 | |
| 302 | STATES = ("", "draft", "open", "submitted", "approved", "billed", "posted", "confirmed", |
| 303 | "resolved", "received", "shipped", "matched", "bounced") |
| 304 | |
| 305 | |
| 306 | def load_hook(path): |
| 307 | spec = importlib.util.spec_from_file_location(f"audit_hook_{path.stem}", path) |
| 308 | module = importlib.util.module_from_spec(spec) |
| 309 | spec.loader.exec_module(module) |
| 310 | return module |
| 311 | |
| 312 | |
| 313 | def schema_for_hook(path): |
| 314 | """The schema that wires this hook: hook/<name>.py is hook_<name>.""" |
| 315 | hook_id = f"hook_{path.stem}" |
| 316 | for schema_path in (path.parents[2] / "schemas").glob("*.json"): |
| 317 | schema = json.loads(schema_path.read_text()) |
| 318 | if (schema.get("hooks") or {}).get("before_write") == hook_id: |
| 319 | return schema |
| 320 | raise AssertionError(f"no schema in {path.parents[2].name} declares {hook_id}") |
| 321 | |
| 322 | |
| 323 | def plausible_row(schema, status, owner): |
| 324 | row = {} |
| 325 | for field in schema["fields"]: |
| 326 | name, kind = field["name"], str(field.get("type") or "text").lower() |
| 327 | if kind in ("integer", "int", "number", "float", "currency"): |
| 328 | row[name] = "0" |
| 329 | elif kind in ("boolean", "bool"): |
| 330 | row[name] = "true" |
| 331 | elif kind in ("date",): |
| 332 | row[name] = "2026-07-01" |
| 333 | elif kind in ("datetime", "timestamp"): |
| 334 | row[name] = "2026-07-01T09:00:00Z" |
| 335 | else: |
| 336 | row[name] = f"some-{name}" |
| 337 | row.update({"id": "r1", "owner_id": owner}) |
| 338 | if "status" in row: |
| 339 | row["status"] = status |
| 340 | return row |
| 341 | |
| 342 | |
| 343 | def test_there_are_hooks_to_audit(): |
| 344 | # 17 until wallets, scans and app_settings became declarations (unique, |
| 345 | # locked_when) and their hooks were deleted; 13 after usage_events' |
| 346 | # "quantity above zero" became validation.exclusive_min. |
| 347 | assert len(HOOKS) >= 13, [path.name for path in HOOKS] |
| 348 | |
| 349 | |
| 350 | @pytest.mark.parametrize("path", HOOKS, ids=lambda path: f"{path.parents[2].name}/{path.stem}") |
| 351 | def test_no_shipped_hook_crashes_on_transforms_or_wrongly_refuses_a_delete(path, tmp_path, monkeypatch): |
| 352 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "nothing-installed")) |
| 353 | schema = schema_for_hook(path) |
| 354 | hook = load_hook(path) |
| 355 | |
| 356 | for status in STATES: |
| 357 | for owner, actor in (("ann", "ann"), ("ann", "bob")): |
| 358 | row = plausible_row(schema, status, owner) |
| 359 | request_payload = { |
| 360 | "collection": schema["name"], "action": "delete", |
| 361 | "record": dict(row), "existing": dict(row), "changes": {}, |
| 362 | "subject": {"user_id": actor, "roles": ["manager"]}, |
| 363 | } |
| 364 | answer = hook.BEFORE_WRITE(request_payload) # must not raise |
| 365 | where = f"{path.stem}: delete of a {status or 'blank-status'} row by {actor}" |
| 366 | if answer in (None, {}): |
| 367 | continue |
| 368 | assert isinstance(answer, dict), f"{where} answered {answer!r}" |
| 369 | assert answer.get("record") is None, f"{where} answered with a transform" |
| 370 | # A refusal is allowed only as a deliberate delete gate: it must |
| 371 | # be a 409 ("this is settled", or "this ledger is append-only" |
| 372 | # for a collection where no row may ever go) or a 503 (the gate |
| 373 | # could not read what it needs, and nothing is installed here), |
| 374 | # never the 400/403 of a create or update rule misfiring on a |
| 375 | # row that is merely being removed. |
| 376 | assert answer.get("error") and answer.get("status") in (409, 503), ( |
| 377 | f"{where} answered {answer!r}") |
| 378 | |
| 379 | |
| 380 | def test_deleting_an_approved_time_log_is_not_mistaken_for_approving_it(tmp_path, monkeypatch): |
| 381 | """hook_time_logs decides "is this being approved?" from the status the |
| 382 | record would have. Asked about a delete with no guard, it saw an |
| 383 | approved row with no approved `existing` and ran the APPROVAL gate: the |
| 384 | owner was refused with "nobody approves their own hours" (403) and |
| 385 | anybody else got a rate-stamping transform back. Neither is a decision |
| 386 | about a delete.""" |
| 387 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "nothing-installed")) |
| 388 | hook = load_hook(PACKAGES / "app-timers" / "objects" / "hook" / "time_logs.py") |
| 389 | row = {"id": "t1", "status": "approved", "billable": "true", "owner_id": "ann", |
| 390 | "ended_at": "2026-07-01T11:00:00Z", "duration_seconds": "7200", |
| 391 | "amount_cents": "24000", "approved_by": "bob"} |
| 392 | for actor in ("ann", "bob"): |
| 393 | answer = hook.BEFORE_WRITE({ |
| 394 | "collection": "time_logs", "action": "delete", "record": dict(row), |
| 395 | "existing": dict(row), "changes": {}, |
| 396 | "subject": {"user_id": actor, "roles": []}}) |
| 397 | assert answer is None or answer.get("status") == 409, answer |
| 398 | |
| 399 | |
| 400 | def test_deleting_an_approved_expense_is_not_mistaken_for_approving_it(tmp_path, monkeypatch): |
| 401 | """The same misfire in hook_expenses, which shares the shape.""" |
| 402 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "nothing-installed")) |
| 403 | hook = load_hook(PACKAGES / "app-finance" / "objects" / "hook" / "expenses.py") |
| 404 | row = {"id": "e1", "status": "approved", "billable": "true", "owner_id": "ann", |
| 405 | "amount_cents": "5000", "incurred_on": "2026-07-01", "approved_by": "bob"} |
| 406 | for actor in ("ann", "bob"): |
| 407 | answer = hook.BEFORE_WRITE({ |
| 408 | "collection": "expenses", "action": "delete", "record": dict(row), |
| 409 | "existing": dict(row), "changes": {}, |
| 410 | "subject": {"user_id": actor, "roles": []}}) |
| 411 | assert answer is None or answer.get("status") == 409, answer |
| 412 | |
| 413 | |
| 414 | def test_the_time_log_hook_through_the_real_object_runtime_allows_a_draft_delete(tmp_path, monkeypatch): |
| 415 | """One hook driven the way the server drives it (execute_object), so the |
| 416 | audit above is not only a statement about importing the module.""" |
| 417 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "nothing-installed")) |
| 418 | row = {"id": "t1", "status": "draft", "owner_id": "ann"} |
| 419 | result = object_execution.execute_object( |
| 420 | RUNTIME, |
| 421 | object_execution.ObjectExecutionRequest( |
| 422 | "hook_time_logs", method="BEFORE_WRITE", |
| 423 | payload={"collection": "time_logs", "action": "delete", "record": row, |
| 424 | "existing": row, "changes": {}, |
| 425 | "subject": {"user_id": "ann", "roles": []}}), |
| 426 | roots=[PACKAGES / "app-timers" / "objects"]) |
| 427 | assert result.ok and result.result is None |